@bubo-squared/gyroview 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +1 -1
- package/dist/packages/adapters/mediabunny/src/MediabunnyCodecReader.js +8 -2
- package/dist/packages/adapters/three/src/ThreeFrameRenderer.js +32 -13
- package/dist/packages/adapters/three/src/drawSchedules.js +13 -0
- package/dist/packages/adapters/three/src/index.js +1 -0
- package/dist/packages/core/src/application/download/FileDownload.js +17 -6
- package/dist/packages/core/src/application/download/SampleCursor.js +4 -4
- package/dist/packages/core/src/application/download/Transfers.js +7 -0
- package/dist/packages/core/src/domain/download/DownloadPolicy.js +10 -1
- package/dist/packages/core/src/domain/format/records/gyro/SampleColumns.js +9 -2
- package/dist/packages/core/src/domain/motion/gyro/GyroTrack.js +14 -4
- package/dist/packages/core/src/domain/motion/orientation/OrientationTrack.js +2 -2
- package/dist/packages/core/src/domain/motion/orientation/estimateGyroBias.js +9 -1
- package/dist/packages/core/src/shared/binary/ByteReader.js +6 -1
- package/dist/packages/core/src/shared/math/Quaternion.js +1 -1
- package/dist/packages/core/src/shared/math/Vector3.js +5 -1
- package/dist/packages/player/src/composition/AnimationFrameDraws.js +38 -0
- package/dist/packages/player/src/composition/animationFrames.js +9 -0
- package/dist/packages/player/src/composition/buildPipeline.js +4 -2
- package/dist/packages/player/src/player/FrameLoop.js +1 -6
- package/dist/standalone.js +58 -59
- package/package.json +3 -3
package/dist/standalone.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
/*! @bubo-squared/gyroview (MIT). Bundles three.js (MIT, https://github.com/mrdoob/three.js) and
|
|
2
2
|
mediabunny (MPL-2.0, source at https://github.com/Vanilagy/mediabunny). */
|
|
3
|
-
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e=>e,n=e=>e,r=90,i=180,a=360,o=t(r),s=t(i),c=t(a),l=e=>n(e*Math.PI/i),u=e=>t(e*i/Math.PI);function d(e){let n=e%c;return n>s&&(n-=c),n<=-s&&(n+=c),t(n)}var f={EdgeRadius:0,CenterX:1,CenterY:2,Yaw:3,Pitch:4,Roll:5},p={EdgeRadius:0,CenterX:1,CenterY:2,Yaw:3,Pitch:4,Roll:5,TranslationX:6,TranslationY:7,TranslationZ:8,C1:9,C2:10,C3:11,C4:12,CanvasWidth:13,CanvasHeight:14,LensType:15},m={Xi:0,FocalX:1,FocalY:2,CenterX:3,CenterY:4,Yaw:5,Pitch:6,Roll:7,TranslationX:8,TranslationY:9,TranslationZ:10},h={K1:11,K2:12,K3:13,P1:14,P2:15,CanvasWidth:16,CanvasHeight:17,LensType:18},g={K1:11,K2:12,K3:13,K4:14,K5:15,P1:16,P2:17,P3:18,P4:19,S1:20,S2:21,S3:22,S4:23,CanvasWidth:24,CanvasHeight:25,LensType:26},_={CanvasWidth:0,CanvasHeight:1,VersionWord:2};function v(e,n,r){return{yaw:t(e),pitch:t(n),roll:t(r)}}function y(e,t){let n=e>>>16;return n===t?void 0:`declares version ${n}`}function b(e,t,n){let[r]=e;return r?{width:r(t),height:r(n)}:x}var x={width:0,height:0};function S(e){let[t,r,i]=e,a=Math.hypot(t,r);return{theta:n(Math.atan2(a,i)),radialUnit:a===0?[0,0]:[t/a,r/a]}}function C(e,t,n){return{x:e.x+t*n[0],y:e.y+t*n[1]}}var w=l(t(100)),T=l(t(96)),E=class{parameters;kind=`equidistant`;halfFieldOfView=w;principalPoint;constructor(e){this.parameters=e,this.principalPoint=e.principalPoint}get projection(){return{kind:`radial-polynomial`,principalPoint:this.principalPoint,coefficients:[this.pixelsPerRadian,0,0,0]}}project(e){let{theta:t,radialUnit:n}=S(e);return t>this.halfFieldOfView?void 0:C(this.principalPoint,this.pixelsPerRadian*t,n)}get pixelsPerRadian(){return this.parameters.edgeRadius/this.parameters.radiusAngle}},D={Legacy:1,Polynomial:2,Mei:3,ExtendedMei:6},O={version:D.Legacy,lensTokens:6,trailingTokens:3,radialScale:1,parseLens(e,t){return{lensIndex:t,model:new E({edgeRadius:e(f.EdgeRadius),radiusAngle:T,principalPoint:{x:e(f.CenterX),y:e(f.CenterY)}}),orientation:v(e(f.Yaw),e(f.Pitch),e(f.Roll)),translation:[0,0,0]}},canvasOf(e){let t=1+(e[0]??0)*6;return{width:e[t+_.CanvasWidth]??0,height:e[t+_.CanvasHeight]??0}}},ee=/* @__PURE__ */ `binary-out-of-bounds.binary-unsafe-integer.codec-unsupported.cors.decode.embed-destroyed.index-out-of-range.invalid-argument.invalid-byte-range.invalid-calibration.invalid-protobuf.invalid-trailer.invariant-violation.missing-second-file.no-calibration.no-info-record.no-key-frame.playback-blocked.range-unsupported.render-unavailable.source-changed.source-truncated.source-unreadable.unsupported-calibration.unsupported-container.unsupported-gyro-record.unsupported-info-format.unsupported-layout.webcodecs-unavailable`.split(`.`),k=[`browser`,`recording`,`source`,`usage`,`internal`],te={"binary-out-of-bounds":`recording`,"binary-unsafe-integer":`recording`,"codec-unsupported":`browser`,cors:`source`,decode:`browser`,"embed-destroyed":`usage`,"index-out-of-range":`internal`,"invalid-argument":`usage`,"invalid-byte-range":`recording`,"invalid-calibration":`recording`,"invalid-protobuf":`recording`,"invalid-trailer":`recording`,"invariant-violation":`internal`,"missing-second-file":`recording`,"no-calibration":`recording`,"no-info-record":`recording`,"no-key-frame":`recording`,"playback-blocked":`browser`,"range-unsupported":`source`,"render-unavailable":`browser`,"source-changed":`source`,"source-truncated":`source`,"source-unreadable":`source`,"unsupported-calibration":`recording`,"unsupported-container":`recording`,"unsupported-gyro-record":`recording`,"unsupported-info-format":`recording`,"unsupported-layout":`recording`,"webcodecs-unavailable":`browser`};function ne(e){return typeof e==`string`&&ee.includes(e)}var A=class extends Error{code;category;constructor(e,t,n){super(t,n),this.code=e,this.name=`GyroViewError`,this.category=te[e]}};function re(e,t,n){return e instanceof A?e:new A(t,n,{cause:e})}function ie(e){return e instanceof Error&&e.name===`AbortError`}function ae(e,t){return e instanceof A&&e.code===t}function oe(e){return e instanceof Error?e.message:String(e)}function j(e,t){if(!e)throw new A(`invariant-violation`,t)}function se(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>=t)throw new A(`index-out-of-range`,`${n} index ${e} is outside 0..${t-1}`)}var ce={radial:5,tangential:2,thinPrism:2};function le(e){ue(`radial`,e.radial.length),ue(`tangential`,e.tangential.length),ue(`thinPrism`,e.thinPrism.length)}function ue(e,t){let n=ce[e];j(t<=n,`a Mei distortion has ${t} ${e} terms, more than the ${n} a string carries`)}function de(e,t){let[n,r]=t,i=n*n+r*r,a=1+i*fe(i,e.radial,e=>e),o=fe(i,e.tangential,e=>e.p1),s=fe(i,e.tangential,e=>e.p2),c=i*fe(i,e.thinPrism,e=>e.x),l=i*fe(i,e.thinPrism,e=>e.y);return[a*n+2*o*n*r+s*(i+2*n*n)+c,a*r+o*(i+2*r*r)+2*s*n*r+l]}function fe(e,t,n){return t.reduceRight((t,r)=>t*e+n(r),0)}var pe=class{parameters;kind=`mei`;halfFieldOfView=w;principalPoint;constructor(e){this.parameters=e,le(e.distortion),this.principalPoint=e.principalPoint}get projection(){return{kind:`mei`,...this.parameters}}project(e){let[t,n,r]=e,i=r+this.parameters.xi;if(i<=0||Math.atan2(Math.hypot(t,n),r)>this.halfFieldOfView)return;let[a,o]=de(this.parameters.distortion,[t/i,n/i]);return{x:this.parameters.focal[0]*a+this.principalPoint.x,y:this.parameters.focal[1]*o+this.principalPoint.y}}},me=({radial:e,tangential:t})=>{let[n,r]=t;return{radial:e,tangential:[{p1:n,p2:r}],thinPrism:[]}};function he(e){return{version:e.version,lensTokens:e.lensTokens,trailingTokens:1,radialScale:e.radialScale,versionWordProblem:t=>y(t,e.version),parseLens:(t,n)=>ge(t,n,e),canvasOf:(t,n)=>b(n,e.canvasTokens.width,e.canvasTokens.height)}}function ge(e,t,n){return{lensIndex:t,model:new pe({xi:e(m.Xi),focal:[e(m.FocalX),e(m.FocalY)],principalPoint:{x:e(m.CenterX),y:e(m.CenterY)},distortion:n.distortionOf(e)}),orientation:v(e(m.Yaw),e(m.Pitch),e(m.Roll)),translation:[e(m.TranslationX),e(m.TranslationY),e(m.TranslationZ)]}}var _e=he({version:D.Mei,lensTokens:19,canvasTokens:{width:h.CanvasWidth,height:h.CanvasHeight},distortionOf:e=>({radial:[e(h.K1),e(h.K2),e(h.K3)],tangential:[{p1:e(h.P1),p2:e(h.P2)}],thinPrism:[]}),radialScale:1}),ve=1.008;function ye(e){return he({version:D.ExtendedMei,lensTokens:27,canvasTokens:{width:g.CanvasWidth,height:g.CanvasHeight},distortionOf:t=>e(xe(t)),radialScale:ve})}var be=ye(me);function xe(e){return{radial:[e(g.K1),e(g.K2),e(g.K3),e(g.K4),e(g.K5)],tangential:[e(g.P1),e(g.P2),e(g.P3),e(g.P4)],thinPrism:[e(g.S1),e(g.S2),e(g.S3),e(g.S4)]}}var Se=class{parameters;kind=`polynomial`;halfFieldOfView=w;principalPoint;scale;constructor(e){this.parameters=e,this.principalPoint=e.principalPoint,this.scale=e.edgeRadius/this.polynomial(this.halfFieldOfView)}get projection(){let[e,t,n,r]=this.parameters.coefficients;return{kind:`radial-polynomial`,principalPoint:this.principalPoint,coefficients:[e*this.scale,t*this.scale,n*this.scale,r*this.scale]}}project(e){let{theta:t,radialUnit:n}=S(e);return t>this.halfFieldOfView?void 0:C(this.principalPoint,this.scale*this.polynomial(t),n)}polynomial(e){let[t,n,r,i]=this.parameters.coefficients;return e*(t+e*(n+e*(r+e*i)))}},Ce={version:D.Polynomial,lensTokens:16,trailingTokens:1,radialScale:1,versionWordProblem:e=>y(e,D.Polynomial),parseLens(e,t){return{lensIndex:t,model:new Se({edgeRadius:e(p.EdgeRadius),principalPoint:{x:e(p.CenterX),y:e(p.CenterY)},coefficients:[e(p.C1),e(p.C2),e(p.C3),e(p.C4)]}),orientation:v(e(p.Yaw),e(p.Pitch),e(p.Roll)),translation:[e(p.TranslationX),e(p.TranslationY),e(p.TranslationZ)]}},canvasOf(e,t){return b(t,p.CanvasWidth,p.CanvasHeight)}},we=`_`,Te=[O,Ce,_e,be];function M(e,t=Te){let n=e.split(we).map(e=>ke(e)),r=n[0]??0,i=De(t,n);Oe(i,n.at(-1)??0);let a=Array.from({length:r},(e,t)=>N(n,1+t*i.lensTokens));return{version:i.version,canvas:i.canvasOf(n,a),lenses:a.map((e,t)=>i.parseLens(e,t)),radialScale:i.radialScale}}function Ee(e,t,n){return 1+e*t+n}function De(e,t){let n=t[0]??0,r=e.find(e=>t.length===Ee(n,e.lensTokens,e.trailingTokens));if(r)return r;throw new A(`invalid-calibration`,`calibration string has ${t.length} tokens for ${n} lenses, matching no known layout`)}function Oe(e,t){let n=e.versionWordProblem?.(t);if(n!==void 0)throw new A(`invalid-calibration`,`calibration string has the v${e.version} layout but ${n}`)}function N(e,t){return n=>e[t+n]??NaN}function ke(e){let t=Number(e);if(e.trim()===``||!Number.isFinite(t))throw new A(`invalid-calibration`,`calibration token "${e}" is not a finite number`);return t}var P={SerialNumber:1,Model:2,Firmware:3,Offset:5,Dimension:19,FrameRate:20,CaptureMode:22,FirstFrameTimestamp:24,RollingShutterTimeMs:25,FileGroupInfo:26,WindowCropInfo:27,GyroTimestampMs:28,HasGyroTimestamp:29,TotalFrames:40,IsFlowstateOnline:42,GyroType:51,OffsetV2:53,OffsetV3:54,IsRawGyro:62,PtsType:64,GyroConfig:65,FileLayout:79,TrackOrder:80,OffsetV6:111},Ae={Width:1,Height:2},je={AccelerometerRangeG:1,GyroscopeRangeDps:2},Me={SensorWidth:1,SensorHeight:2,CropWidth:3,CropHeight:4,CropOffsetX:5,CropOffsetY:6},Ne={TrackTimestamps:1,ExposureRecord:2},Pe={SplitFiles:1,MultiTrack:2},Fe={Stream10First:1,Stream00First:2},Ie={offset:{field:P.Offset,name:`offset`},offsetV2:{field:P.OffsetV2,name:`offset_v2`},offsetV3:{field:P.OffsetV3,name:`offset_v3`},offsetV6:{field:P.OffsetV6,name:`offset_v6`}},Le=/* @__PURE__ */ new Set([`invalid-calibration`,`unsupported-calibration`]),Re=[`offset`,`offsetV6`,`offsetV3`,`offsetV2`];function ze(e){let t=[];for(let n of Be(e)){if(`calibration`in n)return{calibration:n.calibration,warnings:t};t.push(n.warning)}return{calibration:void 0,warnings:t}}function*Be(e){for(let t of Re){let n=e[t];n!==void 0&&(yield Ve(Ie[t],n))}}function Ve({name:e},t){try{return{calibration:M(t)}}catch(t){if(t instanceof A&&Le.has(t.code))return{warning:`${e} skipped: ${t.message}`};throw t}}var He={Index:0,Info:1,Thumbnail:2,Gyro:3,Exposure:4,ThumbnailExtended:5,FrameTimestamps:6,Gps:7},Ue={Protobuf:1,Json:2},We=1,Ge=2,Ke=4,qe=8,Je=4,Ye=8,Xe=8,Ze=!0,Qe=!1,$e=class{bytes;view;constructor(e){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}get length(){return this.bytes.byteLength}uint8At(e){return this.ensureAvailable(e,We),this.view.getUint8(e)}uint16LeAt(e){return this.ensureAvailable(e,Ge),this.view.getUint16(e,Ze)}uint32LeAt(e){return this.ensureAvailable(e,Ke),this.view.getUint32(e,Ze)}uint32BeAt(e){return this.ensureAvailable(e,Ke),this.view.getUint32(e,Qe)}int32BeAt(e){return this.ensureAvailable(e,Je),this.view.getInt32(e,Qe)}uint64LeAt(e){return this.ensureAvailable(e,qe),this.toSafeNumber(this.view.getBigUint64(e,Ze),e)}uint64BeAt(e){return this.ensureAvailable(e,qe),this.toSafeNumber(this.view.getBigUint64(e,Qe),e)}int64BeAt(e){return this.ensureAvailable(e,Ye),this.toSafeNumber(this.view.getBigInt64(e,Qe),e)}float64LeAt(e){return this.ensureAvailable(e,Xe),this.view.getFloat64(e,Ze)}bytesAt(e,t){return this.ensureAvailable(e,t),this.bytes.subarray(e,e+t)}asciiAt(e,t){return Array.from(this.bytesAt(e,t),e=>String.fromCodePoint(e)).join(``)}toSafeNumber(e,t){if(!(e>=BigInt(-(2**53-1))&&e<=BigInt(2**53-1)))throw new A(`binary-unsafe-integer`,`64-bit integer at offset ${t} (${e.toString()}) exceeds the safe integer range`);return Number(e)}ensureAvailable(e,t){if(e<0||t<0||e+t>this.bytes.byteLength)throw new A(`binary-out-of-bounds`,`read of ${t} byte(s) at offset ${e} exceeds ${this.bytes.byteLength} available`)}};function et(e){let t;return()=>(t??={value:e()}).value}var tt=et(()=>new globalThis.TextDecoder(`utf8`));function nt(e){return tt().decode(e)}var rt={Varint:0,Fixed64:1,LengthDelimited:2,Fixed32:5},it=BigInt(7),at=BigInt(127),ot=BigInt(2**53-1),st=class e{decoded;constructor(e){this.decoded=e}static decode(t){let n=new ct(t),r=[];for(;!n.atEnd;)r.push(n.readField());return new e(r)}varint(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`varint`)throw this.wrongType(e,`varint`,t.kind);if(t.value>ot)throw new A(`binary-unsafe-integer`,`field ${e} holds ${t.value.toString()}, beyond the safe integer range`);return Number(t.value)}}boolean(e){let t=this.varint(e);return t===void 0?void 0:t!==0}double(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`fixed64`)throw this.wrongType(e,`fixed64`,t.kind);return new $e(t.bytes).float64LeAt(0)}}bytes(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`bytes`)throw this.wrongType(e,`bytes`,t.kind);return t.bytes}}string(e){let t=this.bytes(e);return t===void 0?void 0:nt(t)}message(t){let n=this.bytes(t);return n===void 0?void 0:e.decode(n)}valueOf(e){return this.decoded.findLast(t=>t.number===e)?.value}wrongType(e,t,n){return new A(`invalid-protobuf`,`field ${e} is encoded as ${n}, expected ${t}`)}},ct=class{bytes;position=0;reader;constructor(e){this.bytes=e,this.reader=new $e(e)}get atEnd(){return this.position>=this.bytes.byteLength}readField(){let e=this.readVarint(),t=Number(e>>BigInt(3)),n=Number(e&BigInt(7));return{number:t,value:this.readValue(n,t)}}readValue(e,t){switch(e){case rt.Varint:return{kind:`varint`,value:this.readVarint()};case rt.Fixed64:return{kind:`fixed64`,bytes:this.readBytes(8)};case rt.Fixed32:return{kind:`fixed32`,bytes:this.readBytes(4)};case rt.LengthDelimited:return{kind:`bytes`,bytes:this.readBytes(this.readLength())};default:throw new A(`invalid-protobuf`,`field ${t} uses unsupported wire type ${e}`)}}readVarint(){let e=0n,t=0n;for(let n=0;n<10;n+=1){let n=this.readByte();if(e|=(BigInt(n)&at)<<t,!(n&128))return e;t+=it}throw new A(`invalid-protobuf`,`varint longer than 10 bytes at byte ${this.position}`)}readLength(){let e=this.readVarint();if(e>BigInt(this.bytes.byteLength))throw new A(`invalid-protobuf`,`length ${e.toString()} exceeds the message at byte ${this.position}`);return Number(e)}readByte(){this.ensureRemaining(1);let e=this.reader.uint8At(this.position);return this.position+=1,e}readBytes(e){this.ensureRemaining(e);let t=this.reader.bytesAt(this.position,e);return this.position+=e,t}ensureRemaining(e){if(this.position+e>this.bytes.byteLength)throw new A(`invalid-protobuf`,`message truncated at byte ${this.position}`)}};function lt(e,t){let n=Object.entries(e).map(([e,n])=>[e,t(n,e)]);return Object.fromEntries(n)}var ut=1e6,dt=1e3,ft=1e3,pt=e=>e,mt=e=>e,F=e=>e,ht=e=>F(e/ut),gt=e=>pt(e*ft),_t=e=>F(e/dt),vt=e=>pt(e*ut);function yt(e,t){if(t!==Ue.Protobuf)throw new A(`unsupported-info-format`,`info record uses format ${t}; only protobuf (${Ue.Protobuf}) is supported`);let n=st.decode(e);return{serialNumber:n.string(P.SerialNumber),model:n.string(P.Model),firmware:n.string(P.Firmware),calibration:Et(n),dimension:Dt(n.message(P.Dimension)),frameRate:n.varint(P.FrameRate),captureMode:n.string(P.CaptureMode),firstFrameTimestamp:n.varint(P.FirstFrameTimestamp),readoutTime:bt(n.double(P.RollingShutterTimeMs)),windowCrop:Ot(n.message(P.WindowCropInfo)),gyroOffset:xt(n),gyroType:n.varint(P.GyroType),isRawGyro:n.boolean(P.IsRawGyro),preferredFrameTimeSource:Ct(n.varint(P.PtsType)),sensorRanges:kt(n.message(P.GyroConfig)),fileLayout:wt(n.varint(P.FileLayout)),trackOrder:Tt(n.varint(P.TrackOrder))}}function bt(e){return e===void 0?void 0:_t(mt(e))}function xt(e){return e.boolean(P.HasGyroTimestamp)===!0?St(e.double(P.GyroTimestampMs)):void 0}function St(e){return e===void 0?void 0:mt(e)}function Ct(e){return e===Ne.TrackTimestamps?`track-timestamps`:e===Ne.ExposureRecord?`exposure-record`:void 0}function wt(e){return e===Pe.SplitFiles?`split-files`:e===Pe.MultiTrack?`multi-track`:void 0}function Tt(e){return e===Fe.Stream10First?`stream-10-first`:e===Fe.Stream00First?`stream-00-first`:void 0}function Et(e){return lt(Ie,t=>e.string(t.field))}function Dt(e){let t=e?.varint(Ae.Width),n=e?.varint(Ae.Height);return t===void 0||n===void 0?void 0:{width:t,height:n}}function Ot(e){return e===void 0?void 0:{sensorWidth:e.varint(Me.SensorWidth),sensorHeight:e.varint(Me.SensorHeight),cropWidth:e.varint(Me.CropWidth),cropHeight:e.varint(Me.CropHeight),cropOffsetX:e.varint(Me.CropOffsetX),cropOffsetY:e.varint(Me.CropOffsetY)}}function kt(e){return e===void 0?void 0:{accelerometerG:e.varint(je.AccelerometerRangeG),gyroscopeDps:e.varint(je.GyroscopeRangeDps)}}async function At(e,t){let n=t.locationOf(He.Info);if(!n)throw new A(`no-info-record`,`the trailer has no info record; the file is not a camera recording`);return yt(await e.read(n.payload),n.format)}var jt=class e{captureTimeStore;shutterTimeStore;constructor(e,t){this.captureTimeStore=e,this.shutterTimeStore=t,j(e.length===t.length,`exposure record arrays disagree on the entry count`)}get length(){return this.captureTimeStore.length}get captureTimes(){return this.captureTimeStore}get shutterTimes(){return this.shutterTimeStore}entryAt(e){return se(e,this.length,`exposure entry`),{captureTime:pt(this.captureTimeStore[e]??0),shutterTime:F(this.shutterTimeStore[e]??0)}}indexAtOrAfter(e){let t=0,n=this.captureTimeStore.length;for(;t<n;){let r=t+n>>>1;(this.captureTimeStore[r]??1/0)<e?t=r+1:n=r}return t}slice(t,n){return j(t>=0&&n>=0&&t+n<=this.length,`exposure slice out of range`),new e(this.captureTimeStore.slice(t,t+n),this.shutterTimeStore.slice(t,t+n))}},Mt=60;function Nt(e,t){try{return Pt(e,t)}catch(e){if(ae(e,`binary-unsafe-integer`))return;throw e}}function Pt(e,t){let n=Math.floor(e.byteLength/16),r=new $e(e),i=new Float64Array(n),a=new Float64Array(n);for(let e=0;e<n;e+=1){let n=e*16;i[e]=t(r.uint64LeAt(n+0)),a[e]=r.float64LeAt(n+8)}return Ft(i)&&a.every(e=>It(e))?new jt(i,a):void 0}function Ft(e){return e.every((t,n)=>n===0||t>=(e[n-1]??t))}function It(e){return e>=0&&e<=Mt}var Lt=32768,Rt=32768,zt=[Rt,Rt/2],Bt=2e3,Vt=class{name=`float`;sampleSize=56;flipSteps={acceleration:[],angularVelocity:[]};captureTimeOf(e){return gt(mt(e))}timestampAt(e,t){return this.captureTimeOf(e.uint64LeAt(t+0))}accelerationAt(e,t){return this.vectorAt(e,t+8)}angularVelocityAt(e,t){return this.vectorAt(e,t+32)}vectorAt(e,t){return[e.float64LeAt(t),e.float64LeAt(t+8),e.float64LeAt(t+16)]}},Ht=class{name=`raw`;sampleSize=20;flipSteps;accelerationScale;angularVelocityScale;constructor(e={}){let n=Ut(e.accelerometerG,16),r=Ut(e.gyroscopeDps,Bt);this.accelerationScale=n/Rt,this.angularVelocityScale=l(t(r))/Rt,this.flipSteps={acceleration:zt.map(e=>e*this.accelerationScale),angularVelocity:zt.map(e=>e*this.angularVelocityScale)}}captureTimeOf(e){return pt(e)}timestampAt(e,t){return this.captureTimeOf(e.uint64LeAt(t+0))}accelerationAt(e,t){return this.vectorAt(e,t+8,this.accelerationScale)}angularVelocityAt(e,t){return this.vectorAt(e,t+14,this.angularVelocityScale)}vectorAt(e,t,n){return[this.componentAt(e,t,n),this.componentAt(e,t+2,n),this.componentAt(e,t+4,n)]}componentAt(e,t,n){return(e.uint16LeAt(t)-Lt)*n}};function Ut(e,t){return e!==void 0&&e>0?e:t}var Wt=[0,0,0];function Gt(e){return Math.hypot(e[0],e[1],e[2])}function Kt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function qt(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Jt(e){return e.every(e=>Number.isFinite(e))}function Yt(e,t){return[e[0]+t[0],e[1]+t[1],e[2]+t[2]]}function Xt(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function Zt(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Qt(e,t,n){return Yt(e,Zt(Xt(t,e),n))}var $t=class{captureTimeStore;accelerationStore;angularVelocityStore;constructor(e,t,n){this.captureTimeStore=e,this.accelerationStore=t,this.angularVelocityStore=n;let r=e.length*3;j(t.length===r&&n.length===r,`gyro track arrays disagree on the sample count`),j(en(e),`gyro sample times go back`)}get length(){return this.captureTimeStore.length}get isEmpty(){return this.captureTimeStore.length===0}get captureTimes(){return this.captureTimeStore}get meanSampleInterval(){return this.length<2?void 0:pt(((this.captureTimeStore[this.length-1]??0)-(this.captureTimeStore[0]??0))/(this.length-1))}sampleAt(e){se(e,this.length,`gyro sample`);let t=e*3;return{captureTime:pt(this.captureTimeStore[e]??0),acceleration:this.vectorAt(this.accelerationStore,t),angularVelocity:this.vectorAt(this.angularVelocityStore,t)}}vectorAt(e,t){return[e[t]??NaN,e[t+1]??NaN,e[t+2]??NaN]}};function en(e){return e.every((t,n)=>n===0||t>=(e[n-1]??t))}var tn=16,nn=class{length=0;recordedTimes;accelerations;angularVelocities;constructor(e){this.recordedTimes=new Float64Array(e),this.accelerations=new Float32Array(e*3),this.angularVelocities=new Float32Array(e*3)}push(e){this.recordedTimes[this.length]=e.captureTime,this.accelerations.set(e.acceleration,this.length*3),this.angularVelocities.set(e.angularVelocity,this.length*3),this.length+=1}dropFlippedBits(e){let t=0;for(let n=0;n<this.length;n+=1)this.isFlippedAt(n,e)||(this.moveSample(n,t),t+=1);this.length=t}captureTimes(){return this.recordedTimes.subarray(0,this.length)}toTrack(e){let t=this.length*3;return new $t(e,this.accelerations.subarray(0,t),this.angularVelocities.subarray(0,t))}isFlippedAt(e,t){return e>0&&e<this.length-1&&(rn(this.accelerations,e,t.acceleration)||rn(this.angularVelocities,e,t.angularVelocity))}moveSample(e,t){if(e!==t){this.recordedTimes[t]=this.recordedTimes[e]??0;for(let n of[this.accelerations,this.angularVelocities])n.copyWithin(t*3,e*3,(e+1)*3)}}};function rn(e,t,n){for(let r=0;r<3;r+=1)if(an(e,t*3+r,n))return!0;return!1}function an(e,t,n){let r=e[t-3]??0,i=e[t+3]??0,a=Math.abs((e[t]??0)-(r+i)/2),o=Math.abs(r-i);for(let e of n){let t=e/tn;if(o<=t&&Math.abs(a-e)<=t)return!0}return!1}function on(e){let t=e.subarray(1).map((t,n)=>t-(e[n]??t)).toSorted();return t[Math.floor(t.length/2)]??0}var sn=50,cn=1e4,ln=17;function un(e){let t=fn(e),n={recorded:e,interval:t,tolerance:dn(t)},r=Float64Array.from(e);gn(r,mn(pn(n)),n);let i=r.filter((t,n)=>t!==e[n]).length;for(let e=1;e<r.length;e+=1)r[e]=Math.max(r[e]??0,r[e-1]??0);return{times:r,mended:i}}function dn(e){return Math.max(sn*e,cn)}function fn(e){return on(e.subarray(0,1025))}function pn({recorded:e,tolerance:t}){let n=[],r=0;for(let i=1;i<=e.length;i+=1){let a=(e[i]??-1/0)-(e[i-1]??0);a>=0&&a<=t||(n.push({start:r,end:i}),r=i)}return n}function mn(e){let t=0;for(let n of e)t=Math.max(t,hn(n));return e.filter(e=>{let n=hn(e);return n>=ln||n===t})}function hn(e){return e.end-e.start}function gn(e,t,n){let[r]=t;if(r){for(let t=r.start-1;t>=0;--t)e[t]=vn(t,(e[t+1]??0)-n.interval,n);for(let[r,i]of t.entries())_n(e,{start:i.end,end:t[r+1]?.start??e.length},n)}}function _n(e,t,n){for(let r=t.start;r<t.end;r+=1)e[r]=vn(r,(e[r-1]??0)+n.interval,n)}function vn(e,t,n){let r=n.recorded[e]??t;return Math.abs(r-t)<=n.tolerance?r:t}var yn=100,bn=1e4,xn=32,Sn=2,Cn=64,wn=100,Tn=56*xn;function En(e,t){let n=new Ht(e.ranges),r=new Vt;if(e.isRawGyro!==void 0)return e.isRawGyro?n:r;if(t===void 0)return;let i=[n,r].filter(e=>jn(t,e)),[a]=i;if(a&&i.length===1)return a;throw new A(`unsupported-gyro-record`,`cannot tell the gyro sample layout from the first ${t.byteLength} bytes without the info record`)}function Dn(e,t){let n=Math.floor(e.byteLength/t.sampleSize),r=new $e(e),i=new nn(n);for(let e=0;e<n;e+=1){let n=On(r,t,e*t.sampleSize);n&&i.push(n)}i.dropFlippedBits(t.flipSteps);let a=un(i.captureTimes());return{track:i.toTrack(a.times),layout:t.name,strayBytes:e.byteLength%t.sampleSize,damagedSamples:n-i.length,mendedStamps:a.mended}}function On(e,t,n){try{let r=t.timestampAt(e,n);if(r===0&&kn(e.bytesAt(n,t.sampleSize)))return;let i={captureTime:r,acceleration:t.accelerationAt(e,n),angularVelocity:t.angularVelocityAt(e,n)};return An(i.acceleration,Cn)&&An(i.angularVelocity,wn)?i:void 0}catch(e){if(ae(e,`binary-unsafe-integer`))return;throw e}}function kn(e){return e.every(e=>e===0)}function An(e,t){return e.every(e=>Math.abs(e)<=t)}function jn(e,t){let n=Mn(e,t);if(n.length<Sn)return!1;let r=on(n);return r>=yn&&r<=bn}function Mn(e,t){let n=new $e(e),r=Math.floor(e.byteLength/t.sampleSize),i=[];for(let e=0;e<r;e+=1){let r=Nn(n,t,e*t.sampleSize);r!==void 0&&i.push(r)}return Float64Array.from(i)}function Nn(e,t,n){try{return t.timestampAt(e,n)}catch(e){if(ae(e,`binary-unsafe-integer`))return;throw e}}function Pn(e,t){return t?t.captureTimeOf(e):pt(e)}function Fn(e,t){let n=e.firstFrameTimestamp;return n===void 0?void 0:Pn(n,t)}var In=class e{offset;length;constructor(e,t){this.offset=e,this.length=t}static of(t,n){if(!Number.isSafeInteger(t)||t<0)throw new A(`invalid-byte-range`,`offset must be a non-negative integer, got ${t}`);if(!Number.isSafeInteger(n)||n<0)throw new A(`invalid-byte-range`,`length must be a non-negative integer, got ${n}`);return new e(t,n)}static lastOf(e,t){if(t>e)throw new A(`invalid-byte-range`,`cannot take ${t} bytes from a ${e}-byte source`);return this.of(e-t,t)}get end(){return this.offset+this.length}overlaps(e){return Math.max(this.offset,e.offset)<Math.min(this.end,e.end)}contains(e){return this.offset<=e.offset&&e.end<=this.end}ensureWithin(e,t){if(!(this.end<=e))throw new A(`invalid-byte-range`,`range ${this.offset}+${this.length} exceeds the ${e}-byte ${t}`)}},Ln=class{source;trailer;info;gyroLayoutPromise;constructor(e,t,n){this.source=e,this.trailer=t,this.info=n}get listsExposure(){return this.trailer.locationOf(He.Exposure)!==void 0}async readGyro(){let e=this.trailer.locationOf(He.Gyro);if(e===void 0)return;let[t,n]=await Promise.all([this.source.read(e.payload),this.gyroSampleLayout()]);return j(n!==void 0,`a gyro record always yields or refuses a layout`),Dn(t,n)}async readExposure(){let e=this.trailer.locationOf(He.Exposure);if(e===void 0)return;let[t,n]=await Promise.all([this.source.read(e.payload),this.gyroSampleLayout()]);return Nt(t,e=>Pn(e,n))}async firstFrameCaptureTime(){return Fn(this.info,await this.gyroSampleLayout())}gyroSampleLayout(){return this.gyroLayoutPromise??=this.selectGyroLayout(),this.gyroLayoutPromise}async selectGyroLayout(){let e=this.gyroLayoutHints();if(e.isRawGyro!==void 0)return En(e,void 0);let t=this.trailer.locationOf(He.Gyro);return En(e,t===void 0?void 0:await this.readHeadOf(t))}gyroLayoutHints(){return{isRawGyro:this.info.isRawGyro,ranges:this.info.sensorRanges}}readHeadOf(e){let t=Math.min(Tn,e.payload.length);return this.source.read(In.of(e.payload.offset,t))}},Rn=class e{format;id;payloadSize;constructor(e,t,n){this.format=e,this.id=t,this.payloadSize=n}static parse(t){if(t.byteLength!==6)throw new A(`invalid-trailer`,`record header must be 6 bytes, got ${t.byteLength}`);let n=new $e(t);return new e(n.uint8At(0),n.uint8At(1),n.uint32LeAt(2))}};function zn(e,t){if(e.byteLength%10!=0)throw new A(`invalid-trailer`,`index size ${e.byteLength} is not a multiple of 10`);let n=new $e(e),r=[];for(let i=0;i<e.byteLength;i+=10){let e=Bn(n,i,t);e&&r.push(e)}return r}function Bn(e,t,n){let r=e.uint32LeAt(t+2);return r===0?void 0:{id:e.uint8At(t+0),format:e.uint8At(t+1),payload:In.of(n+e.uint32LeAt(t+6),r)}}function Vn(e,t){return t.lastHeader.id===He.Index?Hn(e,t):Wn(e,t)}async function Hn(e,t){let n=t.fileSize-72-6-t.lastHeader.payloadSize;qn(n,t.lastHeader,t.payloadStart);let r=In.of(n,t.lastHeader.payloadSize),i=zn(await e.read(r),t.payloadStart);for(let e of i)Un(e,r.offset);return i}function Un(e,t){if(e.payload.end>t)throw new A(`invalid-trailer`,`record ${e.id} at ${e.payload.offset}+${e.payload.length} lies outside the trailer`)}async function Wn(e,t){let n=[],r=new Kn(e,t.payloadStart),i=t.fileSize-72;for(;i>t.payloadStart;){let e=Rn.parse(await r.bytesEndingAt(i,6)),a=i-6-e.payloadSize;qn(a,e,t.payloadStart),n.push({id:e.id,format:e.format,payload:In.of(a,e.payloadSize)}),i=a}return n.toReversed()}var Gn=65536,Kn=class{source;trailerStart;chunkStart=0;chunk=/* @__PURE__ */ new Uint8Array;constructor(e,t){this.source=e,this.trailerStart=t}async bytesEndingAt(e,t){let n=e-t;if(n<this.trailerStart)throw new A(`invalid-trailer`,`a record header at ${n} lies before the trailer`);return n>=this.chunkStart&&e<=this.chunkStart+this.chunk.byteLength||await this.readChunkEndingAt(e),this.chunk.subarray(n-this.chunkStart,e-this.chunkStart)}async readChunkEndingAt(e){this.chunkStart=Math.max(this.trailerStart,e-Gn),this.chunk=await this.source.read(In.of(this.chunkStart,e-this.chunkStart))}};function qn(e,t,n){if(e<n)throw new A(`invalid-trailer`,`record ${t.id} (${t.payloadSize} bytes) runs past the trailer start; records are not contiguous`)}var Jn=class{footer;payloadStart;byId;constructor(e,t,n){this.footer=e,this.payloadStart=t,this.byId=new Map(n.map(e=>[e.id,e]))}get records(){return[...this.byId.values()]}locationOf(e){return this.byId.get(e)}},Yn=class e{trailerSize;version;constructor(e,t){this.trailerSize=e,this.version=t}static parse(t){if(t.byteLength!==72)throw new A(`invalid-trailer`,`footer must be 72 bytes, got ${t.byteLength}`);let n=new $e(t);if(n.asciiAt(40,32)!==`8db42d694ccc418790edff439fe026bf`)throw new A(`invalid-trailer`,`file does not end with the Insta360 magic`);return new e(n.uint32LeAt(32),n.uint32LeAt(36))}},Xn=78;async function Zn(e,t){if(t<Xn)throw new A(`invalid-trailer`,`file of ${t} bytes is too small to hold a trailer`);let n=Qn(await e.read(In.lastOf(t,Xn)),t);return new Jn(n.footer,n.payloadStart,await Vn(e,n))}function Qn(e,t){let n=new $e(e),r=Yn.parse(n.bytesAt(6,72));if(r.trailerSize>t)throw new A(`invalid-trailer`,`trailer size ${r.trailerSize} exceeds file size ${t}`);return{fileSize:t,payloadStart:t-r.trailerSize,footer:r,lastHeader:Rn.parse(n.bytesAt(0,6))}}var $n=class e{firstFrameCaptureTime;gyroOffset;firstFrameVideoTime;constructor(e,t=mt(0),n=F(0)){this.firstFrameCaptureTime=e,this.gyroOffset=t,this.firstFrameVideoTime=n}withFirstFrameAt(t){return new e(this.firstFrameCaptureTime,this.gyroOffset,t)}videoTimeOf(e){let t=pt(e-this.firstFrameCaptureTime);return F(this.firstFrameVideoTime+ht(t))}gyroVideoTimeOf(e){return F(this.videoTimeOf(e)-_t(this.gyroOffset))}captureTimeOf(e){let t=vt(F(e-this.firstFrameVideoTime));return pt(Math.round(this.firstFrameCaptureTime+t))}};async function er(e){let t=await Zn(e,await e.size()),n=await At(e,t),r=new Ln(e,t,n);return{info:n,calibration:ze(n.calibration),listsExposureRecord:r.listsExposure,captureClock:async()=>{let e=await r.firstFrameCaptureTime();return e===void 0?void 0:new $n(e,n.gyroOffset)},readGyroRecord:()=>r.readGyro(),readExposureRecord:()=>r.readExposure()}}var tr={Insta360Trailer:`inst`},nr=/^[ -~]{4}$/u;function rr(e){return nr.test(e)}function ir(e){return e.some(e=>e.type===tr.Insta360Trailer)?`inst-box`:`bare`}function ar(e,t){if(e.length<8)return;let n=e.asciiAt(4,4);if(!rr(n))return;let r=or(e,t);return r!==void 0&&r.size>=r.headerSize&&r.size<=t?{type:n,...r}:void 0}function or(e,t){let n=e.uint32BeAt(0);return n===1&&e.length>=16?sr(e):{size:n===0?t:n,headerSize:8}}function sr(e){try{return{size:e.uint64BeAt(8),headerSize:16}}catch(e){if(ae(e,`binary-unsafe-integer`))return;throw e}}async function cr(e,t){let n=[],r=0;for(;r+8<=t;){let i=await lr(e,r,t);if(!i)break;n.push(i),r=i.range.end}return n}async function lr(e,t,n){let r=n-t,i=Math.min(16,r),a=ar(new $e(await e.read(In.of(t,i))),r);return a&&{type:a.type,range:In.of(t,a.size)}}async function ur(e){let t=await e.size(),[n,r]=await Promise.all([cr(e,t),Zn(e,t)]);return{fileSize:t,boxes:n,trailerWrapper:ir(n),trailerVersion:r.footer.version,trailerPayloadStart:r.payloadStart,records:r.records.toSorted((e,t)=>e.id-t.id)}}var dr=1e3;async function fr(e){let[t,n]=await Promise.all([ur(e),er(e)]),r=await _r(n),i=await vr(n,r);return{...pr(t),info:n.info,calibration:mr(n),calibrationWarnings:n.calibration.warnings,gyro:r,exposure:i}}function pr(e){return{fileSize:e.fileSize,boxes:e.boxes.map(e=>({type:e.type,offset:e.range.offset,size:e.range.length})),trailerWrapper:e.trailerWrapper,trailerVersion:e.trailerVersion,payloadStart:e.trailerPayloadStart,records:e.records.map(e=>({id:e.id,format:e.format,offset:e.payload.offset,size:e.payload.length}))}}function mr(e){let{calibration:t}=e.calibration;return t===void 0?void 0:{version:t.version,canvas:[t.canvas.width,t.canvas.height],lenses:t.lenses.map(e=>({lensIndex:e.lensIndex,model:e.model.kind,principalPoint:[e.model.principalPoint.x,e.model.principalPoint.y],orientationDegrees:[e.orientation.yaw,e.orientation.pitch,e.orientation.roll],translationMetres:e.translation}))}}function hr(e){let{track:t,layout:n,strayBytes:r,damagedSamples:i,mendedStamps:a}=e,o=Math.min(dr,t.length),s=0;for(let e=0;e<o;e+=1)s+=Gt(t.sampleAt(e).acceleration);let c=t.isEmpty?0:t.sampleAt(t.length-1).captureTime-t.sampleAt(0).captureTime;return{layout:n,samples:t.length,strayBytes:r,damagedSamples:i,mendedStamps:a,spanSeconds:ht(pt(c)),meanIntervalUs:t.meanSampleInterval,meanAccelerationMagnitudeG:o>0?s/o:void 0}}function gr(e,t){let n=0;for(let t=0;t<e.length;t+=1)n+=e.entryAt(t).shutterTime;let r=e.length>0;return{entries:e.length,firstCaptureTimeUs:r?e.entryAt(0).captureTime:void 0,lastCaptureTimeUs:r?e.entryAt(e.length-1).captureTime:void 0,meanShutterTimeSeconds:r?n/e.length:void 0,firstEncodedFrameEntry:t}}async function _r(e){try{let t=await e.readGyroRecord();return t===void 0?void 0:hr(t)}catch(e){if(!ae(e,`unsupported-gyro-record`))throw e;return{unreadable:oe(e)}}}async function vr(e,t){if(!e.listsExposureRecord)return;if(t!==void 0&&`unreadable`in t)return{unread:`gyro layout unknown`};let n=await e.readExposureRecord();return n?gr(n,await yr(n,e)):{damaged:!0}}async function yr(e,t){let n=await t.captureClock();return n===void 0?void 0:e.indexAtOrAfter(n.firstFrameCaptureTime)}function br(e,t,n){return Math.min(Math.max(e,t),n)}var xr=.01,Sr=class e{clock;captureTimes;shutterTimes;frameDuration;constructor(e){j(e.shutterTimes===void 0||e.shutterTimes.length===e.captureTimes.length,`frame time arrays disagree on the frame count`),this.clock=e.clock,this.captureTimes=e.captureTimes,this.shutterTimes=e.shutterTimes,this.frameDuration=e.frameDuration}static withoutShutterTimes(t){return new e({...t,shutterTimes:void 0})}get frameCount(){return this.captureTimes.length}frameAt(e){se(e,this.frameCount,`frame`);let t=pt(this.captureTimes[e]??0),n=this.shutterTimes?.[e],r=n===void 0?void 0:F(n),i=this.clock.videoTimeOf(t);return{index:e,captureTime:t,videoTime:i,shutterTime:r,midExposureVideoTime:F(i+(r??0)/2)}}midExposureAt(e){let t=this.frameIndexAt(e);return t===void 0?void 0:this.frameAt(t).midExposureVideoTime}frameIndexAt(e){return this.frameCount===0?void 0:br(this.frameDuration===void 0?this.lastCapturedAt(e):this.onFrameGrid(e,this.frameDuration),0,this.frameCount-1)}onFrameGrid(e,t){let n=(e-this.clock.firstFrameVideoTime)/t;return Math.floor(n+xr)}lastCapturedAt(e){let t=this.clock.captureTimeOf(e),n=0,r=this.frameCount-1;for(;n<r;){let e=Math.ceil((n+r)/2);(this.captureTimes[e]??1/0)<=t?n=e:r=e-1}return n}};function Cr(e){let{exposureRecord:t,clock:n,frameCount:r}=e;if(!t)return;let i=t.indexAtOrAfter(n.firstFrameCaptureTime);if(t.length-i<r)return;let a=t.slice(i,r);return new Sr({clock:n,captureTimes:Float64Array.from(a.captureTimes),shutterTimes:Float64Array.from(a.shutterTimes),frameDuration:e.frameDuration})}function wr(e){let{trackTimestamps:t,clock:n,frameCount:r}=e;if(!t||t.length<r)return;let i=Float64Array.from(t.slice(0,r),e=>n.captureTimeOf(e));return Sr.withoutShutterTimes({clock:n,captureTimes:i,frameDuration:e.frameDuration})}function Tr(e){let{frameRate:t,clock:n,frameCount:r}=e;if(t===void 0||t<=0)return;let i=Float64Array.from({length:r},(e,r)=>n.captureTimeOf(F(n.firstFrameVideoTime+r/t)));return Sr.withoutShutterTimes({clock:n,captureTimes:i,frameDuration:e.frameDuration})}var Er={"exposure-record":Cr,"track-timestamps":wr,nominal:Tr},Dr=[`exposure-record`,`track-timestamps`,`nominal`],Or=[`track-timestamps`,`exposure-record`,`nominal`];function kr(e,t){let n=[];for(let r of jr(t)){let t=Er[r](e);if(t)return{frameTimes:t,source:r,warnings:n};n.push(`${r} unavailable`)}}function Ar(e,t){let n=[];for(let r of jr(t)){if(r===`track-timestamps`)return{needsTrackTimestamps:!0,resolveWith:n=>kr({...e,trackTimestamps:n},t)};let i=Er[r]({...e,trackTimestamps:void 0});if(i)return{needsTrackTimestamps:!1,resolved:{frameTimes:i,source:r,warnings:n}};n.push(`${r} unavailable`)}return{needsTrackTimestamps:!1,resolved:void 0}}function jr(e){return e===`track-timestamps`?Or:Dr}async function Mr(e,t,n){let{info:r}=e,[i,a]=await Promise.all([t.frameCount(),e.readExposureRecord()]),o=Ar({...n,frameCount:i,frameRate:r.frameRate,exposureRecord:a},r.preferredFrameTimeSource);return o.needsTrackTimestamps?o.resolveWith(await t.sampleTimestamps()):o.resolved}var Nr=[1,0,0,0,1,0,0,0,1];function Pr(e){let t=Math.cos(e),n=Math.sin(e);return[1,0,0,0,t,-n,0,n,t]}function Fr(e){let t=Math.cos(e),n=Math.sin(e);return[t,0,n,0,1,0,-n,0,t]}function Ir(e){let t=Math.cos(e),n=Math.sin(e);return[t,-n,0,n,t,0,0,0,1]}function Lr(e,t){let[n,r,i,a,o,s,c,l,u]=e,[d,f,p,m,h,g,_,v,y]=t;return[n*d+r*m+i*_,n*f+r*h+i*v,n*p+r*g+i*y,a*d+o*m+s*_,a*f+o*h+s*v,a*p+o*g+s*y,c*d+l*m+u*_,c*f+l*h+u*v,c*p+l*g+u*y]}function Rr(e,t){let[n,r,i,a,o,s,c,l,u]=e,[d,f,p]=t;return[n*d+r*f+i*p,a*d+o*f+s*p,c*d+l*f+u*p]}function zr(e){let[t,n,r,i,a,o,s,c,l]=e;return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}var Br=/* @__PURE__ */ new Map([[`x`,[1,0,0]],[`y`,[0,1,0]],[`z`,[0,0,1]],[`-x`,[-1,0,0]],[`-y`,[0,-1,0]],[`-z`,[0,0,-1]]]);function Vr(e){let t=Br.get(e);return j(t!==void 0,`unknown IMU axis ${e}`),t}function Hr(e){let[t,n,r]=e.map(e=>Vr(e));return[...t,...n,...r]}function Ur(e){return zr(Hr(e))===1}function Wr(e,t){return{...Kr(e,t),isVerified:!0}}function Gr(e,t){return{...Kr(e,t),isVerified:!1}}function Kr(e,t){return j(Ur(t),`IMU axes ${t.join(`, `)} are not a rotation`),{name:e,toBody:Hr(t)}}function qr(e,t){return Rr(e.toBody,t)}var Jr=[`x`,`z`,`-y`],Yr=Wr(`X5`,Jr),Xr=Wr(`X6`,Jr),Zr=Wr(`X4 Air`,Jr),Qr=Gr(`aligned (unverified)`,[`x`,`y`,`z`]),$r=/* @__PURE__ */ new Map([[`Insta360 X4 Air`,Zr],[`Insta360 X5`,Yr],[`Insta360 X6`,Xr]]);function ei(e){return $r.get(e.model?.trim()??``)??Qr}var ti=.02,ni=vt(F(1));function ri(e,t,n){let r=ht(e.meanSampleInterval??ni),i=Math.max(1,Math.min(e.length,Math.round(n/r))),a=Float64Array.from({length:e.length},(n,r)=>Gt(qr(t,e.sampleAt(r).angularVelocity))),o=0;for(let e=0;e<i;e+=1)o+=a[e]??0;let s={start:0,sum:o};for(let t=1;t+i<=e.length;t+=1)o+=(a[t+i-1]??0)-(a[t-1]??0),o<s.sum&&(s={start:t,sum:o});return{start:s.start,end:s.start+i}}function ii({gyro:e,frame:t},n,r){let i=Wt;for(let a=n.start;a<n.end;a+=1){let n=r(e.sampleAt(a));i=Yt(i,qr(t,n))}return Zt(i,1/Math.max(n.end-n.start,1))}function ai(e,t,n){let r=ii({gyro:e,frame:t},n,e=>e.angularVelocity);return Gt(r)<=ti?r:Wt}var oi=[0,0,0,1],si=1e-12,ci=.9995;function li(e,t){let n=Gt(e);if(n===0)return oi;let r=t/2,i=Math.sin(r)/n;return[e[0]*i,e[1]*i,e[2]*i,Math.cos(r)]}function ui(e){let t=Gt(e);return t<si?oi:li(e,n(t))}function di(e,t){let[n,r,i,a]=e,[o,s,c,l]=t;return[a*o+n*l+r*c-i*s,a*s-n*c+r*l+i*o,a*c+n*s-r*o+i*l,a*l-n*o-r*s-i*c]}function fi(e){let[t,n,r,i]=e;return[-t,-n,-r,i]}function pi(e){let[t,n,r,i]=e,a=Math.hypot(t,n,r,i);return a===0?oi:[t/a,n/a,r/a,i/a]}function mi(e,t){let[n,r,i,a]=e,[o,s,c]=t,l=2*(r*c-i*s),u=2*(i*o-n*c),d=2*(n*s-r*o);return[o+a*l+(r*d-i*u),s+a*u+(i*l-n*d),c+a*d+(n*u-r*l)]}function hi(e,t,n){let[r,i,a,o]=e,[s,c,l,u]=t,d=r*s+i*c+a*l+o*u;if(d<0&&(d=-d,[s,c,l,u]=[-s,-c,-l,-u]),d>ci)return pi([r+(s-r)*n,i+(c-i)*n,a+(l-a)*n,o+(u-o)*n]);let f=Math.acos(d),p=Math.sin(f),m=Math.sin((1-n)*f)/p,h=Math.sin(n*f)/p;return[r*m+s*h,i*m+c*h,a*m+l*h,o*m+u*h]}function gi(e){let[t,n,r,i]=e;return[1-2*(n*n+r*r),2*(t*n-r*i),2*(t*r+n*i),2*(t*n+r*i),1-2*(t*t+r*r),2*(n*r-t*i),2*(t*r-n*i),2*(n*r+t*i),1-2*(t*t+n*n)]}var _i=[0,1,0],vi=.9,yi=1.1;function bi(e){let t=Gt(e);return t>=vi&&t<=yi?Zt(e,-1/t):void 0}function xi(e,t){let n=bi(t);return n?qt(n,mi(fi(e),_i)):[0,0,0]}function Si(e,t){if(e.isEmpty)return{start:0,end:0};let n=e.sampleAt(0).captureTime,r=vt(t),i=1;for(;i<e.length&&e.sampleAt(i).captureTime-n<=r;)i+=1;return{start:0,end:i}}function Ci(e,t,n){if(e.isEmpty)return oi;let r=Si(e,n),i=bi(ii({gyro:e,frame:t},r,e=>e.acceleration));return i?wi(i,_i):oi}function wi(e,t){let r=qt(e,t),i=Kt(e,t),a=Gt(r);return a>0?li(r,n(Math.atan2(a,i))):i>0?oi:li(Ti(e),n(Math.PI))}function Ti(e){return Math.abs(e[0])<Math.abs(e[2])?[0,-e[2],e[1]]:[-e[1],e[0],0]}var Ei=.2,Di=.5,Oi=.5,ki=4,Ai=.05,ji=class e{videoTimes;quaternions;constructor(e,t){this.videoTimes=e,this.quaternions=t,j(t.length===e.length*ki,`orientation track arrays disagree on the sample count`)}static integrate(t){let{gyro:n,clock:r,frame:i}=t,a=new Float64Array(n.length),o=new Float32Array(n.length*ki);if(n.isEmpty)return new e(a,o);let s={frame:i,bias:ai(n,i,ri(n,i,F(Di))),gravityGain:t.options?.gravityGain??Ei};a.set(Mi(n,r));let c={orientation:Ci(n,i,F(Oi)),time:F(a[0]??0),rate:Wt};for(let e=0;e<n.length;e+=1){let t=F(a[e]??c.time);c=Pi(c,{sample:Ni(n,e),time:t},s),o.set(c.orientation,e*ki)}return new e(a,o)}get length(){return this.videoTimes.length}orientationAt(e){if(this.length===0)return oi;let t=this.firstIndexAfter(e);if(t===0)return this.quaternionAt(0);if(t>=this.length)return this.quaternionAt(this.length-1);let n=t-1,r=(this.videoTimes[t]??0)-(this.videoTimes[n]??0),i=r>0?(e-(this.videoTimes[n]??0))/r:0;return hi(this.quaternionAt(n),this.quaternionAt(t),i)}quaternionAt(e){let t=e*ki,[n=0,r=0,i=0,a=1]=this.quaternions.subarray(t,t+ki);return[n,r,i,a]}firstIndexAfter(e){let t=0,n=this.length;for(;t<n;){let r=Math.floor((t+n)/2);(this.videoTimes[r]??1/0)<=e?t=r+1:n=r}return t}};function Mi(e,t){return Float64Array.from({length:e.length},(n,r)=>t.gyroVideoTimeOf(e.sampleAt(r).captureTime))}function Ni(e,t){let n=e.sampleAt(t);return j(Jt(n.acceleration)&&Jt(n.angularVelocity),`gyro sample ${t} is not finite`),n}function Pi(e,{sample:t,time:n},r){let{frame:i,bias:a,gravityGain:o}=r,s=br(n-e.time,0,Ai),c=xi(e.orientation,qr(i,t.acceleration));return{orientation:Ii(e.orientation,Fi(e.rate,c,o),s),time:n,rate:Xt(qr(i,t.angularVelocity),a)}}function Fi(e,t,n){return Yt(e,Zt(t,n))}function Ii(e,t,n){return pi(di(e,ui(Zt(t,n))))}var Li=`the recording has no gyro record; stabilization is unavailable`;async function Ri(e,t){let n=await e.readGyroRecord();if(!n)return{setup:void 0,warnings:[Li]};let r=ei(e.info),i=ji.integrate({gyro:n.track,clock:t,frame:r}),a=[...Bi(r,e),...zi(n)];return{setup:{orientations:i,imuFrame:r},warnings:a}}function zi(e){return[...e.damagedSamples>0?[`damaged gyro samples left out of stabilization: ${e.damagedSamples}`]:[],...e.mendedStamps>0?[`gyro stamps off their neighbours mended: ${e.mendedStamps}`]:[]]}function Bi(e,t){return e.isVerified?[]:[`the IMU frame of ${t.info.model??`this camera`} has not been verified on a recording; stabilization may misbehave`]}var Vi=`frame timing and stabilization are unavailable`,Hi=`the recording has no capture clock; ${Vi}`,Ui=`the recording has no frame source to time; ${Vi}`,Wi=`no frame timing source is usable; frames are timed by their track timestamps`;async function Gi(e,t){try{return await Ki(e,t)}catch(e){if(!ae(e,`unsupported-gyro-record`))throw e;return Ji([`${oe(e)}; ${Vi}`])}}async function Ki(e,t){let n=await e.captureClock();if(!n)return Ji([Hi]);if(!t)return Ji([Ui]);let r=await qi(n,t),[i,a]=await Promise.all([Mr(e,t,r),Ri(e,r.clock)]);return{frameTimes:i?.frameTimes,frameTimeSource:i?.source,motion:a.setup,warnings:[...i?.warnings??[Wi],...a.warnings]}}async function qi(e,t){let n=await t.firstKeyframe(),r=n!==void 0&&n.duration>0;return{clock:e.withFirstFrameAt(n?.timestamp??F(0)),frameDuration:r?n.duration:void 0}}function Ji(e){return{frameTimes:void 0,frameTimeSource:void 0,motion:void 0,warnings:e}}var Yi=/^(?<prefix>[A-Za-z]+(?:_[A-Za-z]+)*)_(?<stamp>\d{8}_\d{6})_(?<lens>\d)(?<proxy>\d)_(?<sequence>\d{3})\.(?<extension>[A-Za-z0-9]+)$/u,Xi=0,Zi=1,Qi=0,$i=1,ea=class e{parts;constructor(e){this.parts=e}static parse(t){let n=Yi.exec(t)?.groups;return n?new e(ta(n)):void 0}get isBackLens(){return this.parts.lensDigit===Xi}get isScreenLens(){return this.parts.lensDigit===Zi}get isProxy(){return this.parts.proxyDigit===$i}otherLensName(){let t=this.isBackLens?Zi:Xi;return new e({...this.parts,lensDigit:t,proxyDigit:Qi}).toString()}toString(){let{prefix:e,captureStamp:t,lensDigit:n,proxyDigit:r,sequence:i,extension:a}=this.parts;return`${e}_${t}_${n}${r}_${i}.${a}`}};function ta(e){return{prefix:e.prefix??``,captureStamp:e.stamp??``,lensDigit:Number(e.lens),proxyDigit:Number(e.proxy),sequence:e.sequence??``,extension:e.extension??``}}var na=/[#?]/u;function ra(e){let t=e.search(na);return t===-1?{path:e,suffix:``}:{path:e.slice(0,t),suffix:e.slice(t)}}function ia(e){let{path:t}=ra(e),n=t.slice(t.lastIndexOf(`/`)+1);try{return decodeURIComponent(n)}catch{return n}}async function aa(e,t){let n=ea.parse(ia(e));if(!n)return;let r=oa(e,n.otherLensName());return await t.exists(r)?r:void 0}function oa(e,t){let{path:n,suffix:r}=ra(e);return`${n.slice(0,n.lastIndexOf(`/`)+1)}${encodeURIComponent(t)}${r}`}var sa={FileType:`ftyp`,MediaData:`mdat`,Movie:`moov`,MovieHeader:`mvhd`,MovieExtends:`mvex`,Track:`trak`,TrackHeader:`tkhd`,Edit:`edts`,EditList:`elst`,Media:`mdia`,MediaHeader:`mdhd`,Handler:`hdlr`,MediaInformation:`minf`,SampleTable:`stbl`,SampleDescription:`stsd`,TimeToSample:`stts`,CompositionOffset:`ctts`,SyncSample:`stss`,SampleToChunk:`stsc`,SampleSize:`stsz`,ChunkOffset:`stco`,ChunkLargeOffset:`co64`,AvcConfiguration:`avcC`,HevcConfiguration:`hvcC`},ca={Video:`vide`,Sound:`soun`},la=[`avc1`,`avc3`],ua=[`hvc1`,`hev1`],da={isKeyframe:()=>!0},fa=31,pa=1,ma=4,ha=5,ga=1,_a=63,va=16,ya=23,ba={typeOf:e=>e&fa,verdictOn:e=>e===ha?`keyframe`:e>=pa&&e<=ma?`not-a-keyframe`:`read-on`},xa={typeOf:e=>e>>ga&_a,verdictOn:e=>e<va?`not-a-keyframe`:e<=ya?`keyframe`:`read-on`},Sa=8,Ca=class{family;lengthSize;constructor(e,t){this.family=e,this.lengthSize=t}isKeyframe(e){let t=0;for(;t+this.lengthSize<e.length;){let n=t+this.lengthSize,r=n+wa(e,t,this.lengthSize);if(r>e.length)return!1;let i=this.family.verdictOn(this.family.typeOf(e[n]??0));if(i!==`read-on`)return i===`keyframe`;t=r}return!1}};function wa(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r*2**Sa+(e[t+i]??0);return r}var Ta=[[la,ba],[ua,xa]];function Ea(e){let{sampleEntryType:t,nalLengthSize:n}=e,[,r]=Ta.find(([e])=>e.includes(t))??[];return r&&n!==void 0?new Ca(r,n):da}function Da(e){let t=[],n=0;for(;e.byteLength-n>=8;){let r=e.byteLength-n,i=ar(new $e(e.subarray(n,n+16)),r);if(!i)throw ja(`holds no box at byte ${n} of ${e.byteLength}`);let a=e.subarray(n+i.headerSize,n+i.size);t.push({type:i.type,body:a}),n+=i.size}return t}function Oa(e,t){let n=ka(e,t);if(!n)throw ja(`has no ${t} box where one belongs`);return n}function ka(e,t){return e.find(e=>e.type===t)}function Aa(e){if(e.body.byteLength<4)throw ja(`has a ${e.type} box too short for its version and flags`);return{version:e.body[0]??0,content:new $e(e.body.subarray(4))}}function ja(e){return new A(`unsupported-container`,`the movie box ${e}`)}var Ma={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:96},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:108}},Na={0:8,1:16},Pa={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:20},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:32}},Fa={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleDelta:{offset:4,kind:`uint32`}}},Ia={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleOffset:{offset:4,kind:`int32`}}},La={entrySize:4,fields:{sampleNumber:{offset:0,kind:`uint32`}}},Ra={0:{entrySize:12,fields:{segmentDuration:{offset:0,kind:`uint32`},mediaTime:{offset:4,kind:`int32`},mediaRate:{offset:8,kind:`uint32`}}},1:{entrySize:20,fields:{segmentDuration:{offset:0,kind:`uint64`},mediaTime:{offset:8,kind:`int64`},mediaRate:{offset:16,kind:`uint32`}}}},za={entrySize:12,fields:{firstChunk:{offset:0,kind:`uint32`},samplesPerChunk:{offset:4,kind:`uint32`},sampleDescriptionIndex:{offset:8,kind:`uint32`}}},Ba={entrySize:4,fields:{chunkOffset:{offset:0,kind:`uint32`}}},Va={entrySize:8,fields:{chunkOffset:{offset:0,kind:`uint64`}}},Ha={uint32:(e,t)=>e.uint32BeAt(t),uint64:(e,t)=>e.uint64BeAt(t),int32:(e,t)=>e.int32BeAt(t),int64:(e,t)=>e.int64BeAt(t)};function Ua(e,t,n=0){return Ha[t.kind](e,n+t.offset)}function Wa(e,t){let n=e.uint32BeAt(0);if(4+n*t.entrySize>e.length)throw ja(`has a table of ${n} entries that do not fit in its box`);let r=Object.keys(t.fields),i={};for(let a of r)i[a]=Array.from({length:n},(n,r)=>Ua(e,t.fields[a],4+r*t.entrySize));return i}var Ga=1;function Ka(e){let t=qa(Oa(e,sa.SampleSize)),n=Ja(e),r=Aa(Oa(e,sa.SampleToChunk)).content;return{offsets:Xa({sizes:t,chunkOffsets:n,perChunk:Ya(Wa(r,za),n.length)}),sizes:t}}function qa(e){let{content:t}=Aa(e),n=t.uint32BeAt(0),r=t.uint32BeAt(4);if(n!==0)return new Float64Array(r).fill(n);if(8+r*4>t.length)throw ja(`lists ${r} sample sizes that do not fit in its box`);return Float64Array.from({length:r},(e,n)=>t.uint32BeAt(8+n*4))}function Ja(e){let t=ka(e,sa.ChunkLargeOffset),n=t??ka(e,sa.ChunkOffset);if(!n)throw ja(`has a sample table without chunk offsets`);let r=t?Va:Ba;return Wa(Aa(n).content,r).chunkOffset}function Ya(e,t){let n=Array.from({length:t},()=>0);for(let[r,i]of e.firstChunk.entries()){let a=e.firstChunk[r+1]??t+Ga,o=e.samplesPerChunk[r]??0;n.fill(o,i-Ga,a-Ga)}return n}function Xa(e){let t=new Float64Array(e.sizes.length),n=0;for(let[r,i]of e.chunkOffsets.entries()){let a=i,o=Math.min(n+(e.perChunk[r]??0),t.length);for(;n<o;n+=1)t[n]=a,a+=e.sizes[n]??0}if(n<t.length)throw ja(`has chunks for ${n} of its ${t.length} samples`);return t}var Za=4,Qa=/* @__PURE__ */ new Map([[sa.AvcConfiguration,4],[sa.HevcConfiguration,21]]);function $a(e){let t=Aa(Oa(e,sa.MovieHeader));return t.content.uint32BeAt(no(t,Ma,sa.MovieHeader).timescale)}function eo(e){let t=Da(e.body),n=Da(Oa(t,sa.Media).body);return{track:t,media:n,sampleTable:Da(Oa(Da(Oa(n,sa.MediaInformation).body),sa.SampleTable).body)}}function to(e){let t=ao(e.media),n=oo(e.sampleTable);return{trackId:ro(e.track),handlerType:t,mediaTimescale:io(e.media),sampleEntryType:n.type,nalLengthSize:t===ca.Video?so(n):void 0}}function no(e,t,n){let r=e.version===0||e.version===1?t[e.version]:void 0;if(r===void 0)throw ja(`has a ${n} box of version ${e.version}`);return r}function ro(e){let t=Aa(Oa(e,sa.TrackHeader));return t.content.uint32BeAt(no(t,Na,sa.TrackHeader))}function io(e){let t=Aa(Oa(e,sa.MediaHeader));return t.content.uint32BeAt(no(t,Pa,sa.MediaHeader).timescale)}function ao(e){let{content:t}=Aa(Oa(e,sa.Handler));return t.asciiAt(4,Za)}function oo(e){let{content:t}=Aa(Oa(e,sa.SampleDescription)),n=t.length-4,[r]=Da(t.bytesAt(4,n));if(!r)throw ja(`has a track without a sample entry`);return r}function so(e){let t=Da(e.body.subarray(78)).find(e=>Qa.has(e.type)),n=t?.body[Qa.get(t.type)??0];return n===void 0?void 0:(n&3)+1}function co(e){return Array.from({length:e.length},(e,t)=>t).toSorted((t,n)=>(e[t]??0)-(e[n]??0))}function lo(e,t){let n=uo(Oa(e.sampleTable,sa.TimeToSample),t),r=fo(e.sampleTable,t.sampleCount),i=r?n.times.map((e,t)=>e+(r[t]??0)):n.times,a=mo(e.track,t),o=i.map(e=>(e-a)/t.media),s=(r?ho(i,n.deltas):n.deltas).map(e=>e/t.media);return{timestamps:o,durations:s,end:go(o,s,t.media)}}function uo(e,t){let n=Wa(Aa(e).content,Fa),r=po(n.sampleCount,n.sampleDelta);if(r.length!==t.sampleCount)throw ja(`times ${r.length} samples of a track that has ${t.sampleCount}`);let i=new Float64Array(r.length);for(let e=1;e<r.length;e+=1)i[e]=(i[e-1]??0)+(r[e-1]??0);return{times:i,deltas:r}}function fo(e,t){let n=ka(e,sa.CompositionOffset);if(!n)return;let r=Wa(Aa(n).content,Ia),i=new Float64Array(t);return i.set(po(r.sampleCount,r.sampleOffset).subarray(0,t)),i}function po(e,t){let n=e.reduce((e,t)=>e+t,0),r=new Float64Array(n),i=0;for(let[n,a]of e.entries())r.fill(t[n]??0,i,i+a),i+=a;return r}function mo(e,t){let n=ka(e,sa.Edit),r=n&&ka(Da(n.body),sa.EditList);if(!r)return 0;let i=Aa(r),a=Wa(i.content,no(i,Ra,sa.EditList)),o=0;for(let[e,n]of a.mediaTime.entries()){if(n===-1){o+=a.segmentDuration[e]??0;continue}return a.mediaRate[e]===65536?n-Math.round(o/t.movie*t.media):0}return 0}function ho(e,t){let n=co(e),r=Float64Array.from(t);for(let t=0;t<n.length-1;t+=1){let i=n[t]??0;r[i]=(e[n[t+1]??0]??0)-(e[i]??0)}return r}function go(e,t,n){let r=co(e).at(-1);if(r===void 0)return F(0);let i=(e[r]??0)+(t[r]??0);return F(Math.round(i*n)/n)}var _o=class{tracks;constructor(e){this.tracks=e}get videoTracks(){return this.tracks.filter(e=>e.kind===`video`)}get audioTracks(){return this.tracks.filter(e=>e.kind===`audio`)}get duration(){return F(Math.max(0,...this.tracks.map(e=>e.end)))}trackWithId(e){return this.tracks.find(t=>t.trackId===e)}};function vo(e,t,n){let r=0,i=e;for(;r<i;){let e=r+i>>>1;t(e)<=n?r=e+1:i=e}return r}var yo=class{parts;trackId;kind;end;keyframeRule;presentationOrder;constructor(e){this.parts=e;let{length:t}=e.offsets;j([e.sizes,e.timestamps,e.durations].every(e=>e.length===t),`the sample table of track ${e.trackId} disagrees on its sample count`),j(bo(e.syncSamples??[],t),`the sync samples of track ${e.trackId} are not samples of it in order`),this.trackId=e.trackId,this.kind=e.kind,this.end=e.end,this.keyframeRule=e.keyframeRule,this.presentationOrder=co(e.timestamps)}get sampleCount(){return this.parts.offsets.length}rangeOf(e){return this.ensureSample(e),In.of(this.parts.offsets[e]??0,this.parts.sizes[e]??0)}timestampOf(e){return this.ensureSample(e),F(this.parts.timestamps[e]??0)}durationOf(e){return this.ensureSample(e),F(this.parts.durations[e]??0)}isSync(e){return this.ensureSample(e),this.syncSampleAtOrBefore(e)===e}sampleShownAt(e){let t=vo(this.presentationOrder.length,e=>this.parts.timestamps[this.presentationOrder[e]??0]??1/0,e);return this.presentationOrder[t-1]}keyframeAt(e){let t=this.sampleShownAt(e);return t===void 0?void 0:this.syncSampleAtOrBefore(t)}syncSampleAtOrBefore(e){let{syncSamples:t}=this.parts;return t?t[vo(t.length,e=>t[e]??0,e)-1]:e>=0?e:void 0}syncSampleAtOrAfter(e){let{syncSamples:t}=this.parts,n=Math.max(0,e);return t?t[vo(t.length,e=>t[e]??0,n-1)]:n<this.sampleCount?n:void 0}timestampsInPresentationOrder(){return this.presentationOrder.map(e=>F(this.parts.timestamps[e]??0))}ensureSample(e){se(e,this.sampleCount,`sample of track ${this.trackId}`)}};function bo(e,t){return e.every((n,r)=>Number.isSafeInteger(n)&&n>=0&&n<t&&n>(e[r-1]??-1))}var xo={[ca.Video]:`video`,[ca.Sound]:`audio`},So=1;function Co(e){let[t]=Da(e);if(t?.type!==sa.Movie)throw ja(`is not where the file says it is`);let n=Da(t.body);if(ka(n,sa.MovieExtends))throw ja(`is fragmented: its samples are described in movie fragments after it`);let r=$a(n);return new _o(n.filter(e=>e.type===sa.Track).flatMap(e=>wo(eo(e),r)))}function wo(e,t){let n=to(e),r=xo[n.handlerType];if(!r)return[];let i=Ka(e.sampleTable),a=lo(e,{media:n.mediaTimescale,movie:t,sampleCount:i.sizes.length});return[new yo({trackId:n.trackId,kind:r,...i,...a,syncSamples:To(e.sampleTable),keyframeRule:Ea(n)})]}function To(e){let t=ka(e,sa.SyncSample);if(!t)return;let{sampleNumber:n}=Wa(Aa(t).content,La);return n.map(e=>e-So)}function Eo(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}async function Do(e){let t=await cr(e,await e.size()),n=t.find(e=>e.type===sa.Movie);if(!n)throw new A(`unsupported-container`,`the file has no movie box to read its samples from`);let r=t.find(e=>e.type===sa.FileType),[i,a]=await Promise.all([Oo(e,r),Oo(e,n)]);return{table:Co(a),movieBytes:Eo([i,a])}}function Oo(e,t){return t?e.read(t.range):Promise.resolve(/* @__PURE__ */ new Uint8Array)}var ko={x:0,y:0,width:1,height:1},Ao={x:0,y:0,width:.5,height:1},jo={x:.5,y:0,width:.5,height:1},Mo=2,No=2,Po=.02,Fo=0,Io=1,Lo=2;function Ro(e,t){let n=e.flatMap((e,t)=>e.videoTracks.map(({description:n})=>({input:e,inputIndex:t,track:n})));if(e.length===1&&Uo(n))return zo(n,t);if(e.length===Mo&&Wo(e,n))return Bo(e,n);let[r]=n;if(r&&n.length===1&&Ko(r.track))return Vo(r);throw Jo(e,n)}function zo(e,t){let n=t.trackOrder===`stream-10-first`,r=n?e.toReversed():e,i=t.fileLayout===void 0?[]:[`info record file layout ${t.fileLayout}`],a=t.trackOrder===void 0?`no track order hint: lens 0 assumed to be track 0`:`info record track order ${t.trackOrder}: lens 0 is track ${+!!n}`;return{kind:`multi-track`,sources:r.map((e,t)=>Ho(e,t)),evidence:[`one input with two video tracks`,...i,a]}}function Bo(e,t){let n=t.toSorted((e,t)=>qo(e.input)-qo(t.input)),r=e.map(e=>e.name??`?`).join(`, `);return{kind:`split-files`,sources:n.map((e,t)=>Ho(e,t)),evidence:[`two inputs with one video track each (${r})`,`lens 0 taken from the _00_ file when named`]}}function Vo(e){let{inputIndex:t,track:n}=e;return{kind:`packed`,sources:[{lensIndex:0,inputIndex:t,trackIndex:n.trackIndex,region:Ao},{lensIndex:1,inputIndex:t,trackIndex:n.trackIndex,region:jo}],evidence:[`single ${n.codedWidth}x${n.codedHeight} track with a 2:1 aspect ratio`]}}function Ho(e,t){return{lensIndex:t,inputIndex:e.inputIndex,trackIndex:e.track.trackIndex,region:ko}}function Uo(e){let[t,n]=e;return e.length===Mo&&t!==void 0&&n!==void 0&&Go(t.track)&&t.track.codedWidth===n.track.codedWidth&&t.track.codedHeight===n.track.codedHeight}function Wo(e,t){return t.length===Mo&&e.every(e=>e.videoTracks.length===1)&&t.every(e=>Go(e.track))}function Go(e){return e.codedWidth===e.codedHeight}function Ko(e){return Math.abs(e.codedWidth/e.codedHeight-No)<=Po}function qo(e){let t=ea.parse(e.name??``);return t?.isBackLens?Fo:t?.isScreenLens?Lo:Io}function Jo(e,t){let[n]=t;if(e.length===1&&t.length===1&&n!==void 0&&Go(n.track))return Yo(n.input);let r=t.map(e=>`${e.track.codedWidth}x${e.track.codedHeight}`).join(`, `);return new A(`unsupported-layout`,`cannot map ${t.length} video track(s) [${r}] in ${e.length} file(s) onto two lenses`)}function Yo(e){let t=ea.parse(e.name??``);return new A(`missing-second-file`,`this recording stores one lens per file; provide ${t?`the matching ${t.otherLensName()}`:`the other lens's file`} as the second source`)}var Xo=[`off`,`lock`,`horizon`,`follow`],Zo=`lock`,Qo=class{nextRotation(){return Nr}},$o=class{nextRotation(e){return gi(fi(e))}},es=class{nextRotation(e){let t=li(_i,as(e));return Lr(gi(fi(e)),gi(t))}},ts={timeConstant:F(1.5),maxContinuousGap:F(1)},ns=class{options;smoothed;previousTime;constructor(e=ts){this.options=e}nextRotation(e,t){return this.smoothed=this.follow(e,t),this.previousTime=t,Lr(gi(fi(e)),gi(this.smoothed))}follow(e,t){let n=this.previousTime===void 0?1/0:t-this.previousTime;if(!this.smoothed||Math.abs(n)>this.options.maxContinuousGap)return e;if(n<=0)return this.smoothed;let r=1-Math.exp(-n/this.options.timeConstant);return hi(this.smoothed,e,r)}},rs={off:()=>new Qo,lock:()=>new $o,horizon:()=>new es,follow:()=>new ns};function is(e){return rs[e]()}function as(e){let[,t,,r]=e;return n(2*Math.atan2(t,r))}function os(e){return t(2*(Math.round(e/o)*o)-e)}function ss(e){let{yaw:n,pitch:r,roll:i}=e.orientation,a=Fr(l(n)),o=Lr(Pr(l(r)),a),c=Lr(Pr(l(t(s*e.lensIndex))),o);return Lr(Ir(l(os(i))),c)}var cs=1.5,ls=.01,us=[1,1,1],ds={maxGain:2,timeConstant:F(cs)};function fs(e,t){let[n]=e;return n?e.map((e,r)=>r===0?us:ps(n,e,t)):[]}function ps(e,t,n){return[ms(e[0],t[0],n),ms(e[1],t[1],n),ms(e[2],t[2],n)]}function ms(e,t,n){return e<ls||t<ls?1:br(e/t,1/n,n)}var hs=class{options;current;lastTime;constructor(e=ds){this.options=e}update(e,t){let n=fs(e,this.options.maxGain),r=this.lastTime===void 0?1/0:Math.max(t-this.lastTime,0);this.lastTime=t;let i=this.current?1-Math.exp(-r/this.options.timeConstant):1,a=this.current;return this.current=n.map((e,t)=>Qt(a?.[t]??us,e,i)),this.current}},gs=30,_s=120,vs=90,ys=90,bs={yaw:t(0),pitch:t(0),fieldOfView:t(vs)};function xs(e){return j([e.yaw,e.pitch,e.fieldOfView].every(e=>Number.isFinite(e)),`view angles must be finite`),{...e,yaw:d(e.yaw),pitch:t(br(e.pitch,-90,ys)),fieldOfView:t(br(e.fieldOfView,gs,_s))}}function Ss(e,t){return e.yaw===t.yaw&&e.pitch===t.pitch&&e.fieldOfView===t.fieldOfView}function Cs(e){return Lr(Fr(l(e.yaw)),Pr(l(e.pitch)))}var ws=[`fast`,`balanced`,`high`],Ts=`balanced`,Es={fast:1,balanced:2,high:3};function Ds(e){return Es[e]}var Os=[`raw-lenses`,`equirectangular`,`normal`],ks=`raw-lenses`,As=.5,js={x:0,y:0,width:1,height:1},Ms={x:As,y:As};function Ns(e){return Math.max(e,1)}function Ps(e){return e.width/Ns(e.height)}function Fs(e,t){return{across:e.x/Ns(t.width),down:e.y/Ns(t.height)}}function Is(e,t){return{x:(t.x-e.x)/e.width,y:(t.y-e.y)/e.height}}function Ls(e,t){let n=Vs(e,t),r=Vs(1/e,t);return n.height>=r.height/e?Rs(n,e):zs(r,e)}function Rs(e,t){let n=e.width/t;return Array.from({length:t},(t,r)=>({...e,x:e.x+r*n,width:n}))}function zs(e,t){let n=e.height/t;return Array.from({length:t},(t,r)=>({...e,y:e.y+r*n,height:n}))}function Bs(e){j(e.length>0,`bounds need at least one rectangle`);let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),r=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:n,width:r-t,height:i-n}}function Vs(e,t){if(e>=t){let n=t/e;return{x:0,y:(1-n)*As,width:1,height:n}}let n=e/t;return{x:(1-n)*As,y:0,width:n,height:1}}function Hs(e){return Math.tan(l(t(e/2)))}function Us(e,t){return t*e.width/e.height}function Ws(e,t,n){let r=Hs(e),i=[(t.x*2-1)*r,(t.y*2-1)*r/n,1];return Zt(i,1/Gt(i))}function Gs(e,t,n){return Rr(Cs(e),Ws(e.fieldOfView,t,n))}var Ks=1.1;function qs(e){return Ks**e}function Js(e,n){return t(e.fieldOfView/Math.max(n,1))}function Ys(e,n,r){let i=Js(e,r);return xs({...e,yaw:t(e.yaw-n.x*i),pitch:t(e.pitch+n.y*i)})}function Xs(e,n){return xs({...e,fieldOfView:t(e.fieldOfView/qs(n))})}function Zs(e,t,r){let i=Xs(e,t.steps);if(t.focus.x===Ms.x&&t.focus.y===Ms.y||i.fieldOfView===e.fieldOfView)return i;let a=Gs(e,t.focus,r),o=Ws(i.fieldOfView,t.focus,r),s=Qs(o,a[1],e.pitch);if(s===void 0)return i;let c=Rr(Pr(l(s)),o),d=u(n(Math.atan2(a[0],a[2])-Math.atan2(c[0],c[2])));return xs({...i,yaw:d,pitch:s})}function Qs(e,r,i){let[,a,o]=e,s=r/Math.hypot(a,o);if(Math.abs(s)>1)return;let c=u(n(Math.atan2(o,a))),l=u(n(Math.acos(s))),f=d(t(l-c)),p=d(t(-l-c));return Math.abs(f-i)<=Math.abs(p-i)?f:p}function $s(e,t){return e<=0||t<=0?0:Math.log(t/e)/Math.log(Ks)}function ec(e,t,n){return xs({...e,yaw:t,pitch:n})}var tc={scale:1,centre:{x:As,y:As}},nc=1e-9;function rc(e,t){return e.scale===t.scale&&e.centre.x===t.centre.x&&e.centre.y===t.centre.y}function ic(e,t){let n=e.width*t.scale,r=e.height*t.scale;return{x:Ms.x-t.centre.x*n,y:Ms.y-t.centre.y*r,width:n,height:r}}function ac(e,t){let n=br(t.scale,1,8),r=n-1<nc?1:n;return{scale:r,centre:{x:lc(t.centre.x,e.width*r),y:lc(t.centre.y,e.height*r)}}}function oc(e,t,n){let r=ac(e,t),i=Is(ic(e,r),n.focus),a=r.scale*qs(n.steps);return ac(e,{scale:a,centre:{x:i.x+(Ms.x-n.focus.x)/(e.width*a),y:i.y+(Ms.y-n.focus.y)/(e.height*a)}})}function sc(e,t,n){let r=ac(e,t),i=cc(e,r,n);return ac(e,{scale:r.scale,centre:{x:r.centre.x-i.across,y:r.centre.y-i.down}})}function cc(e,t,n){return{across:n.across/(e.width*t.scale),down:n.down/(e.height*t.scale)}}function lc(e,t){if(t<=1)return As;let n=As/t;return br(e,n,1-n)}var uc={view:bs,panorama:tc,lenses:tc};function dc(e,t){return Ss(e.view,t.view)&&rc(e.panorama,t.panorama)&&rc(e.lenses,t.lenses)}function fc(e,t){return{...e,view:t}}function pc(e,t){return{...e,lenses:t}}var mc=90;function hc({viewport:e,lensCount:t}){let n=Ls(t,Ps(e));return{tiles:n,bounds:Bs(n)}}function gc(e,t,n){let r=Fs(t,n.viewport);return pc(e,sc(hc(n).bounds,e.lenses,r))}function _c(e,t,n){let r=n.viewport.width/mc;return gc(e,{x:-(t.yaw*r),y:t.pitch*r},n)}function vc(e,t){let{tiles:n,bounds:r}=hc(t),i=ac(r,e.lenses),a=ic(r,i);return n.map(e=>({x:a.x+(e.x-r.x)*i.scale,y:a.y+(e.y-r.y)*i.scale,width:e.width*i.scale,height:e.height*i.scale}))}var yc={isStabilized:!1,canPan:({lenses:e})=>e.scale>1,pan:gc,turn:_c,zoom:(e,t,n)=>pc(e,oc(hc(n).bounds,e.lenses,t)),reset:e=>pc(e,tc),picture:(e,t)=>({kind:`lens-tiles`,tiles:vc(e,t)})},bc={isStabilized:!0,canPan:()=>!0,pan:(e,t,{viewport:n})=>fc(e,Ys(e.view,t,n.width)),turn:(e,n)=>{let{view:r}=e;return fc(e,ec(r,t(r.yaw+n.yaw),t(r.pitch+n.pitch)))},zoom:(e,t,{viewport:n})=>fc(e,Zs(e.view,t,Ps(n))),reset:e=>fc(e,bs),picture:({view:e})=>({kind:`rectilinear`,rotation:Cs(e),fieldOfView:e.fieldOfView,area:js})},xc=2;function Sc(e,t){let n=ac(e,t);return{...n,centre:{x:As,y:n.centre.y}}}function Cc(e,{viewport:t}){let n=Vs(xc,Ps(t));return{fitted:n,panorama:Sc(n,e.panorama)}}function wc(e,n,r){let{view:i}=e;return{...fc(e,ec(i,t(i.yaw+r),i.pitch)),panorama:n}}function Tc(e,n,r){let{fitted:i,panorama:a}=Cc(e,r),o=Fs(n,r.viewport);return wc(e,sc(i,a,{across:0,down:o.down}),t(-(cc(i,a,o).across*c)))}function Ec(e,t,n){let{fitted:r,panorama:i}=Cc(e,n);return wc(e,Sc(r,{...i,centre:{x:As,y:i.centre.y-t.pitch/s}}),t.yaw)}function Dc(e,n,r){let{fitted:i,panorama:a}=Cc(e,r),o=Sc(i,oc(i,a,n)),s=Is(ic(i,a),n.focus),l=Is(ic(i,o),n.focus);return wc(e,o,t((s.x-l.x)*c))}var Oc={normal:bc,equirectangular:{isStabilized:!0,canPan:()=>!0,pan:Tc,turn:Ec,zoom:Dc,reset:e=>({...fc(e,ec(e.view,t(0),e.view.pitch)),panorama:tc}),picture:(e,t)=>{let{fitted:n,panorama:r}=Cc(e,t);return{kind:`equirectangular`,rotation:Fr(l(e.view.yaw)),area:ic(n,r)}}},"raw-lenses":yc};function kc(e){return Oc[e]}var Ac=t(90);function jc(e,t){switch(e.kind){case`mei`:{let[n,r]=e.focal;return{...e,focal:[n*t,r*t]}}case`radial-polynomial`:{let[n,r,i,a]=e.coefficients;return{...e,coefficients:[n*t,r*t,i*t,a*t]}}}}var Mc=5,Nc={start:l(t(Ac-Mc)),end:l(t(Ac+Mc))};function Pc(e){let t=[];for(let n of e.sources)t.every(e=>!Lc(e,n))&&t.push({inputIndex:n.inputIndex,trackIndex:n.trackIndex});return t}function Fc(e){let{calibration:t,layout:n}=e;if(t.lenses.length!==n.sources.length)throw new A(`unsupported-layout`,`the calibration describes ${t.lenses.length} lenses but the layout has ${n.sources.length}`);let r=Pc(n);return j(e.displayConversions.length===r.length,`${e.displayConversions.length} display conversions for ${r.length} frame sources`),{lenses:n.sources.map(n=>{let i=Rc(t,n.lensIndex),a=r.findIndex(e=>Lc(e,n));return{lensIndex:n.lensIndex,frameSlot:a,region:n.region,window:zc(t,i),rotation:ss(i),projection:jc(i.model.projection,t.radialScale),halfFieldOfView:i.model.halfFieldOfView,displayConversion:Ic(e.displayConversions,a)}}),frameSlotCount:r.length,feather:Nc}}function Ic(e,t){let n=e[t];return j(n!==void 0,`no display conversion for frame slot ${t}`),n}function Lc(e,t){return e.inputIndex===t.inputIndex&&e.trackIndex===t.trackIndex}function Rc(e,t){let n=e.lenses.find(e=>e.lensIndex===t);if(!n)throw new A(`invalid-calibration`,`the calibration has no lens ${t}`);return n}function zc(e,t){let n=e.canvas.height;return{x:Math.floor(t.model.principalPoint.x/n)*n,y:0,width:n,height:n}}var Bc=class{parts;stabilizer=new Qo;constructor(e){this.parts=e}setStabilizer(e){this.stabilizer=e}present(e){let t=this.exposureTimeOf(e),n=this.parts.orientations.orientationAt(t);this.parts.sink.setStabilization(this.stabilizer.nextRotation(n,t)),this.parts.sink.present(e)}exposureTimeOf(e){let{timestamp:t}=e.pair;return this.parts.frameTimes?.midExposureAt(t)??t}};function Vc(e){let t=e instanceof Error?e:Error(`a failure went unheard`,{cause:e});Promise.reject(t)}var Hc=.5,Uc=class{meter;applyGains;reportFailure;matcher=new hs;lastMeasuredAt;inFlight;isStopped=!1;constructor(e,t,n=Vc){this.meter=e,this.applyGains=t,this.reportFailure=n}afterPresent(e){(this.lastMeasuredAt===void 0||Math.abs(e-this.lastMeasuredAt)>=Hc)&&!this.isStopped&&this.matchReporting(e)}matchNow(e){return this.inFlight??=this.measureAt(e),this.inFlight}stop(){this.isStopped=!0}async matchReporting(e){try{await this.matchNow(e)}catch(e){this.reportFailure(e)}}async measureAt(e){this.lastMeasuredAt=e;try{let t=await this.meter.measure();t&&!this.isStopped&&this.applyGains(this.matcher.update(t,e))}catch(e){throw this.isStopped=!0,e}finally{this.inFlight=void 0}}},Wc=[1,1,1],Gc=class{sink;renderer;active;lastMediaTime;constructor(e,t){this.sink=e,this.renderer=t}enable(){if(this.active)return;let{renderer:e}=this,t=e.createSeamMeter(),n=new Uc(t,t=>{e.setLensGains(t)});this.active={meter:t,matching:n}}disable(){this.stop();let e=Array.from({length:this.renderer.lensCount},()=>Wc);this.renderer.setLensGains(e)}async matchNow(){this.lastMediaTime!==void 0&&await this.active?.matching.matchNow(this.lastMediaTime)}present(e){this.sink.present(e),this.lastMediaTime=e.mediaTime,this.active?.matching.afterPresent(e.mediaTime)}dispose(){this.stop()}stop(){this.active?.matching.stop(),this.active?.meter.dispose(),this.active=void 0}},Kc=7,qc=.5,Jc=5,Yc=360;Ac-Kc,Math.round(14/qc),Math.round(Jc/qc);var Xc=Math.round(Yc/Jc);Array.from({length:Xc},()=>t(0));var Zc=[`bt709`,`bt470bg`,`smpte170m`,`bt2020`,`smpte432`],Qc=[`bt709`,`smpte170m`,`iec61966-2-1`,`linear`,`pq`,`hlg`],$c=[`rgb`,`bt709`,`bt470bg`,`smpte170m`,`bt2020-ncl`];function el(e,t){return e.find(e=>e===t)??`unspecified`}var tl={a:.17883277,b:.28466892,c:.55991073,segmentJoin:.5,squareSegmentDivisor:3,logSegmentDivisor:12},nl=[1.660491,-.5876411,-.0728499,-.1245505,1.1328999,-.0083494,-.0181508,-.1005789,1.1187297],rl=[.2126,.7152,.0722],il={exposure:1.4,kneeStart:.2,ceiling:1.5,exponent:2.2},al=/* @__PURE__ */ new Set([`bt709`,`bt470bg`,`smpte170m`,`unspecified`]),ol={bt709:Nr,bt2020:nl,unspecified:nl,bt470bg:void 0,smpte170m:void 0,smpte432:void 0};function sl({matrix:e}){return{kind:`as-recorded`,matrix:e}}function cl(e){let t=sl(e);return al.has(e.primaries)?{conversion:t}:{conversion:t,problem:`${e.primaries} primaries are shown as BT.709`}}function ll(e){let t=ol[e.primaries],n={kind:`hlg-to-sdr-bt709`,matrix:e.matrix,gamut:t??Nr,tone:il};return t===void 0?{conversion:n,problem:`HLG of ${e.primaries} primaries is shown without their gamut`}:{conversion:n}}function ul(e){return t=>({conversion:sl(t),problem:`the ${e} transfer cannot be shown yet: drawn as recorded`})}var dl={bt709:cl,smpte170m:cl,"iec61966-2-1":cl,unspecified:cl,hlg:ll,pq:ul(`pq`),linear:ul(`linear`)};function fl(e){let t=e.map(e=>dl[e.transfer](e)),n=t.flatMap(e=>e.problem===void 0?[]:[e.problem]);return{conversions:t.map(e=>e.conversion),warnings:[...new Set(n)]}}var pl={bt709:{red:.2126,blue:.0722},"bt2020-ncl":{red:.2627,blue:.0593},bt470bg:{red:.299,blue:.114},smpte170m:{red:.299,blue:.114},rgb:void 0,unspecified:void 0};function ml(e,t){let n=pl[e],r=pl[t];return n===void 0||r===void 0||e===t?Nr:Lr(hl(n),gl(r))}function hl({red:e,blue:t}){let n=1-e-t,r=2*(1-e),i=2*(1-t);return[1,0,r,1,-t*i/n,-e*r/n,1,i,0]}function gl({red:e,blue:t}){let n=1-e-t,r=2*(1-t),i=2*(1-e);return[e,n,t,-e/r,-n/r,(1-t)/r,(1-e)/i,-n/i,-t/i]}function _l(e){return Object.keys(e)}var vl=class{emitter;queue=[];depth=0;isDelivering=!1;isSuperseding=!1;constructor(e){this.emitter=e}change(e){this.depth===0&&this.isDelivering&&(this.isSuperseding=!0),this.depth+=1;try{return e()}finally{--this.depth,this.depth===0&&(this.isSuperseding=!1,this.deliver())}}emit(e,t){this.post(()=>{this.emitter.emit(e,t)})}post(e){this.isSuperseding&&=(this.queue.length=0,!1),this.queue.push(e),this.depth===0&&this.deliver()}deliver(){if(!this.isDelivering){this.isDelivering=!0;try{for(let e=this.queue.shift();e;e=this.queue.shift())e()}finally{this.isDelivering=!1}}}},yl={done:!0,value:void 0},bl=class{isEnded=!1;end(){this.isEnded=!0}hasEnded(){return this.isEnded}},xl=class{source;constructor(e){this.source=e}stream(e){return{[Symbol.asyncIterator]:()=>new Sl(this.source,e)}}},Sl=class{source;range;ending=new bl;constructor(e,t){this.source=e,this.range=t}async next(){if(await Promise.resolve(),this.ending.hasEnded())return yl;let e=await this.source.read(this.range);return this.ending.hasEnded()?yl:(this.ending.end(),e.byteLength===0?yl:{done:!1,value:e})}return(){return this.ending.end(),Promise.resolve(yl)}},Cl=class{parts;constructor(e){this.parts=e}get duration(){return this.parts.track.end}samplesFrom(e){let{download:t,track:n}=this.parts;return{[Symbol.asyncIterator]:()=>new wl(n,t.openCursor(n,n.sampleShownAt(e)??0,e))}}},wl=class{track;cursor;ending=new bl;constructor(e,t){this.track=e,this.cursor=t}async next(){let e=await this.cursor.nextSample();return!e||this.ending.hasEnded()?yl:{done:!1,value:{timestamp:this.track.timestampOf(e.sample),duration:this.track.durationOf(e.sample),data:Uint8Array.from(e.bytes)}}}return(){return this.ending.end(),this.cursor.close(),Promise.resolve(yl)}},Tl=class{parts;rejected=/* @__PURE__ */ new Set;constructor(e){this.parts=e}get description(){return this.parts.codec.description}decoderConfiguration(){return Promise.resolve(this.parts.codec.configuration)}keyframeAt(e){return Promise.resolve(this.timeOf(this.keyframeSampleAt(e)))}firstKeyframe(){return Promise.resolve(this.timeOf(this.firstKeyframeSample()))}packetsFrom(e){return{[Symbol.asyncIterator]:()=>new El({track:this.parts.track,open:()=>this.cursorFrom(e),reject:e=>{this.rejected.add(e)},packetOf:e=>this.packetOf(e)})}}sampleTimestamps(){return Promise.resolve(this.parts.track.timestampsInPresentationOrder())}frameCount(){return Promise.resolve(this.parts.track.sampleCount)}cursorFrom(e){let t=this.keyframeSampleAt(e)??this.firstKeyframeSample();return t===void 0?void 0:this.parts.download.openCursor(this.parts.track,t,e)}keyframeSampleAt(e){let{track:t}=this.parts,n=t.keyframeAt(e);for(;n!==void 0&&this.rejected.has(n);)n=t.syncSampleAtOrBefore(n-1);return n}firstKeyframeSample(){let{track:e}=this.parts,t=e.syncSampleAtOrAfter(0);for(;t!==void 0&&this.rejected.has(t);)t=e.syncSampleAtOrAfter(t+1);return t}timeOf(e){let{track:t}=this.parts;return e===void 0?void 0:{timestamp:t.timestampOf(e),duration:t.durationOf(e)}}packetOf(e){let{track:t}=this.parts;return{timestamp:t.timestampOf(e.sample),duration:t.durationOf(e.sample),isKeyFrame:t.isSync(e.sample)&&!this.rejected.has(e.sample),data:e.bytes}}},El=class{parts;cursor;isVerified=!1;ending=new bl;constructor(e){this.parts=e,this.cursor=e.open()}async next(){if(this.ending.hasEnded())return yl;let{cursor:e}=this;if(!e)throw new A(`no-key-frame`,`track ${this.parts.track.trackId} has no key frame`);let t=await e.nextSample();return!t||this.ending.hasEnded()?yl:!this.isVerified&&!this.parts.track.keyframeRule.isKeyframe(t.bytes)?this.startEarlier(e,t):(this.isVerified=!0,{done:!1,value:this.parts.packetOf(t)})}return(){return this.ending.end(),this.cursor?.close(),Promise.resolve(yl)}startEarlier(e,t){return this.parts.reject(t.sample),e.close(),this.cursor=this.parts.open(),this.next()}},Dl=class e{ranges;static empty=new e([]);constructor(e){this.ranges=e}static of(t){let n=t.filter(e=>e.length>0).toSorted((e,t)=>e.offset-t.offset);return new e(Ol(n,0))}get isEmpty(){return this.ranges.length===0}get totalLength(){return this.ranges.reduce((e,t)=>e+t.length,0)}union(t){return e.of([...this.ranges,...t.ranges])}subtract(t){return new e(this.ranges.flatMap(e=>kl(e,t.ranges)))}covers(e){return e.length===0||this.ranges.some(t=>t.contains(e))}overlaps(e){return this.ranges.some(t=>t.overlaps(e))}bridgingGapsBelow(t){return new e(Ol(this.ranges,t))}};function Ol(e,t){let n=[];for(let r of e){let e=n.at(-1),i=e!==void 0&&r.offset-e.end<Math.max(t,1);e&&i?n[n.length-1]=Al(e.offset,r.end,e.end):n.push(r)}return n}function kl(e,t){let n=[],r=e.offset;for(let i of t)i.end<=r||i.offset>=e.end||(i.offset>r&&n.push(In.of(r,i.offset-r)),r=Math.max(r,i.end));return r<e.end&&n.push(In.of(r,e.end-r)),n}function Al(e,t,n){return In.of(e,Math.max(t,n)-e)}var jl=class{range;bytes;filled=0;isComplete=!1;constructor(e,t){this.range=e,this.bytes=t}get filledRange(){return In.of(this.range.offset,this.filled)}},Ml=class{blocks=[];get held(){return Dl.of(this.blocks.map(e=>e.filledRange))}get allocatedBytes(){return this.blocks.reduce((e,t)=>e+t.bytes.byteLength,0)}allocate(e){let t=new jl(e,new Uint8Array(e.length));return this.blocks.push(t),t}write(e,t){let n=this.fillingOf(e);n.bytes.set(t,n.filled),n.filled+=t.byteLength}complete(e){this.fillingOf(e).isComplete=!0}trim(e){let t=this.fillingOf(e);t.isComplete=!0,t.bytes=t.bytes.slice(0,t.filled),this.blocks=this.blocks.filter(e=>e.bytes.byteLength>0)}bytesOf(e){let t=this.blocks.find(t=>t.filledRange.contains(e));return t?Nl(t,e):this.held.covers(e)?this.copyOf(e):void 0}release(e){this.blocks=this.blocks.filter(t=>!t.isComplete||!e.covers(t.filledRange))}fillingOf(e){let t=this.blocks.find(t=>t===e);return j(t!==void 0,`the block is not one this store holds`),t}copyOf(e){let t=new Uint8Array(e.length);for(let n of this.blocks){let r=Math.max(n.range.offset,e.offset),i=Math.min(n.filledRange.end,e.end);r<i&&t.set(n.bytes.subarray(r-n.range.offset,i-n.range.offset),r-e.offset)}return t}};function Nl(e,t){let n=t.offset-e.range.offset;return e.bytes.subarray(n,n+t.length)}var Pl=class{track;host;target;next;waiter;isClosed=!1;constructor(e,t,n){this.track=e,this.host=n,this.next=t.sample,this.target=t.target}get position(){return this.next}get isWaiting(){return this.waiter!==void 0}nextSample(){if(this.isClosed||this.next>=this.track.sampleCount)return Promise.resolve(void 0);j(this.waiter===void 0,`a cursor reads one sample at a time`);let e=this.track.rangeOf(this.next),t=this.host.bytesOf(e);if(t)return Promise.resolve(this.take(t));let n=this.host.failureOf(e);return n===void 0?this.waitForBytes():Promise.reject(n)}serve(){let{waiter:e}=this,t=e&&this.host.bytesOf(this.track.rangeOf(this.next));e&&t&&(this.waiter=void 0,e.resolve(this.take(t)))}fail(e,t){let{waiter:n}=this;n!==void 0&&e.overlaps(this.track.rangeOf(this.next))&&(this.waiter=void 0,n.reject(t))}close(){this.isClosed||(this.isClosed=!0,this.waiter?.resolve(void 0),this.waiter=void 0,this.host.closed(this))}waitForBytes(){return new Promise((e,t)=>{this.waiter={resolve:e,reject:t},this.host.changed()})}take(e){let t=this.next;return this.next+=1,this.host.changed(),{sample:t,bytes:e}}},Fl=class{parts;nextId=1;running=/* @__PURE__ */ new Map;constructor(e){this.parts=e}get states(){return[...this.running.values()].map(e=>({id:e.id,remaining:Il(e)}))}start(e){let t={id:this.nextId,block:this.parts.store.allocate(e),chunks:this.parts.stream.stream(e)[Symbol.asyncIterator](),delivered:0};this.nextId+=1,this.running.set(t.id,t),this.pump(t)}cancel(e){let t=this.running.get(e);t&&(this.running.delete(e),t.chunks.return?.(),this.parts.store.trim(t.block))}cancelAll(){for(let e of this.running.keys())this.cancel(e)}async pump(e){try{for(let t=await e.chunks.next();t.done!==!0;t=await e.chunks.next()){if(!this.isRunning(e))return;this.parts.store.write(e.block,t.value),e.delivered+=t.value.byteLength,this.parts.listener.onChunk()}this.finish(e)}catch(t){this.fail(e,t)}}finish(e){this.isRunning(e)&&(this.running.delete(e.id),this.parts.store.complete(e.block),this.parts.listener.onEnd())}fail(e,t){this.isRunning(e)&&(this.running.delete(e.id),this.parts.store.trim(e.block),this.parts.listener.onFailure(Il(e),t))}isRunning(e){return this.running.get(e.id)===e}};function Il(e){let{range:t}=e.block;return In.of(t.offset+e.delivered,t.length-e.delivered)}function Ll(e,t){let{track:n}=e,r=[];for(let i=e.sample;i<n.sampleCount&&!(n.timestampOf(i)>t);i+=1)r.push(n.rangeOf(i));return r}function Rl(e,t){let n=[],r=t;for(let t of e.ranges){if(r<=0)break;n.push(In.of(t.offset,Math.min(t.length,r))),r-=t.length}return Dl.of(n)}function zl(e){let{policy:t}=e,n=F(e.time+t.resumeSeconds),r=e.cursors.filter(e=>e.track.kind===`video`),i=Dl.of(r.flatMap(e=>Ll(e,n))),a=Math.min(t.requestSize,t.refillBytes);return Rl(i,t.aheadBytes-a)}function Bl(e){return zl(e).subtract(e.held).isEmpty}function Vl(e){let t=e.cursors.filter(e=>Yl(e)),n=t.length>0?Wl(t):e.anchor,r=n??Hl(e);if(!r)return Ul(e);let i=e.isReadingAhead?e.policy.aheadSeconds:0,a=F(r.time+i),o=Gl({state:e,windowStart:r,windowEnd:a}).bridgingGapsBelow(e.policy.bridgedGap),s=e.transfers.filter(e=>e.remaining.length===0||o.overlaps(e.remaining)),c=Dl.of(s.map(e=>e.remaining)),l=o.subtract(e.held).subtract(c).subtract(e.unreadable),u=e.policy.requestsInFlight-s.length;return{start:Zl({state:e,windowStart:r,windowEnd:a,missing:l,threshold:Xl(e,r)})?$l(l,e.policy,u):[],cancel:e.transfers.filter(e=>!s.includes(e)).map(e=>e.id),release:e.held.subtract(o.union(eu(r,e.policy))),anchor:n}}function Hl(e){return e.isReadingAhead&&e.cursors.length>0?Wl(e.cursors):void 0}function Ul(e){return{start:[],cancel:e.transfers.map(e=>e.id),release:Dl.empty,anchor:void 0}}function Wl(e){return{time:F(Math.min(...e.map(e=>ru(e)))),offset:Math.min(...e.map(e=>au(e))),keyframeOffset:Math.min(...e.map(e=>iu(e)))}}function Gl(e){let{state:t,windowEnd:n}=e,r=t.cursors.filter(t=>Kl(t,e)),i=r.flatMap(e=>Ll(e,Jl(n,e.target))),a=r.filter(e=>ql(e,n)),o=Dl.of(a.map(e=>e.track.rangeOf(e.sample)));return Rl(Dl.of(i),t.policy.aheadBytes).union(o)}function Kl(e,t){return ru(e)>=t.windowStart.time-t.state.policy.keepBehindSeconds}function ql(e,t){let n=e.isWaiting&&ru(e)<=t;return!nu(e)&&(Yl(e)||n)}function Jl(e,t){return t!==void 0&&t>e?t:e}function Yl(e){return e.track.kind===`video`}function Xl(e,t){let n={cursors:e.cursors,time:t.time,policy:e.policy};return e.isReadingAhead?zl(n):Dl.empty}function Zl(e){let{state:t,missing:n,threshold:r}=e;return n.ranges.some(e=>r.overlaps(e))?!0:t.cursors.some(t=>Ql(t,e)&&n.overlaps(t.track.rangeOf(t.sample)))||n.totalLength>=t.policy.refillBytes}function Ql(e,t){if(!e.isWaiting||nu(e))return!1;let{windowStart:n,state:r}=t,i=n.time+(r.isReadingAhead?r.policy.resumeSeconds:0);return Yl(e)||ru(e)<=i}function $l(e,t,n){let r=[];for(let i of e.ranges)for(let e=i.offset;e<i.end&&r.length<n;e+=t.requestSize)r.push(In.of(e,Math.min(t.requestSize,i.end-e)));return r}function eu(e,t){let n=tu(e,t);return Dl.of([In.of(n,e.offset-n)])}function tu(e,t){return Math.max(0,Math.min(e.keyframeOffset,e.offset-t.keepBehindBytes))}function nu(e){return e.sample>=e.track.sampleCount}function ru(e){return nu(e)?e.track.end:e.track.timestampOf(e.sample)}function iu(e){let{track:t}=e,n=Math.min(e.sample,t.sampleCount-1),r=t.syncSampleAtOrBefore(n);return r===void 0?au(e):t.rangeOf(r).offset}function au(e){let{track:t}=e;return nu(e)?t.sampleCount>0?t.rangeOf(t.sampleCount-1).end:0:t.rangeOf(e.sample).offset}var ou=In.of(0,2**53-1),su=class{parts;store=new Ml;progressListeners=/* @__PURE__ */ new Set;transfers;cursors=/* @__PURE__ */ new Set;host;failures=[];anchor;isReadingAhead=!1;isPlanDue=!1;isDisposed=!1;constructor(e){this.parts=e,this.transfers=new Fl({stream:e.stream,store:this.store,listener:{onChunk:()=>{this.serveCursors();for(let e of this.progressListeners)e()},onEnd:()=>{this.schedulePlan()},onFailure:(e,t)=>{this.fail(e,t)}}}),this.host=this.cursorHost()}openCursor(e,t,n){j(this.parts.table.tracks.includes(e),`the track is not one of this file`);let r=new Pl(e,{sample:t,target:n},this.host);return this.isDisposed?(r.close(),r):(this.failures=[],this.cursors.add(r),this.schedulePlan(),r)}startReadingAhead(){this.isReadingAhead=!0,this.schedulePlan()}isReadyToResumeAt(e){return Bl({cursors:this.positions(),held:this.store.held,time:e,policy:this.parts.policy})}onProgress(e){let t=()=>{e()};return this.progressListeners.add(t),()=>{this.progressListeners.delete(t)}}dispose(){this.isDisposed=!0,this.transfers.cancelAll();for(let e of this.cursors)e.close()}cursorHost(){return{bytesOf:e=>this.store.bytesOf(e),failureOf:e=>this.failures.find(t=>t.range.overlaps(e))?.error,changed:()=>{this.schedulePlan()},closed:e=>{this.cursors.delete(e),this.schedulePlan()}}}schedulePlan(){this.isPlanDue||this.isDisposed||(this.isPlanDue=!0,this.planAfterThisTurn())}async planAfterThisTurn(){if(await Promise.resolve(),this.isPlanDue=!1,!this.isDisposed)try{this.plan()}catch(e){this.failEveryRead(e)}}failEveryRead(e){let t=re(e,`invariant-violation`,`the download could not plan`);this.failures.push({range:ou,error:t});for(let e of this.cursors)e.fail(ou,t)}plan(){let e=Vl({cursors:this.positions(),held:this.store.held,transfers:this.transfers.states,unreadable:Dl.of(this.failures.map(e=>e.range)),isReadingAhead:this.isReadingAhead,anchor:this.anchor,policy:this.parts.policy});this.anchor=e.anchor,this.carryOut(e)}positions(){return[...this.cursors].map(e=>({track:e.track,sample:e.position,isWaiting:e.isWaiting,target:e.target}))}carryOut(e){for(let t of e.cancel)this.transfers.cancel(t);this.store.release(e.release);for(let t of e.start)this.transfers.start(t)}serveCursors(){for(let e of this.cursors)e.serve()}fail(e,t){let n=re(t,`source-unreadable`,`a range of the recording could not be read`);this.failures.push({range:e,error:n});for(let t of this.cursors)t.fail(e,n);this.schedulePlan()}};function cu(e){let t=new su(e);return{download:t,videoTracks:e.codecs.video.map(n=>new Tl({download:t,track:lu(e.table,n.trackId,`video`),codec:n})),audioTracks:e.codecs.audio.map(n=>({samples:new Cl({download:t,track:lu(e.table,n.trackId,`audio`)}),configuration:n.configuration})),duration:e.table.duration,dispose:()=>{t.dispose()}}}function lu(e,t,n){let r=e.trackWithId(t);if(r?.kind!==n)throw new A(`unsupported-container`,`the movie box has no ${n} track ${t} to read`);return r}var uu=1048576,du=10,fu=128,pu=2,mu=32,hu=8,gu=2,_u=1,vu=.25,yu=4;function bu(e,t){let n=e.size/e.duration,r=Math.min(Math.round(du*n),fu*uu/t);return{aheadSeconds:F(du),aheadBytes:r,keepBehindBytes:Math.min(Math.round(pu*n),mu*uu/t),keepBehindSeconds:F(pu),requestSize:hu*uu,requestsInFlight:gu,bridgedGap:_u*uu,refillBytes:Math.round(r*vu),resumeSeconds:F(yu)}}var xu=class{files;constructor(e){this.files=e}isReadyToResumeAt(e){return this.files.every(t=>t.isReadyToResumeAt(e))}onProgress(e){let t=this.files.map(t=>t.onProgress(e));return()=>{for(let e of t)e()}}};function Su(e){for(let t of e.frames)t.close()}var Cu=class{capacity;onPush;pairs=[];roomWaiters=[];isClosed=!1;constructor(e,t=wu){this.capacity=e,this.onPush=t,j(Number.isSafeInteger(e)&&e>0,`queue capacity must be positive`)}get length(){return this.pairs.length}get isFull(){return this.pairs.length>=this.capacity}get isClosedForGood(){return this.isClosed}waitForRoom(){return!this.isFull||this.isClosed?Promise.resolve():new Promise(e=>{this.roomWaiters.push(e)})}push(e){if(this.isClosed){Su(e);return}this.pairs.push(e),this.onPush()}takePairAt(e){let t;for(;this.pairs.length>0&&(this.pairs[0]?.timestamp??1/0)<=e;)t&&Su(t),t=this.pairs.shift();return t&&this.wakeWaiters(),t}peekTimestamp(){return this.pairs[0]?.timestamp}newestTimestamp(){return this.pairs.at(-1)?.timestamp}close(){this.isClosed=!0;for(let e of this.pairs)Su(e);this.pairs.length=0,this.wakeWaiters()}wakeWaiters(){if(this.isFull&&!this.isClosed)return;let e=this.roomWaiters;this.roomWaiters=[];for(let t of e)t()}};function wu(){}var Tu=class{tolerance;onPair;queues;unpairedCount=0;constructor(e,t,n){this.tolerance=t,this.onPair=n,this.queues=Array.from({length:e},()=>[])}get unpaired(){return this.unpairedCount}push(e,t){se(e,this.queues.length,`frame source`),this.queues[e]?.push(t),this.drain()}discardAll(){for(let e of this.queues){for(let t of e)t.close();e.length=0}}drain(){for(;this.queues.every(e=>e.length>0);){let e=this.queues.map(e=>e[0]).filter(e=>e!==void 0),t=Math.min(...e.map(e=>e.timestamp));e.every(e=>Math.abs(e.timestamp-t)<=this.tolerance)?this.emit(e,F(t)):this.dropHeadAt(t)}}emit(e,t){for(let e of this.queues)e.shift();this.onPair({timestamp:t,frames:e})}dropHeadAt(e){this.queues.find(t=>t[0]?.timestamp===e)?.shift()?.close(),this.unpairedCount+=1}},Eu=class{from;deliver;held;droppedCount=0;constructor(e,t){this.from=e,this.deliver=t}get dropped(){return this.droppedCount}push(e){if(e.timestamp>=this.from){this.release(),this.deliver(e);return}this.hold(e)}release(){if(!this.held)return;let e=this.held;this.held=void 0,this.deliver(e)}discard(){this.held&&Su(this.held),this.held=void 0}hold(e){this.held&&(Su(this.held),this.droppedCount+=1),this.held=e}},Du=class{promise;isSettledNow=!1;resolvePromise;rejectPromise;constructor(){this.promise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})}get isSettled(){return this.isSettledNow}resolve(e){this.isSettledNow||(this.isSettledNow=!0,this.resolvePromise?.(e))}reject(e){this.isSettledNow||(this.isSettledNow=!0,this.rejectPromise?.(e))}async follow(e){try{this.resolve(await e)}catch(e){this.reject(e)}}},Ou=Symbol(`stopped`),ku=class{isStopped=!1;wakeWaiter;get wasStopped(){return this.isStopped}stop(){this.isStopped=!0,this.wakeWaiter?.()}async race(e){if(this.isStopped)return Ou;j(this.wakeWaiter===void 0,`a run stop races one wait at a time`);let t=new Promise(e=>{this.wakeWaiter=()=>{e(Ou)}});try{return await Promise.race([e(),t])}finally{this.wakeWaiter=void 0}}},Au=class{frameSources;decoderPort;options;stop=new ku;hasRun=!1;iterators=[];constructor(e,t,n){if(this.frameSources=e,this.decoderPort=t,this.options=n,e.length===0)throw new A(`invariant-violation`,`a decode pipeline needs at least one frame source`)}async run(e,t){j(!this.hasRun,`a decode pipeline runs once; create a new one for each run`),this.hasRun=!0;let n=await this.openRun(e,t);try{let e=await this.feed(n);if(await Mu(n,e),n.failure.isSettled)throw await n.failure.promise;return Iu(n,e)}finally{Pu(n)}}abort(){this.stop.stop(),Fu(this.iterators)}async openRun(e,t){let{stop:n}=this,r=new Du,i={packets:0,pairs:0},a=new Eu(e,e=>{i.pairs+=1,t.push(e)}),o=new Tu(this.frameSources.length,this.options.pairTolerance,e=>{a.push(e)}),s=n.wasStopped?[]:this.packetIteratorsFrom(e);this.iterators=s;let c=e=>{r.resolve(e),n.stop()};try{return{output:t,stop:n,failure:r,tally:i,gate:a,pairer:o,iterators:s,decoders:n.wasStopped?[]:await this.createDecoders(o,c)}}catch(e){throw Fu(s),e}}async createDecoders(e,t){let n=await Promise.allSettled(this.frameSources.map(async(n,r)=>this.decoderPort.create(await n.decoderConfiguration(),{onFrame:t=>{e.push(r,t)},onError:t}))),r=n.flatMap(e=>e.status===`fulfilled`?[e.value]:[]),i=n.find(e=>e.status===`rejected`);if(i){for(let e of r)e.close();throw Lu(i.reason)}return r}async feed(e){for(;!ju(e);){if(await e.stop.race(()=>e.output.waitForRoom()),ju(e))return!1;let t=await e.stop.race(()=>Ru(e.iterators));if(t===Ou)return!1;if(!t)return!0;await this.decodeRound(e,t)}return!1}async decodeRound(e,t){for(let[n,r]of e.decoders.entries()){let i=t[n];if(i){if(await e.stop.race(()=>r.waitForPendingBelow(this.options.maxPendingPackets)),ju(e))return;r.decode(i),e.tally.packets+=1}}}packetIteratorsFrom(e){return this.frameSources.map(t=>t.packetsFrom(e)[Symbol.asyncIterator]())}};function ju(e){return e.stop.wasStopped||e.output.isClosedForGood}async function Mu(e,t){await e.stop.race(()=>Nu(e.decoders,e.failure))!==Ou&&t&&e.gate.release()}async function Nu(e,t){try{await Promise.all(e.map(e=>e.flush()))}catch(e){if(!t.isSettled)throw e}}function Pu(e){for(let t of e.decoders)t.close();e.pairer.discardAll(),e.gate.discard(),Fu(e.iterators)}function Fu(e){for(let t of e)t.return?.()}function Iu(e,t){return{packetsDecoded:e.tally.packets,pairsDelivered:e.tally.pairs,unpairedFrames:e.pairer.unpaired,pairsDroppedBeforeStart:e.gate.dropped,hasReachedEnd:t}}function Lu(e){return e instanceof Error?e:new A(`decode`,`a decoder could not be created`,{cause:e})}async function Ru(e){let t=await Promise.all(e.map(e=>e.next())),n=[];for(let e of t){if(e.done===!0)return;n.push(e.value)}return n}var zu={verdict:`decodes`,detail:void 0},Bu={verdict:`no-key-frame`,detail:`the track has no key frame`},Vu={verdict:`decode-failed`,detail:`the decoder accepted the first key frame but produced no picture`},Hu={verdict:`timed-out`,detail:`the decoder produced no picture before the deadline`},Uu={verdict:`key-frame-late`,detail:`the first key frame did not arrive before the deadline`};async function Wu(e,t,n){let r=e.map(e=>new qu(e,t));try{let e=await Promise.all(r.map(e=>Gu(e,n)));return{canDecode:e.every(e=>e.verdict===`decodes`),sources:e}}finally{for(let e of r)e.close()}}async function Gu(e,t){try{let n=await Promise.race([e.run(),Ku(t,e)]);return{track:e.track.description,...n}}finally{e.close()}}async function Ku(e,t){return await e.promise,t.outcomeAtDeadline}var qu=class{track;decoderPort;decoder;firstOutcome;isClosed=!1;isReadingKeyFrame=!1;constructor(e,t){this.track=e,this.decoderPort=t}get outcomeAtDeadline(){return this.isReadingKeyFrame?Uu:Hu}async run(){let e=await this.track.decoderConfiguration();if(!await this.decoderPort.isSupported(e))return Ju(e);if(this.isClosed)return Hu;let t=await this.track.firstKeyframe();if(!t)return Bu;this.isReadingKeyFrame=!0;let n=await Xu(this.track,t.timestamp);return this.isReadingKeyFrame=!1,n?await this.decodeFirst(e,n):Bu}close(){this.isClosed=!0,this.decoder?.close(),this.decoder=void 0,this.firstOutcome?.resolve(Hu)}async decodeFirst(e,t){if(this.isClosed)return Hu;let n=new Du;this.firstOutcome=n;let r=await this.openDecoder(e,n);return r===void 0?n.promise:(this.decoder=r,this.decodeInto(r,t,n),n.promise)}async openDecoder(e,t){try{let n=await this.decoderPort.create(e,{onFrame:e=>{e.close(),t.resolve(zu)},onError:e=>{t.resolve(Yu(e))}});if(!this.isClosed)return n;n.close(),t.resolve(Hu)}catch(e){t.resolve(Yu(e))}}async decodeInto(e,t,n){try{e.decode(t),await e.flush(),n.resolve(Vu)}catch(e){n.resolve(Yu(e))}}};function Ju(e){return{verdict:`unsupported-configuration`,detail:`${e.codec} at ${e.codedWidth}x${e.codedHeight} is not supported here`}}function Yu(e){let t=oe(e);return{verdict:ae(e,`codec-unsupported`)?`unsupported-configuration`:`decode-failed`,detail:t}}async function Xu(e,t){let n=e.packetsFrom(t)[Symbol.asyncIterator]();try{let e=await n.next();return e.done===!0?void 0:e.value}finally{n.return?.()}}var Zu=class{now;hasEnded=!1;failure=void 0;isRunningNow=!1;positionAtAnchor=F(0);anchorMs=0;constructor(e){this.now=e}get isRunning(){return this.isRunningNow}get currentTime(){if(!this.isRunningNow)return this.positionAtAnchor;let e=_t(mt(this.now()-this.anchorMs));return F(this.positionAtAnchor+e)}start(){return this.isRunningNow||=(this.anchorMs=this.now(),!0),Promise.resolve()}pause(){this.isRunningNow&&=(this.positionAtAnchor=this.currentTime,!1)}seek(e){this.positionAtAnchor=e,this.anchorMs=this.now()}dispose(){this.pause()}},Qu={ready:[`playing`,`buffering`,`paused`,`seeking`,`error`,`disposed`],playing:[`buffering`,`paused`,`seeking`,`ended`,`error`,`disposed`],buffering:[`playing`,`paused`,`seeking`,`error`,`disposed`],paused:[`playing`,`buffering`,`seeking`,`error`,`disposed`],seeking:[`buffering`,`paused`,`error`,`disposed`],ended:[`seeking`,`error`,`disposed`],error:[`disposed`],disposed:[]},$u=/* @__PURE__ */ new Set([`playing`,`buffering`]);function ed(e){return e!==void 0&&$u.has(e)}var td=class{current=`ready`;get state(){return this.current}canTransitionTo(e){return Qu[this.current].includes(e)}transitionTo(e){if(!this.canTransitionTo(e))throw new A(`invariant-violation`,`player cannot go from ${this.current} to ${e}`);this.current=e}isOneOf(...e){return e.includes(this.current)}},nd=class{reportListenerError;listeners=/* @__PURE__ */ new Map;constructor(e=Vc){this.reportListenerError=e}on(e,t){let n=this.listeners.get(e)??/* @__PURE__ */ new Set;return n.add(t),this.listeners.set(e,n),()=>{n.delete(t)}}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r=[...n];for(let e of r)if(n.has(e))try{e(t)}catch(e){this.reportListenerError(e)}}removeAll(){for(let e of this.listeners.values())e.clear();this.listeners.clear()}},rd=1,id=.25,ad=class{position;previousPlayingTick;placedAt(e){this.position=e}stoppedAt(e){(this.position===void 0||e>=this.position)&&(this.position=e)}playingFrom(e){this.previousPlayingTick=e}wasMovedFromOutside({now:e,state:t}){let n=this.position;return this.position=e,n!==void 0&&(t===`playing`?n-e:Math.abs(e-n))>id}wereTicksMissed({now:e,state:t}){let n=t===`playing`,r=this.previousPlayingTick;this.previousPlayingTick=n?e:void 0;let i=r===void 0?0:e-r;return n&&i>rd}};function od(e){return!e.isRunning&&!e.hasEnded}function sd(e,t){return e.hasEnded||e.currentTime>=t}var cd=class{generation=0;scrubs=0;isFromFlowing=!1;get resumesPlaying(){return this.isFromFlowing}begin(e){this.isFromFlowing=ed(e),this.generation+=1}claimScrub(){return this.scrubs+=1,{seek:this.generation,scrub:this.scrubs}}isScrubCurrent(e){return e.seek===this.generation&&e.scrub===this.scrubs}},ld=.25,ud=class{lifecycle;announced;constructor(e){this.lifecycle=e}announce(e){this.announced=e,this.lifecycle.announce(`timeupdate`,e)}followPlayback(e){let{announced:t}=this;(t===void 0||Math.abs(e-t)>=ld)&&this.announce(e)}},dd=class{lifecycle;cause=`priming`;startAttempt;constructor(e){this.lifecycle=e}get waitingStart(){return this.startAttempt?.promise}enter(e){this.cause=e,this.lifecycle.moveTo(`buffering`)}enterForStart(){let e=new Du;return this.startAttempt=e,this.enter(`priming`),e.promise}isOverAt(e,t){return!e||!this.lifecycle.is(`buffering`)?!1:this.cause===`priming`?e.isPrimedAt(t):e.isReadyToResumeAt(t)}takeStart(){let e=this.startAttempt;return this.startAttempt=void 0,e}settleStart(){this.takeStart()?.resolve()}},fd=class{machine=new td;outbox;constructor(e){this.outbox=new vl(e)}get current(){return this.machine.state}is(e){return this.machine.state===e}isOneOf(...e){return this.machine.isOneOf(...e)}canMoveTo(e){return this.machine.canTransitionTo(e)}moveTo(e){this.machine.transitionTo(e),this.announce(`statechange`,e)}announce(e,t){this.outbox.emit(e,t)}change(e){return this.outbox.change(e)}},pd=2,md=.25,hd=class e{parts;listener;queue;pipeline;primingPairs;stopFollowingBuffer;isAborted=!1;hasReachedEnd=!1;hasHandedOutPair=!1;constructor(e,t){this.parts=e,this.listener=t,this.primingPairs=Math.min(pd,e.queueCapacity),this.queue=new Cu(e.queueCapacity,()=>{this.isAborted||t.onProgress()}),this.stopFollowingBuffer=e.buffer?.onProgress(()=>{t.onProgress()})??(()=>void 0),this.pipeline=new Au(e.frameSources,e.decoderPort,e.pipeline)}static start(t,n,r){let i=new e(t,r);return i.follow(i.pipeline.run(n,i.queue)),i}get isDrained(){return this.hasReachedEnd&&this.queue.length===0}isPrimedAt(e){let t=(this.queue.newestTimestamp()??-1/0)>=e;return this.hasReachedEnd||t&&this.queue.length>=this.primingPairs}isReadyToResumeAt(e){return this.isPrimedAt(e)&&(this.hasReachedEnd||(this.parts.buffer?.isReadyToResumeAt(e)??!0))}isStarvedAt(e,t){let n=this.queue.length===0&&!this.hasReachedEnd,r=e-(t??-1/0);return n&&r>md}takePairAt(e){let t=this.queue.peekTimestamp(),n=!this.hasHandedOutPair&&t!==void 0,r=this.queue.takePairAt(n?F(Math.max(e,t)):e);return r&&(this.hasHandedOutPair=!0),r}abort(){this.isAborted=!0,this.stopFollowingBuffer(),this.pipeline.abort(),this.queue.close()}async follow(e){try{let{hasReachedEnd:t}=await e;if(this.isAborted)return;this.hasReachedEnd=t,this.listener.onProgress()}catch(e){this.isAborted||this.listener.onFailure(e)}}};async function gd(e,t){try{return(await e.keyframeAt(t))?.timestamp??t}catch{return t}}var _d=class{parts;events=new nd;lifecycle=new fd(this.events);run;presented;timeUpdates=new ud(this.lifecycle);buffering=new dd(this.lifecycle);clockWatch=new ad;seeks=new cd;constructor(e){this.parts=e}get state(){return this.lifecycle.current}get currentTime(){return this.parts.clock.currentTime}async play(){if(this.lifecycle.current!==`playing`){if(this.lifecycle.current===`buffering`){await this.buffering.waitingStart;return}await this.lifecycle.change(()=>this.beginStart())}}pause(){this.lifecycle.change(()=>{let e=this.parts.clock.isRunning;this.parts.clock.pause(),e&&this.clockWatch.stoppedAt(this.parts.clock.currentTime),this.lifecycle.canMoveTo(`paused`)&&(this.lifecycle.moveTo(`paused`),this.buffering.settleStart(),this.timeUpdates.announce(this.parts.clock.currentTime))})}stop(){this.lifecycle.change(()=>{this.pause(),this.seek(F(0))})}seek(e){this.lifecycle.isOneOf(`disposed`,`error`)||this.lifecycle.change(()=>{let t=F(br(e,0,this.parts.duration));this.seeks.begin(this.lifecycle.current),this.moveClockTo(t),this.startRun(t),this.lifecycle.moveTo(`seeking`),this.seeks.resumesPlaying?this.buffering.enter(`priming`):this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(t)})}async scrub(e){let[t]=this.parts.frameSources;if(!t||this.lifecycle.isOneOf(`disposed`,`error`))return;let n=F(br(e,0,this.parts.duration)),r=this.seeks.claimScrub(),i=await gd(t,n);this.seeks.isScrubCurrent(r)&&!this.lifecycle.isOneOf(`disposed`,`error`)&&this.seek(i)}preload(){this.run||this.lifecycle.current!==`ready`||this.lifecycle.change(()=>{this.startRun(this.parts.clock.currentTime)})}tick(){this.lifecycle.isOneOf(`disposed`,`error`)||this.lifecycle.change(()=>{let{failure:e}=this.parts.clock;if(e){this.fail(e);return}let t=this.parts.clock.currentTime;if(this.clockWatch.wasMovedFromOutside({now:t,state:this.lifecycle.current})){this.followMoveFromOutside(t);return}if(this.haveTicksStopped(t)){this.restartAt(t);return}this.presentDue(t),this.lifecycle.is(`playing`)?this.followClock(t):this.isStartedFromOutside()&&this.followStartFromOutside()})}redraw(){if(!this.presented||this.lifecycle.isOneOf(`playing`,`error`))return;let{presented:e}=this;this.lifecycle.change(()=>this.draw(e))}dispose(){this.lifecycle.current!==`disposed`&&(this.lifecycle.change(()=>{this.abortRun(),this.presented&&Su(this.presented.pair),this.presented=void 0,this.parts.clock.pause(),this.lifecycle.moveTo(`disposed`),this.buffering.settleStart()}),this.events.removeAll())}beginStart(){if(this.isAtTheEnd()&&this.seek(F(0)),this.lifecycle.canMoveTo(`buffering`))return this.run||this.startRun(this.parts.clock.currentTime),this.isPrimed()?(this.enterPlaying(),this.startClockOnceHeard()):this.startOncePrimed()}startOncePrimed(){return this.parts.clock.pause(),this.buffering.enterForStart()}async startClockOnceHeard(){await Promise.resolve(),this.lifecycle.is(`playing`)&&await this.startClock()}enterPlaying(){this.clockWatch.playingFrom(this.parts.clock.currentTime),this.lifecycle.moveTo(`playing`)}presentDue(e){let t=this.run?.takePairAt(e);t&&this.present(t,e)}followClock(e){if(this.isPlayedOut(e)){this.end();return}if(od(this.parts.clock)){this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(e);return}if(this.run?.isStarvedAt(e,this.presented?.pair.timestamp)===!0){this.parts.clock.pause(),this.buffering.enter(`starvation`);return}this.timeUpdates.followPlayback(e)}isStartedFromOutside(){return this.parts.clock.isRunning&&this.lifecycle.isOneOf(`ready`,`paused`,`ended`)}async followStartFromOutside(){try{await this.play()}catch{}}moveClockTo(e){this.parts.clock.pause(),this.parts.clock.seek(e),this.clockWatch.placedAt(this.parts.clock.currentTime)}followMoveFromOutside(e){let t=this.parts.clock.isRunning;!t&&this.lifecycle.is(`playing`)&&this.pause(),this.seek(e),t&&this.lifecycle.is(`paused`)&&this.followStartFromOutside()}haveTicksStopped(e){return this.clockWatch.wereTicksMissed({now:e,state:this.lifecycle.current})&&!this.parts.clock.hasEnded}restartAt(e){let{clock:t,duration:n}=this.parts;if(e>=n){this.moveClockTo(n),this.end();return}let r=t.isRunning;if(t.pause(),this.startRun(e),r){this.buffering.enter(`priming`);return}this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(e)}isAtTheEnd(){return this.lifecycle.current===`ended`||sd(this.parts.clock,this.parts.duration)}isPrimed(){return this.run?.isPrimedAt(this.parts.clock.currentTime)===!0}resumeIfPrimed(){this.buffering.isOverAt(this.run,this.parts.clock.currentTime)&&this.resume()}async resume(){let e=this.buffering.takeStart();this.enterPlaying();try{await this.startClockOnceHeard(),e?.resolve()}catch(t){e?.reject(t)}}async startClock(){try{await this.parts.clock.start()}catch(e){throw this.lifecycle.is(`playing`)&&this.lifecycle.moveTo(`paused`),e}}isPlayedOut(e){let t=this.run?.isDrained===!0&&e>=this.parts.duration;return this.parts.clock.hasEnded||t}present(e,t){this.presented&&Su(this.presented.pair),this.presented={pair:e,mediaTime:t},this.draw(this.presented)&&this.lifecycle.announce(`present`,t)}draw(e){try{return this.parts.sink.present(e),!0}catch(e){return this.fail(re(e,`render-unavailable`,`the picture could not be drawn`)),!1}}startRun(e){this.abortRun(),this.run=hd.start(this.parts,e,{onProgress:()=>{this.resumeIfPrimed()},onFailure:e=>{this.fail(e)}})}abortRun(){this.run?.abort(),this.run=void 0}end(){this.lifecycle.canMoveTo(`ended`)&&(this.parts.clock.pause(),this.lifecycle.moveTo(`ended`),this.timeUpdates.announce(this.parts.clock.currentTime),this.lifecycle.announce(`ended`,void 0))}fail(e){this.lifecycle.canMoveTo(`error`)&&this.lifecycle.change(()=>{this.parts.clock.pause(),this.abortRun(),this.lifecycle.moveTo(`error`),this.buffering.settleStart(),this.lifecycle.announce(`error`,re(e,`decode`,`playback failed`))})}};function vd(e,t){if(e===null)return;let n=e.trim().toLowerCase();return t.find(e=>e===n)}function yd(e){return vd(e,Xo)}function bd(e){return vd(e,Os)}function xd(e){return vd(e,ws)}function Sd(e,t){for(let n of t)Object.defineProperty(e,kd(n),{configurable:!0,enumerable:!0,get(){return this.getAttribute(n)},set(e){Dd(this,n,e)}})}function Cd(e,t){for(let n of t)Object.defineProperty(e,kd(n),{configurable:!0,enumerable:!0,get(){return this.hasAttribute(n)},set(e){this.toggleAttribute(n,!!e)}})}function wd(e,t){for(let n of t)Object.defineProperty(e,kd(n.name),{configurable:!0,enumerable:!0,get(){return Ed(n,this.getAttribute(n.name))},set(e){Dd(this,n.name,e)}})}function Td(e,t){for(let n of t)Object.defineProperty(e,n.property,{configurable:!0,enumerable:!0,get(){let e=this.getAttribute(n.name);return e===null?null:Ed(n,e)},set(e){Dd(this,n.name,e)}})}function Ed(e,t){let n=t?.trim().toLowerCase();return e.keywords.find(e=>e===n)??e.fallback}function Dd(e,t,n){if(n==null){e.removeAttribute(t);return}e.setAttribute(t,n)}var Od=/-(?<letter>[a-z])/gu;function kd(e){return e.replaceAll(Od,(e,t)=>t.toUpperCase())}function Ad(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new A(`invalid-argument`,`${t} must be a finite number`)}function jd(e){return Ad(e.yaw,`yaw`),Ad(e.pitch,`pitch`),Ad(e.fieldOfView,`fieldOfView`),{yaw:t(e.yaw),pitch:t(e.pitch),fieldOfView:t(e.fieldOfView)}}var Md=/* @__PURE__ */ new Map([[` `,`toggle-play`],[`k`,`toggle-play`],[`j`,`seek-back`],[`l`,`seek-forward`],[`s`,`stop`],[`m`,`toggle-mute`],[`f`,`toggle-fullscreen`],[`0`,`reset-view`],[`+`,`zoom-in`],[`=`,`zoom-in`],[`-`,`zoom-out`],[`ArrowLeft`,`look-left`],[`ArrowRight`,`look-right`],[`ArrowUp`,`look-up`],[`ArrowDown`,`look-down`]]),Nd=/* @__PURE__ */ new Map([[`ArrowLeft`,`seek-back`],[`ArrowRight`,`seek-forward`]]);function Pd(e){if(!e.hasSystemModifier)return e.key.length===1?Md.get(e.key.toLowerCase()):e.isShiftPressed?Nd.get(e.key):Md.get(e.key)}var Fd=5;function Id(e){return({player:t})=>{t.seek(t.currentTime+e)}}function Ld(e,t){return({player:n})=>{n.turn(e,t)}}var Rd={"toggle-play":e=>{e.togglePlay()},stop:({player:e})=>{e.stop()},"seek-back":Id(-5),"seek-forward":Id(5),"toggle-mute":({player:e})=>{e.setMuted(!e.isMuted)},"toggle-fullscreen":e=>{e.toggleFullscreen()},"reset-view":({player:e})=>{e.resetView()},"zoom-in":({player:e})=>{e.zoom(1)},"zoom-out":({player:e})=>{e.zoom(-1)},"look-left":Ld(-5,0),"look-right":Ld(Fd,0),"look-up":Ld(0,Fd),"look-down":Ld(0,-5)};function zd(e,t){let n=new AbortController;return e.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&t.isFullscreen()){t.exitFullscreen();return}let n=Pd({key:e.key,isShiftPressed:e.shiftKey,hasSystemModifier:e.ctrlKey||e.altKey||e.metaKey});n&&!Hd(e)&&(e.preventDefault(),Rd[n](t))},{signal:n.signal}),()=>{n.abort()}}var Bd=/* @__PURE__ */ new Set([`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`]),Vd=` `;function Hd(e){let[t]=e.composedPath();return t instanceof HTMLInputElement?Bd.has(e.key):t instanceof HTMLButtonElement&&e.key===Vd}var Ud=100,Wd=`data-draggable`,Gd=0,Kd=4,qd=class{surface;player;onTap;pointers=/* @__PURE__ */ new Map;listening=new AbortController;dragDistance=0;constructor(e,t,n){this.surface=e,this.player=t,this.onTap=n;let{signal:r}=this.listening;e.addEventListener(`pointerenter`,this.reflectDraggable,{signal:r}),e.addEventListener(`pointerdown`,this.onPointerDown,{signal:r}),e.addEventListener(`pointermove`,this.onPointerMove,{signal:r}),e.addEventListener(`pointerup`,this.onPointerUp,{signal:r}),e.addEventListener(`pointercancel`,this.onPointerCancel,{signal:r}),e.addEventListener(`lostpointercapture`,this.onPointerCancel,{signal:r}),e.addEventListener(`wheel`,this.onWheel,{passive:!1,signal:r})}detach(){this.listening.abort(),this.pointers.clear(),this.surface.removeAttribute(Wd)}onPointerDown=e=>{(e.pointerType!==`mouse`||e.button===Gd)&&(this.pointers.size===0&&(this.dragDistance=0),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.surface.setPointerCapture(e.pointerId))};onPointerMove=e=>{this.reflectDraggable();let t=this.pointers.get(e.pointerId);if(!t)return;let n={x:e.clientX,y:e.clientY};this.pointers.size===1?this.pan(t,n):this.pinch(e.pointerId,n),this.pointers.set(e.pointerId,n)};onPointerUp=e=>{!this.pointers.delete(e.pointerId)||this.pointers.size>0||this.dragDistance<Kd&&this.onTap(e.pointerType)};onPointerCancel=e=>{this.pointers.delete(e.pointerId),this.dragDistance=1/0};onWheel=e=>{e.preventDefault();let t={x:e.clientX,y:e.clientY};this.player.zoom(-e.deltaY/Ud,this.focusAt(t)),this.reflectDraggable()};reflectDraggable=()=>{this.surface.toggleAttribute(Wd,this.player.canPan)};pan(e,t){let n={x:t.x-e.x,y:t.y-e.y};this.dragDistance+=Math.hypot(n.x,n.y),this.player.pan(n)}pinch(e,t){let n=[...this.pointers].find(([t])=>t!==e)?.[1],r=this.pointers.get(e);if(!n||!r)return;this.dragDistance=1/0;let i=$s(Jd(r,n),Jd(t,n)),a={x:(t.x+n.x)/2,y:(t.y+n.y)/2};this.player.zoom(i,this.focusAt(a))}focusAt(e){let t=this.surface.getBoundingClientRect();return{x:(e.x-t.left)/Math.max(t.width,1),y:(e.y-t.top)/Math.max(t.height,1)}}};function Jd(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Yd(e,t,n={}){let r=new qd(e,t,n.onTap??(()=>{Zd(t)}));return()=>{r.detach()}}function Xd(e,t,n={}){let r=()=>e.matches(`:fullscreen`);return zd(e,{player:t,togglePlay:()=>{Zd(t)},toggleFullscreen:n.toggleFullscreen??(()=>{r()?document.exitFullscreen():e.requestFullscreen()}),isFullscreen:r,exitFullscreen:()=>{document.exitFullscreen()}})}function Zd(e){if(!e.isPaused){e.pause();return}e.play().catch(t=>{e.events.emit(`warning`,{code:`playback-failed`,message:`playback could not start: ${oe(t)}`})})}var Qd=class{blob;constructor(e){this.blob=e}size(){return Promise.resolve(this.blob.size)}async read(e){if(e.ensureWithin(this.blob.size,`blob`),e.length===0)return/* @__PURE__ */ new Uint8Array;let t=await this.bytesOf(this.blob.slice(e.offset,e.end));if(t.byteLength!==e.length)throw new A(`source-truncated`,`the blob yielded ${t.byteLength} bytes for a ${e.length}-byte range at ${e.offset}; the file may have changed on disk`);return t}async bytesOf(e){try{return new Uint8Array(await e.arrayBuffer())}catch(e){throw new A(`source-unreadable`,`the blob could not be read`,{cause:e})}}},$d=/^bytes (\d+)-(\d+)\/(\d+|\*)$/u,ef=`*`;function tf(e){let t=$d.exec(e.headers.get(`content-range`)??``);if(!t)return;let[,n,r,i]=t;return{first:Number(n),last:Number(r),total:i===ef?void 0:Number(i)}}var nf=/* @__PURE__ */ new WeakSet;function rf(e){return nf.add(e),e}function af(e){return e instanceof A&&nf.has(e)}function of(e){return ae(e,`source-unreadable`)&&e instanceof Error?rf(new A(`source-unreadable`,e.message,{cause:e.cause})):e}function sf(e,t,n){return rf(new A(`source-unreadable`,`${e} broke off the ${t.length}-byte range at ${t.offset}`,{cause:n}))}function cf(e,t,n){return new A(`source-truncated`,`${e} returned ${t} bytes for a ${n.length}-byte range at ${n.offset}`)}var lf=1e4,uf=class{resource;stallTimeoutMs;constructor(e,t={}){this.resource=e,this.stallTimeoutMs=t.stallTimeoutMs??lf}stream(e){return{[Symbol.asyncIterator]:()=>new df({resource:this.resource,range:e,stallTimeoutMs:this.stallTimeoutMs})}}},df=class{parts;attempt;received=0;ending=new bl;constructor(e){this.parts=e}async next(){try{let e=await this.parts.resource.askingAgain(()=>this.readChunk());if(e)return{done:!1,value:e}}catch(e){if(!this.ending.hasEnded())throw this.end(),e}return this.end(),yl}return(){return this.end(),Promise.resolve(yl)}async readChunk(){let{resource:e,range:t}=this.parts;if(await e.ensureFits(t),this.ending.hasEnded()||t.length===0)return;this.attempt??=this.attemptAtTheRest();let{attempt:n}=this;try{let e=await this.withinStallTimeout(this.readFrom(n));return this.taken(e)}catch(e){throw this.drop(n),e}}attemptAtTheRest(){let{range:e}=this.parts,t=In.of(e.offset+this.received,e.length-this.received),n=new AbortController;return{request:n,body:this.bodyOf(t,n.signal)}}async bodyOf(e,t){let n=await this.parts.resource.rangeAnswer(e,t);return this.ensureAnswers(n,e),n.body?.getReader()??new ReadableStream().getReader()}ensureAnswers(e,t){let n=tf(e);if(!n)return;let r=`${t.offset}-${t.end-1}`,i=`${n.first}-${n.last}`;if(i!==r)throw new A(`source-unreadable`,`${this.parts.resource.url} answered bytes ${i} to a request for bytes ${r}`)}async readFrom(e){let t=await e.body;try{return await t.read()}catch(e){throw ie(e)?e:sf(this.parts.resource.url,this.parts.range,e)}}async withinStallTimeout(e){let t,n=new Promise((e,n)=>{t=setTimeout(()=>{n(this.stalled())},this.parts.stallTimeoutMs)});try{return await Promise.race([e,n])}finally{clearTimeout(t)}}stalled(){let{resource:e,range:t,stallTimeoutMs:n}=this.parts;return rf(new A(`source-unreadable`,`${e.url} sent nothing of the ${t.length}-byte range at ${t.offset} for ${n} ms`))}taken(e){if(e.done){this.ensureWhole();return}return this.count(e.value),e.value}count(e){let{resource:t,range:n}=this.parts;if(this.received+=e.byteLength,!(this.received<=n.length))throw new A(`source-unreadable`,`${t.url} sent more than the ${n.length}-byte range at ${n.offset}`)}ensureWhole(){let{resource:e,range:t}=this.parts;if(this.received!==t.length)throw cf(e.url,this.received,t)}drop(e){e.request.abort(),this.attempt===e&&(this.attempt=void 0)}end(){this.ending.end(),this.attempt&&this.drop(this.attempt)}},ff=class{resource;constructor(e){this.resource=e}size(){return this.resource.size()}async read(e){return await this.resource.ensureFits(e),e.length===0?/* @__PURE__ */ new Uint8Array:this.resource.askingAgain(()=>this.readOnce(e))}async readOnce(e){let t=await this.resource.rangeAnswer(e),n=await this.bodyOf(t,e);if(n.byteLength!==e.length)throw cf(this.resource.url,n.byteLength,e);return n}async bodyOf(e,t){try{return new Uint8Array(await e.arrayBuffer())}catch(e){throw ie(e)?e:sf(this.resource.url,t,e)}}},pf=`bytes=0-0`,mf=`Access-Control-Expose-Headers: Content-Range, Content-Length, Accept-Ranges, ETag`,hf=`Access-Control-Allow-Origin, ${mf}`,gf=`Access-Control-Allow-Origin naming this page's origin, not *; Access-Control-Allow-Credentials: true; ${mf}`,_f=`no-store`;async function vf(e,t,n){try{return await yf(e,t,n)}catch(t){throw ie(t)?t:await Sf(e,n,t)}}function yf(e,t,n){return(n.fetch??fetch)(e,{cache:_f,...n.requestInit,method:t.method,headers:{...Df(n.requestInit),...t.headers}})}function bf(e,t){let n=e.requestInit?.signal??void 0,r=n?xf(n,t):t;return{...e,requestInit:{...e.requestInit,signal:r}}}function xf(e,t){let n=new AbortController;for(let r of[e,t])r.aborted&&n.abort(r.reason),r.addEventListener(`abort`,()=>{n.abort(r.reason)},{once:!0,signal:n.signal});return n.signal}async function Sf(e,t,n){return await wf(e,t)?new A(`cors`,`${e} answered, but its server does not allow this page's origin to read it; add CORS headers (${Cf(t)})`,{cause:n}):new A(`source-unreadable`,`${e} could not be fetched; check the URL and the network`,{cause:n})}function Cf(e){return e.requestInit?.credentials===`include`?gf:hf}async function wf(e,t){let n=t.fetch??fetch,r=t.requestInit?.signal??null;try{return Tf(await n(e,{method:`HEAD`,mode:`no-cors`,signal:r})),!0}catch(e){if(ie(e))throw e;return!1}}function Tf(e){Ef(e)}async function Ef(e){try{await e.body?.cancel()}catch{}}function Df(e){return Object.fromEntries(new Headers(e?.headers).entries())}var Of=200,kf=/^W\//u;function Af(e){let t=e.headers.get(`etag`),n=e.headers.get(`last-modified`),r=Pf(e);return{...t!==null&&{etag:t},...n!==null&&{lastModified:n},...r!==void 0&&{size:r}}}function jf(e,t){return e.etag!==void 0&&t.etag!==void 0?Mf(e.etag)===Mf(t.etag):Nf(e.lastModified,t.lastModified)&&Nf(e.size,t.size)}function Mf(e){return e.replace(kf,``)}function Nf(e,t){return e===void 0||t===void 0||e===t}function Pf(e){let t=e.status===Of?Number(e.headers.get(`content-length`)??NaN):tf(e)?.total;return t!==void 0&&Number.isSafeInteger(t)&&t>0?t:void 0}var Ff=200,If=206,Lf=500,Rf=[250,1e3],zf=class{url;options;retryDelaysMs;sizePromise;hasReadRange=!1;version;constructor(e,t={},n){this.url=e,this.options=n?bf(t,n):t,this.retryDelaysMs=t.retryDelaysMs??Rf}size(){return this.sizePromise??=this.rememberSize(),this.sizePromise}async ensureFits(e){e.ensureWithin(await this.size(),`resource ${this.url}`)}async askingAgain(e){for(let t of this.retryDelaysMs){try{return await e()}catch(e){if(!af(e))throw e}await Bf(t,this.options.requestInit?.signal)}return e()}async rangeAnswer(e,t){let n=t?bf(this.options,t):this.options,r=await this.requestRange(e,n);if(r.status!==If)throw Tf(r),this.refusalOf(r.status);return this.hasReadRange=!0,this.ensureUnchanged(r),r}ensureUnchanged(e){let t=Af(e);if(this.version??=t,!jf(this.version,t))throw Tf(e),new A(`source-changed`,`${this.url} was replaced while it played; load it again`)}async requestRange(e,t){let n={Range:`bytes=${e.offset}-${e.end-1}`};try{return this.hasReadRange?await yf(this.url,{method:`GET`,headers:n},t):await vf(this.url,{method:`GET`,headers:n},t)}catch(e){throw this.hasReadRange?this.passingOnceAnswered(e):of(e)}}passingOnceAnswered(e){let t=`${this.url} could not be reached for a byte range`;return ie(e)?e:rf(new A(`source-unreadable`,t,{cause:e}))}refusalOf(e){if(e===Ff)return new A(`range-unsupported`,`${this.url} ignores Range requests (answered 200 to a byte range)`);let t=`${this.url} answered ${e} to a byte range`;return e>=Lf?rf(new A(`source-unreadable`,t)):new A(`source-unreadable`,t)}async rememberSize(){try{return await this.fetchSize()}catch(e){throw this.sizePromise=void 0,e}}async fetchSize(){let e=await this.request(`HEAD`);if(Tf(e),!e.ok)return this.sizeFromContentRange();this.ensureUnchanged(e);let t=Number(e.headers.get(`content-length`));return Number.isSafeInteger(t)&&t>0?t:this.sizeFromContentRange()}async sizeFromContentRange(){let e=await this.request(`GET`,{Range:pf});if(Tf(e),e.status!==If)throw new A(`source-unreadable`,`${this.url} answered ${e.status} to a byte range; cannot determine the file size`);return this.hasReadRange=!0,this.ensureUnchanged(e),this.totalOf(e)}totalOf(e){if(!e.headers.has(`content-range`)&&e.type===`cors`)throw this.hiddenContentRange();let t=tf(e)?.total;if(t===void 0)throw new A(`source-unreadable`,`${this.url} reports neither Content-Length nor Content-Range; cannot determine the file size`);return t}hiddenContentRange(){return new A(`cors`,`${this.url} answered a byte range but hides its Content-Range from this origin; add ${mf}`)}request(e,t){return vf(this.url,{method:e,...t&&{headers:t}},this.options)}};function Bf(e,t){return new Promise((n,r)=>{t?.throwIfAborted();let i=new AbortController,a=setTimeout(()=>{i.abort(),n()},e);t?.addEventListener(`abort`,()=>{clearTimeout(a),r(Vf(t))},{once:!0,signal:i.signal})})}function Vf(e){let t=e?.reason;return t instanceof Error?t:new DOMException(`the read was aborted`,`AbortError`)}var Hf=/* @__PURE__ */ new Set([405,403]),Uf=class{options;constructor(e={}){this.options=e}async exists(e){try{let t=await yf(e,{method:`HEAD`},this.options);if(Tf(t),!Hf.has(t.status))return t.ok;let n=await yf(e,{method:`GET`,headers:{Range:pf}},this.options);return Tf(n),n.ok}catch{return!1}}};function I(e){if(!e)throw Error(`Assertion failed.`)}var Wf=Math.PI/180,Gf=180/Math.PI,Kf=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},qf=[1,0,0,0,1,0,0,0,1],Jf=(e,t,n)=>{let[r,i,,a,o]=e,s=Math.abs(r)*t+Math.abs(a)*n,c=Math.abs(i)*t+Math.abs(o)*n;return ep(ep(Qf(-t/2,-n/2),e),Qf(s/2,c/2))},Yf=e=>{let[t,n]=e;return Kf(Rp(Math.atan2(n,Xf(e)?-t:t)*Gf,90))},Xf=e=>{let[t,n,,r,i]=e;return t*i-n*r<0},Zf=e=>{let t=e*Wf,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},Qf=(e,t)=>[1,0,0,0,1,0,e,t,1],$f=(e,t)=>[e,0,0,0,t,0,0,0,1],ep=(e,t)=>{let n=Array(9);for(let r=0;r<3;r++)for(let i=0;i<3;i++)n[3*r+i]=e[3*r]*t[i]+e[3*r+1]*t[3+i]+e[3*r+2]*t[6+i];return n},tp=e=>e&&e[e.length-1],np=e=>e>=0&&e<2**32,rp=e=>e>=-(2**31)&&e<2**31,L=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},ip=e=>{let t=L(e);return t&1?t+1>>1:-(t>>1)},ap=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),op=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),sp=globalThis.TextEncoder===void 0?class{constructor(){this.encoding=`utf-8`}encode(e=``){let t=new Uint8Array(3*e.length),n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i<128)t[n++]=i;else if(i<2048)t[n++]=192|i>>6,t[n++]=128|i&63;else if(i<55296||i>57343)t[n++]=224|i>>12,t[n++]=128|i>>6&63,t[n++]=128|i&63;else{let a=r+1<e.length?e.charCodeAt(r+1):0;i<56320&&a>=56320&&a<=57343?(i=65536+(i-55296<<10)+(a-56320),r++,t[n++]=240|i>>18,t[n++]=128|i>>12&63,t[n++]=128|i>>6&63,t[n++]=128|i&63):(t[n++]=239,t[n++]=191,t[n++]=189)}}return t.slice(0,n)}}:globalThis.TextEncoder,cp=globalThis.TextDecoder===void 0?class{constructor(e=`utf-8`){let t=e.trim().toLowerCase();if(t===`utf-8`||t===`utf8`||t===`unicode-1-1-utf-8`)this.encoding=`utf-8`;else if(t===`utf-16le`||t===`utf-16`)this.encoding=`utf-16le`;else if(t===`utf-16be`)this.encoding=`utf-16be`;else throw RangeError(`The encoding label provided ('${e}') is invalid.`)}decode(e){let t=e?ap(e):/* @__PURE__ */ new Uint8Array,n=[];if(this.encoding===`utf-8`){let e=t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?3:0;for(;e<t.length;){let r=t[e];if(r<128){n.push(r),e++;continue}let i,a;if(r>=194&&r<224)i=1,a=r&31;else if(r>=224&&r<240)i=2,a=r&15;else if(r>=240&&r<245)i=3,a=r&7;else{n.push(65533),e++;continue}let o=r===224?160:r===240?144:128,s=r===237?159:r===244?143:191,c=1;for(;c<=i;c++){let n=e+c<t.length?t[e+c]:0;if(n<o||n>s)break;a=a<<6|n&63,o=128,s=191}e+=c,c<=i?n.push(65533):a>=65536?(a-=65536,n.push(55296|a>>10,56320|a&1023)):n.push(a)}}else{let e=this.encoding===`utf-16le`,r=e?255:254,i=e?254:255,a=t.length>=2&&t[0]===r&&t[1]===i?2:0;for(;a+1<t.length;){let r=e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1];if(a+=2,r>=55296&&r<=56319){let i=a+1<t.length?e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1]:-1;i>=56320&&i<=57343?(n.push(r,i),a+=2):n.push(65533)}else r>=56320&&r<=57343?n.push(65533):n.push(r)}a<t.length&&n.push(65533)}let r=``;for(let e=0;e<n.length;e+=8192)r+=String.fromCharCode(...n.slice(e,e+8192));return r}}:globalThis.TextDecoder,lp=/* #__PURE__ */ new cp,up=/* #__PURE__ */ new sp,dp=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),fp={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},pp=/* #__PURE__ */ dp(fp),mp={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},hp=/* #__PURE__ */ dp(mp),gp={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},_p=/* #__PURE__ */ dp(gp),vp=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,yp=e=>!e||e.primaries==null&&e.transfer==null&&e.matrix==null&&e.fullRange==null,bp={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},xp=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),Sp=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},Cp=/^[0-9a-fA-F]+$/,wp=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),Tp=e=>{I(e.length%2==0);let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.slice(n,n+2),16);return t},Ep=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),Dp=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},Op=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},kp=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Ap=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},jp=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},Mp=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},Np=e=>{throw Error(`Unexpected value: ${e}`)},Pp=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},Fp=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},Ip=(e,t,n)=>Math.max(t,Math.min(n,e)),Lp=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},Rp=(e,t)=>Math.round(e/t)*t,zp=(e,t)=>Math.round(e*t)/t,Bp=(e,t)=>Math.floor(e/t)*t,Vp=e=>{let t=0;for(;e;)t++,e>>=1;return t},Hp=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Up=/^[a-z]{3}$/,Wp=e=>Up.test(e),Gp=1e6*(1+2**-52),Kp=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{num:n*a,den:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{num:n*a,den:o}},qp=null,Jp=()=>qp===null?qp=!(typeof navigator>`u`||!navigator.vendor?.includes(`Google Inc`)&&!/Chrome/.test(navigator.userAgent)):qp,Yp=(/* #__PURE__ */ (async()=>{})()).constructor,R=e=>e instanceof Yp||e instanceof Promise||typeof e?.then==`function`,Xp=(e,t)=>e===-1?t:e,Zp=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Qp=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},$p=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},em=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},tm=e=>typeof e==`number`&&!Number.isNaN(e),nm=(e,t)=>{if(t.includes(`://`))return t;if(e.includes(`://`)){let t=e.indexOf(`?`);t!==-1&&(e=e.slice(0,t))}let n;if(t.startsWith(`/`)){let r=e.indexOf(`://`);if(r===-1)n=t;else{let i=e.indexOf(`/`,r+3);n=i===-1?e+t:e.slice(0,i)+t}}else{let r=e.lastIndexOf(`/`);n=r===-1?t:e.slice(0,r+1)+t}let r=``,i=n.indexOf(`://`);if(i!==-1){let e=n.indexOf(`/`,i+3);e!==-1&&(r=n.slice(0,e),n=n.slice(e))}let a=n.split(`/`),o=[];for(let e of a)e===`..`?o.pop():e!==`.`&&o.push(e);return r+o.join(`/`)},rm=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},im=(e,t)=>{let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);a<r&&(r=a,n=i)}return n},am=e=>{I(Number.isInteger(e.num)),I(Number.isInteger(e.den)),I(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},om=e=>new Promise(t=>setTimeout(t,e)),sm=e=>Array.isArray(e)?e:[e],cm=class{constructor(){this._listeners=/* @__PURE__ */ new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,/* @__PURE__ */ new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},lm=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),um;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(um||={});var dm=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==um.Silent&&t!==um.Errors&&t!==um.Warnings&&t!==um.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new cm}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=um.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=um.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=um.Info&&console.info(...t)}};dm._level=um.Info,dm._emitterInstance=null;var fm=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},pm=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},mm=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(Array.isArray(t)&&t.every(e=>typeof e==`string`))&&!(t instanceof Uint8Array)&&!(t instanceof fm)&&!(t instanceof pm)&&!lm(t))throw TypeError(`Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},hm={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},gm=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.primary!==void 0&&typeof e.primary!=`boolean`)throw TypeError(`disposition.primary must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},_m=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}copyBits(e,t){let n=0;for(;n<e-7;n+=8)this.writeBits(8,t.readBits(8));let r=e-n;r>0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},vm=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ym=[-1,1,2,3,4,5,6,8],bm=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new _m(e),n=xm(t),{frequencyIndex:r,sampleRate:i}=Sm(t),a=t.readBits(4),o=null;a>=1&&a<=7&&(o=ym[a]);let s=n,c=!1,l=i;if(n===5||n===29)c=n===29,l=Sm(t).sampleRate,s=xm(t),s===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let e=t.pos;if(t.readBits(11)!==695){t.pos=e+1;continue}xm(t)===5&&t.readBits(1)&&(l=Sm(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return o!==null&&o>1&&(c=!1),{objectType:n,coreObjectType:s,frequencyIndex:r,channelConfiguration:a,outputSampleRate:l,outputNumberOfChannels:c&&o===1?2:o}},xm=e=>{let t=e.readBits(5);return t===31?32+e.readBits(6):t},Sm=e=>{let t=e.readBits(4);return t===15?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<vm.length?vm[t]:null}},Cm=e=>{let t=e.objectType===5||e.objectType===29,n=e.objectType===29,r=t?e.outputSampleRate/2:e.outputSampleRate,i=n?1:e.outputNumberOfChannels,a=ym.indexOf(i);if(a===-1)throw TypeError(`Unsupported number of channels: ${e.outputNumberOfChannels}`);let o=16;e.objectType>=32&&(o+=6),Em(r)===15&&(o+=24),t&&(o+=9,Em(e.outputSampleRate)===15&&(o+=24));let s=Math.ceil(o/8),c=new Uint8Array(s),l=new _m(c);return wm(l,e.objectType),Tm(l,r),l.writeBits(4,a),t&&(Tm(l,e.outputSampleRate),wm(l,2)),l.writeBits(3,0),c},wm=(e,t)=>{t<32?e.writeBits(5,t):(e.writeBits(5,31),e.writeBits(6,t-32))},Tm=(e,t)=>{let n=Em(t);e.writeBits(4,n),n===15&&e.writeBits(24,t)},Em=e=>{let t=vm.indexOf(e);return t===-1?15:t},Dm=[48e3,44100,32e3],Om=[24e3,22050,16e3],km;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(km||={});var Am;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(Am||={});var jm=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},Mm=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;t===1?e=r.getUint8(n):t===2?e=r.getUint16(n,!1):t===3?e=Pp(r,n,!1):(I(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},Nm=(e,t)=>t.description?Mm(e,(ap(t.description)[4]&3)+1):jm(e),Pm=e=>e&31,Fm=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)};new Uint8Array([0,0,0,1]);var Im=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:Fp(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},Lm=e=>{try{let t=[],n=[],r=[];for(let i of jm(e)){let a=e.subarray(i.offset,i.offset+i.length),o=Pm(a[0]);o===km.SPS?t.push(a):o===km.PPS?n.push(a):o===km.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=Vm(i);I(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return dm._error(`Error building AVC Decoder Configuration Record:`,e),null}},Rm=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if((e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144)&&e.chromaFormat!==null){I(e.bitDepthLumaMinus8!==null),I(e.bitDepthChromaMinus8!==null),I(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},zm=e=>{try{let t=op(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return dm._error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},Bm={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Vm=e=>{try{let t=Fm(e),n=new _m(t);if(n.skipBits(1),n.skipBits(2),n.readBits(5)!==7)return null;let r=n.readAlignedByte(),i=n.readAlignedByte(),a=n.readAlignedByte();L(n);let o=1,s=0,c=0,l=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(o=L(n),o===3&&(l=n.readBits(1)),s=L(n),c=L(n),n.skipBits(1),n.readBits(1))){for(let e=0;e<(o===3?12:8);e++)if(n.readBits(1)){let t=e<6?16:64,r=8,i=8;for(let e=0;e<t;e++){if(i!==0){let e=ip(n);i=(r+e+256)%256}r=i===0?r:i}}}L(n);let u=L(n);if(u===0)L(n);else if(u===1){n.skipBits(1),ip(n),ip(n);let e=L(n);for(let t=0;t<e;t++)ip(n)}L(n),n.skipBits(1);let d=L(n),f=L(n),p=16*(d+1),m=16*(f+1),h=p,g=m,_=n.readBits(1);if(_||n.skipBits(1),n.skipBits(1),n.readBits(1)){let e=L(n),t=L(n),r=L(n),i=L(n),a,s;if((l===0?o:0)===0)a=1,s=2-_;else{let e=o===3?1:2,t=o===1?2:1;a=e,s=t*(2-_)}h-=a*(e+t),g-=s*(r+i)}let v=2,y=2,b=2,x=0,S={num:1,den:1},C=null,w=null,T=null,E=null,D=n.pos;if(n.readBits(1)){if(n.readBits(1)){let e=n.readBits(8);if(e===255)S={num:n.readBits(16),den:n.readBits(16)};else{let t=Bm[e];t&&(S=t)}}n.readBits(1)&&n.skipBits(1),n.readBits(1)&&(n.skipBits(3),x=n.readBits(1),n.readBits(1)&&(v=n.readBits(8),y=n.readBits(8),b=n.readBits(8))),n.readBits(1)&&(L(n),L(n)),n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.skipBits(1));let e=n.readBits(1);e&&Hm(n);let t=n.readBits(1);t&&Hm(n),(e||t)&&n.skipBits(1),n.skipBits(1),T=n.pos,E=n.readBits(1),E&&(n.skipBits(1),L(n),L(n),L(n),L(n),C=L(n),w=L(n))}if(C===null){I(w===null);let e=i&16;if((r===44||r===86||r===100||r===110||r===122||r===244)&&e)C=0,w=0;else{let e=d+1,t=f+1,n=(2-_)*t,r=Xh.find(e=>e.level>=a)??tp(Xh),i=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);C=i,w=i}}return I(w!==null),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:_,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:c,codedWidth:p,codedHeight:m,displayWidth:h,displayHeight:g,pixelAspectRatio:S,colourPrimaries:v,matrixCoefficients:b,transferCharacteristics:y,fullRangeFlag:x,numReorderFrames:C,maxDecFrameBuffering:w,vuiParametersFlagBitOffset:D,bitstreamRestrictionFlagBitOffset:T,bitstreamRestrictionFlag:E}}catch(e){return dm._error(`Error parsing AVC SPS:`,e),null}},Hm=e=>{let t=L(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)L(e),L(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Um=(e,t)=>t.description?Mm(e,(ap(t.description)[21]&3)+1):jm(e),Wm=e=>e>>1&63,Gm=e=>{try{let t=new _m(Fm(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=qm(t,n);L(t);let u=L(t),d=0;u===3&&(d=t.readBits(1));let f=L(t),p=L(t),m=f,h=p;if(t.readBits(1)){let e=L(t),n=L(t),r=L(t),i=L(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=L(t),_=L(t);L(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)L(t),y=L(t),L(t);if(L(t),L(t),L(t),L(t),L(t),L(t),t.readBits(1)&&t.readBits(1)&&Jm(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),L(t),L(t),t.skipBits(1)),Ym(t,L(t)),t.readBits(1)){let e=L(t);for(let n=0;n<e;n++)L(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,w=0,T={num:1,den:1};if(t.readBits(1)){let e=Zm(t,n);T=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,w=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:T,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:w}}catch(e){return dm._error(`Error parsing HEVC SPS:`,e),null}},Km=e=>{try{let t=[],n=[],r=[],i=[];for(let a of jm(e)){let o=e.subarray(a.offset,a.offset+a.length),s=Wm(o[0]);s===Am.VPS_NUT?t.push(o):s===Am.SPS_NUT?n.push(o):s===Am.PPS_NUT?r.push(o):(s===Am.PREFIX_SEI_NUT||s===Am.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Gm(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new _m(Fm(e));t.skipBits(16),L(t),L(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),L(t),L(t),ip(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&L(t),ip(t),ip(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:Am.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Am.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Am.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Wm(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return dm._error(`Error building HEVC Decoder Configuration Record:`,e),null}},qm=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=/* @__PURE__ */ new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},Jm=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))L(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&ip(e);for(let t=0;t<n;t++)ip(e)}},Ym=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Xm(e,r,t,n)},Xm=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(L(e)+1):t-1,e.readBits(1),L(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=L(e),n=L(e);for(let n=0;n<t;n++)L(e),e.readBits(1);for(let t=0;t<n;t++)L(e),e.readBits(1);i=t+n}return i},Zm=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=Bm[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(L(e),L(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(L(e),L(e),L(e),L(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&L(e),e.readBits(1)&&Qm(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=L(e),L(e),L(e),L(e),L(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},Qm=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?L(e):o=e.readBits(1)===1;let s=1;o||(s=L(e)+1),r&&$m(e,s,a),i&&$m(e,s,a)}},$m=(e,t,n)=>{for(let r=0;r<t;r++)L(e),L(e),n&&(L(e),L(e)),e.readBits(1)},eh=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},th=e=>{try{let t=op(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=i>>6&3,o=i>>5&1,s=i&31,c=t.getUint32(n,!1);n+=4;let l=e.subarray(n,n+6);n+=6;let u=t.getUint8(n++),d=(t.getUint8(n++)&15)<<8|t.getUint8(n++),f=t.getUint8(n++)&3,p=t.getUint8(n++)&3,m=t.getUint8(n++)&7,h=t.getUint8(n++)&7,g=t.getUint16(n,!1);n+=2;let _=t.getUint8(n++),v=_>>6&3,y=_>>3&7,b=_>>2&1,x=_&3,S=t.getUint8(n++),C=[];for(let r=0;r<S;r++){let r=t.getUint8(n++),i=r>>7&1,a=r&63,o=t.getUint16(n,!1);n+=2;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}C.push({arrayCompleteness:i,nalUnitType:a,nalUnits:s})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:p,bitDepthLumaMinus8:m,bitDepthChromaMinus8:h,avgFrameRate:g,constantFrameRate:v,numTemporalLayers:y,temporalIdNested:b,lengthSizeMinusOne:x,arrays:C}}catch(e){return dm._error(`Error deserializing HEVC Decoder Configuration Record:`,e),null}},nh;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(nh||={});var rh={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},ih=e=>{let t=new _m(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7){if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1}else o=3,s=1;let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=tp(Zh).level;for(let e of Zh)if(u<=e.maxPictureSize){d=e.level;break}let f=rh[a],p=f?.colourPrimaries??2,m=f?.transferCharacteristics??2,h=f?.matrixCoefficients??2;return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:p,transferCharacteristics:m,matrixCoefficients:h}},ah=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,oh=function*(e){let t=new _m(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e+=(r&127)*2**(n*7),!(r&128))break;if(n===7&&r&128)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),i=t.readBits(1),a=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let o;if(a){let e=n();if(e===null)return;o=e}else o=Math.floor(t.getBitsLeft()/8);I(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(o*8)}},sh=e=>{for(let{type:t,data:n}of oh(e)){if(t!==1)continue;let e=new _m(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{let t=e.readBits(1),n=0;if(t){if(e.skipBits(32),e.skipBits(32),e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}n=e.readBits(1),n&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}let r=e.readBits(1),i=e.readBits(5);for(let t=0;t<=i;t++){e.skipBits(12);let i=e.readBits(5);if(t===0&&(a=i),i>7){let n=e.readBits(1);t===0&&(o=n)}if(n&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}r&&e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=2,_=2,v=2;e.readBits(1)&&(g=e.readBits(8),_=e.readBits(8),v=e.readBits(8));let y=0,b=1,x=1,S=0;return h?y=e.readBits(1):g===1&&_===13&&v===0?(y=1,b=0,x=0):(y=e.readBits(1),r===0?(b=1,x=1):r===1?(b=0,x=0):m===12?(b=e.readBits(1),x=b?e.readBits(1):0):(b=1,x=0),b&&x&&(S=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:b,chromaSubsamplingY:x,chromaSamplePosition:S,videoFullRangeFlag:y,colourPrimaries:g,transferCharacteristics:_,matrixCoefficients:v}}return null},ch=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,lh=e=>{if(e.length<36)return null;let t=op(e);return t.getUint32(4)!==1768124518||t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},uh=e=>{let t=op(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},dh=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],fh=e=>{let t=e[0]>>3,n=e[0]&3,r;return r=n===0?1:n===1||n===2?2:e[1]&63,{durationInSamples:dh[t]*r}},ph=e=>{if(e.length<7)throw Error(`Setup header is too short.`);if(e[0]!==5)throw Error(`Wrong packet type in Setup header.`);if(String.fromCharCode(...e.slice(1,7))!==`vorbis`)throw Error(`Invalid packet signature in Setup header.`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e[t-1-r];let r=new _m(n),i=0;for(;r.getBitsLeft()>97;)if(r.readBits(1)===1){i=r.pos;break}if(i===0)throw Error(`Invalid Setup header: framing bit not found.`);let a=0,o=!1,s=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),n=r.readBits(16),i=r.readBits(16);if(t>63||n!==0||i!==0){r.pos=e;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,s=a)}if(!o)throw Error(`Invalid Setup header: mode header not found.`);if(s>63)throw Error(`Unsupported mode count: ${s}.`);let c=s;r.pos=0,r.skipBits(i);let l=Array(c).fill(0);for(let e=c-1;e>=0;e--)r.skipBits(40),l[e]=r.readBits(1);return{modeBlockflags:l}},mh=(e,t,n)=>{switch(e){case`avc`:for(let e of Nm(n,t)){let t=n[e.offset],r=Pm(t);if(r>=km.NON_IDR_SLICE&&r<=km.SLICE_DPC)return`delta`;if(r===km.IDR)return`key`;if(r===km.SEI&&!Jp()){let t=Fm(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(n===void 0||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(e===void 0||(n+=e,e<255))break}if(e===6){let e=new _m(t);e.pos=8*r;let n=L(e),i=e.readBits(1);if(n===0&&i===1)return`key`}r+=n}while(r<t.length-1)}}return`delta`;case`hevc`:for(let e of Um(n,t)){let t=Wm(n[e.offset]);if(t<Am.BLA_W_LP)return`delta`;if(t<=Am.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new _m(n);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:r}of oh(n))if(t===1){let t=new _m(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new _m(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}case`prores`:return`key`;default:Np(e),I(!1)}},hh;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(hh||={});var gh=(e,t)=>{let n=op(e),r=0,i=n.getUint32(r,!0);r+=4;let a=lp.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=lp.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf(`=`);if(o===-1)continue;let s=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(t.raw??={},Array.isArray(t.raw[s])?t.raw[s]=[...t.raw[s],c]:typeof t.raw[s]==`string`?t.raw[s]=[t.raw[s],c]:t.raw[s]??=c,s){case`TITLE`:t.title??=c;break;case`DESCRIPTION`:t.description??=c;break;case`ARTIST`:t.artist??=c;break;case`ALBUM`:t.album??=c;break;case`ALBUMARTIST`:t.albumArtist??=c;break;case`COMMENT`:t.comment??=c;break;case`LYRICS`:t.lyrics??=c;break;case`TRACKNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case`TRACKTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case`DISCNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case`DISCTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case`DATE`:{let e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case`GENRE`:t.genre??=c;break;case`METADATA_BLOCK_PICTURE`:{let e=Qp(c),n=op(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=lp.decode(e.subarray(12+i,12+i+o)),l=n.getUint32(i+o+28),u=e.subarray(i+o+32,i+o+32+l);t.images??=[],t.images.push({data:u,mimeType:a,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,name:void 0,description:s||void 0})}}}},_h=[2,1,2,3,3,4,4,5],vh=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new _m(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},yh=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],bh=1536;new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var xh=[1,2,3,6],Sh=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new _m(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=xh[o],d;return d=i<3?Dm[i]/1e3:Om[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},Ch=e=>{if(e.length<2)return null;let t=new _m(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},wh=e=>{let t=e.substreams[0];return I(t),t.fscod<3?Dm[t.fscod]:t.fscod2!==null&&t.fscod2<3?Om[t.fscod2]:null},Th=e=>{let t=e.substreams[0];I(t);let n=_h[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n},Eh=4096,Dh=8,Oh=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],kh=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Ah=[16,16,20,20,0,24,24,0],jh=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Mh=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Nh=8,Ph=44646,Fh=[32e3,44100,48e3,0],Ih=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Lh=[512,1024,2048,4096],Rh=e=>{let t=Bh(e),n=op(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=Vh(e.subarray(r));if(!t)break;i??=t,r+=t.frameSize}if(t)return{frameSize:i?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:i!==null};if(!i?.asset)return null;let{asset:a}=i;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},zh=e=>{let t=Rh(e);return t?.core?t.hasExtensions?`dtsh`:`dtsc`:null},Bh=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new _m(e);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==31)return null;let n=t.readBits(1),r=t.readBits(7)+1;if(r%Dh!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=jh.length)return null;let o=Oh[t.readBits(4)];if(o===0)return null;let s=kh[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),n&&t.skipBits(16),t.skipBits(7);let l=Ah[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:jh[a]+ +!!u,sampleCount:r*32,channelLayout:Mh[a]|(u?Nh:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},Vh=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new _m(e);t.skipBits(32),t.skipBits(8);let n=t.readBits(2),r=t.readBits(1),i=8+4*r,a=16+4*r;t.skipBits(i);let o=t.readBits(a)+1,s={frameSize:o,asset:null};if(!t.readBits(1))return s;let c=Fh[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,f=[];for(let e=0;e<u;e++)f.push(t.readBits(n+1));for(let e of f)t.skipBits(8*Hp(e));if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,n=t.readBits(2)+1;t.skipBits(n*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let p=t.readBits(5)+1,m=Ih[t.readBits(4)],h=t.readBits(8)+1,g=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;g=t.readBits(e)}return c===0||t.getBitsLeft()<0?s:{frameSize:o,asset:{sampleRate:m,numberOfChannels:h,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:p}}},Hh=e=>{if(e.length<20)return null;let t=op(e),n=t.getUint32(0);if(n===0)return null;let r=new _m(e);r.seekToByte(13);let i=r.readBits(2);r.skipBits(5);let a=r.readBits(1),o=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);let s=r.readBits(16),c=null;return s===0?o<jh.length&&(c=jh[o]+a):c=Wh(s),{sampleRate:n,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:Lh[i],channelLayout:s,numberOfChannels:c}},Uh=e=>{let t=/* @__PURE__ */ new Uint8Array(20),n=op(t);n.setUint32(0,e.sampleRate),n.setUint32(4,e.bitRate),n.setUint32(8,e.bitRate),t[12]=e.pcmResolution;let r=e.core&&!e.hasExtensions?1:0,i=new _m(t);return i.seekToByte(13),i.writeBits(2,Math.max(Lh.indexOf(e.sampleCount),0)),i.writeBits(5,r),i.writeBits(1,+!!e.core?.lfePresent),i.writeBits(6,e.core?.amode??0),i.writeBits(14,e.core?e.core.frameSize-1:0),i.writeBits(1,0),i.writeBits(3,0),i.writeBits(16,e.channelLayout),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(5,0),t},Wh=e=>Hp(e)+Hp(e&Ph),Gh=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Kh=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],qh=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],Jh=[...qh,...Kh],Yh=[`webvtt`],Xh=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Zh=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Qh=`.01.01.01.01.00`,$h=`.0.110.01.01.01.0`,eg=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],tg=[`dtsc`,`dtsh`,`dtsl`,`dtse`],ng=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=+(r.slice(-1)===`H`),s=Number(t[3]),c=s===8?0:1,l=+(s===12),u=t[4]?Number(t[4]):0,d=t[5]?Number(t[5][0]):1,f=t[5]?Number(t[5][1]):1,p=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(c<<6)+(l<<5)+(u<<4)+(d<<3)+(f<<2)+p,0]},rg=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s,proresFormat:c}=e;if(t===`avc`){if(I(e.avcType!==null),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${wp(t)}`}if(!n||n.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${wp(n.subarray(1,4))}`}if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=Ep(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let a=op(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=Ep(a.getUint32(2)),i=c>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=r.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=o;s.length>0&&s[s.length-1]===0;)s.pop();return s.length>0&&(c+=`.`,c+=s.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}if(t===`vp8`)return`vp8`;if(t===`vp9`){if(!o){let t=e.width*e.height,n=tp(Zh).level;for(let e of Zh)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=o.profile.toString().padStart(2,`0`),n=o.level.toString().padStart(2,`0`),r=o.bitDepth.toString().padStart(2,`0`),i=o.chromaSubsampling.toString().padStart(2,`0`),a=o.colourPrimaries.toString().padStart(2,`0`),s=o.transferCharacteristics.toString().padStart(2,`0`),c=o.matrixCoefficients.toString().padStart(2,`0`),l=o.videoFullRangeFlag.toString().padStart(2,`0`),u=`vp09.${t}.${n}.${r}.${i}`;return u+=`.${a}.${s}.${c}.${l}`,u.endsWith(Qh)&&(u=u.slice(0,-15)),u}if(t===`av1`){if(!s){let t=e.width*e.height,n=tp(Zh).level;for(let e of Zh)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=s.profile,n=s.level.toString().padStart(2,`0`),i=s.tier?`H`:`M`,a=s.bitDepth.toString().padStart(2,`0`),o=s.monochrome?`1`:`0`,c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),l=r?.primaries?fp[r.primaries]:1,u=r?.transfer?mp[r.transfer]:1,d=r?.matrix?gp[r.matrix]:1,f=+!!r?.fullRange,p=`av01.${t}.${n}${i}.${a}`;return p+=`.${o}.${c.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith($h)&&(p=p.slice(0,-17)),p}if(t===`prores`)return c??`apch`;throw t!==null&&Np(t),TypeError(`Unhandled codec '${t}'.`)},ig=e=>{switch(e.codec){case`avc`:{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=zm(e.codecDescription)?.sequenceParameterSets[0]),t){let e=Vm(t);if(e)return{primaries:pp[e.colourPrimaries],transfer:hp[e.transferCharacteristics],matrix:_p[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`hevc`:{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Am.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=th(e.codecDescription)?.arrays.find(e=>e.nalUnitType===Am.SPS_NUT)?.nalUnits[0]),t){let e=Gm(t);if(e)return{primaries:pp[e.colourPrimaries],transfer:hp[e.transferCharacteristics],matrix:_p[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`vp8`:break;case`vp9`:if(e.vp9CodecInfo)return{primaries:pp[e.vp9CodecInfo.colourPrimaries],transfer:hp[e.vp9CodecInfo.transferCharacteristics],matrix:_p[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case`av1`:if(e.av1CodecInfo)return{primaries:pp[e.av1CodecInfo.colourPrimaries],transfer:hp[e.av1CodecInfo.transferCharacteristics],matrix:_p[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case`prores`:if(e.proresCodecInfo)return{primaries:pp[e.proresCodecInfo.colourPrimaries],transfer:hp[e.proresCodecInfo.transferCharacteristics],matrix:_p[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},ag=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r,dtsFormat:i}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?bm(n).objectType:r.objectType,`mp4a.40.${e}`}}if(t===`mp3`)return`mp3`;if(t===`opus`)return`opus`;if(t===`vorbis`)return`vorbis`;if(t===`flac`)return`flac`;if(t===`ac3`)return`ac-3`;if(t===`eac3`)return`ec-3`;if(t===`dts`)return i??`dtsc`;if(t&&Kh.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},og=48e3,sg=/^pcm-([usf])(\d+)(be)?$/,cg=e=>{if(I(Kh.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=sg.exec(e);I(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?128:0}},lg=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:eg.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:tg.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:sg.test(e)?e:e===`webvtt`?`webvtt`:null,ug=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...eg],dg=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,fg=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,pg=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,mg=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,hg=(e,t)=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!ug.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectWidth!==void 0!=(e.decoderConfig.displayAspectHeight!==void 0))throw TypeError(`Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.`);if(e.decoderConfig.description!==void 0&&!xp(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(fp);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(mp);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(gp);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!dg.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!fg.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!pg.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)){if(!mg.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)}else if(eg.some(t=>e.decoderConfig.codec.startsWith(t))&&!eg.some(t=>e.decoderConfig.codec===t))throw TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${eg.join(`, `)}.`);if(t!==null&&lg(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},gg=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],_g=(e,t)=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!gg.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!xp(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if(e.decoderConfig.codec.startsWith(`dts`)){if(!tg.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${tg.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!Kh.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Kh.join(`, `)}).`);if(t!==null&&lg(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},vg=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},yg=[44100,48e3,32e3],bg=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],xg=(e,t,n,r,i)=>t===0?0:t===1?Math.floor(144*n/(r<<e))+i:t===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,Sg=(e,t,n,r)=>t===0?0:t===1?144*n/(r<<e):t===2?144*n/r:12*n/r*4,Cg=(e,t)=>e===3?t===3?21:36:t===3?13:21,wg=(e,t)=>{let n=e>>>24,r=e>>>16&255,i=e>>>8&255,a=e&255;if(n!==255&&r!==255&&i!==255&&a!==255)return{header:null,bytesAdvanced:4};if(n!==255||(r&224)!=224)return{header:null,bytesAdvanced:1};let o=0,s=0;r&16?o=r&8?0:1:(o=1,s=1);let c=r>>3&3,l=r>>1&3,u=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,p=a>>6&3,m=a>>4&3,h=a>>3&1,g=a>>2&1,_=a&3,v=bg[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=yg[d]>>o+s,x=xg(o,l,y,b,f);if(t!==null&&t<x)return{header:null,bytesAdvanced:1};let S;return S=c===3?l===3?384:1152:l===3?384:l===2?1152:576,{header:{totalSize:x,mpegVersionId:c,lowSamplingFrequency:o,layer:l,bitrate:y,frequencyIndex:d,sampleRate:b,channel:p,modeExtension:m,copyright:h,original:g,emphasis:_,audioSamplesInFrame:S},bytesAdvanced:1}},Tg=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n},Eg;(function(e){e[e.FrameCount=1]=`FrameCount`,e[e.FileSize=2]=`FileSize`,e[e.Toc=4]=`Toc`})(Eg||={});var Dg=e=>e===3?1:2,Og=class{constructor(e){this.input=e}dispose(){}},kg=/* #__PURE__ */ new Uint8Array,Ag=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===kg&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===kg}get microsecondTimestamp(){return Math.trunc(Gp*this.timestamp)}get microsecondDuration(){return Math.trunc(Gp*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`EncodedAudioChunk is not available in this environment.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},jg=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},Mg=e=>{let t=op(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=wp(e.subarray(n,n+16));n+=16;let a=null;if(r>0){let r=t.getUint32(n);if(n+=4,r>0){a=[];for(let t=0;t<r;t++)a.push(wp(e.subarray(n,n+16))),n+=16}}let o=t.getUint32(n);return n+=4,{systemId:i,keyIds:a,data:e.slice(n,n+o)}},Ng=(e,t)=>e.systemId===t.systemId&&$p(e.data,t.data),Pg=e=>{let t=U(e),n=xb(e,4),r=8;t===1&&(t=gb(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},Fg=e=>pb(e)/65536,Ig=e=>pb(e)/1073741824,Lg=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=H(e);if(t|=n&127,!(n&128))break}return t},Rg=e=>{let t=cb(e);return e.skip(2),t=Math.min(t,e.remainingLength),lp.decode(V(e,t))},zg=e=>{let t=Pg(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=U(e);e.skip(4);let r=V(e,t.contentSize-8);switch(n){case 1:return lp.decode(r);case 2:return new cp(`utf-16be`).decode(r);case 13:return new fm(r,`image/jpeg`);case 14:return new fm(r,`image/png`);case 27:return new fm(r,`image/bmp`);default:return r}},Bg=/* @__PURE__ */ new Uint32Array(256),Vg=/* @__PURE__ */ new Uint32Array(256),Hg=/* @__PURE__ */ new Uint32Array(256),Ug=/* @__PURE__ */ new Uint32Array(256),Wg=/* @__PURE__ */ new Uint32Array(256),Gg=/* @__PURE__ */ new Uint32Array(256),Kg=/* @__PURE__ */ new Uint32Array(10),qg=!1,Jg=()=>{let e=/* @__PURE__ */ new Uint8Array(256),t=/* @__PURE__ */ new Uint8Array(256),n=/* @__PURE__ */ new Uint8Array(256);for(let e=0,r=1;e<256;e++)n[e]=r,t[r]=e,r=r^r<<1^(r&128?283:0);let r=(e,r)=>e&&r?n[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let i=n[255-t[r]],a=i^i<<1^i<<2^i<<3^i<<4;a=a>>>8^a&255^99,e[r]=a}for(let t=0;t<256;t++){let n=e[t],i=e.indexOf(t);Bg[t]=n<<24|n<<16|n<<8|n,Gg[t]=i<<24|i<<16|i<<8|i;let a=r(i,14),o=r(i,9),s=r(i,13),c=r(i,11),l=a<<24|o<<16|s<<8|c;Vg[t]=l,Hg[t]=l>>>8|l<<24,Ug[t]=l>>>16|l<<16,Wg[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)Kg[e]=i<<24,i=i<<1^(i&128?283:0);qg=!0},Yg=class{constructor(){this.roundkey=/* @__PURE__ */ new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=/* @__PURE__ */ new Uint8Array(16),this.out=/* @__PURE__ */ new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){I(e.byteLength===16),I(t.byteLength===16),qg||Jg();let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^Bg[t>>>16&255]&4278190080^Bg[t>>>8&255]&16711680^Bg[t>>>0&255]&65280^Bg[t>>>24&255]&255^Kg[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;e<t;e+=4,t-=4)for(let n=0;n<4;n++){let r=this.roundkey[e+n];this.roundkey[e+n]=this.roundkey[t+n],this.roundkey[t+n]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let n=this.roundkey[e+t];this.roundkey[e+t]=Vg[Bg[n>>>24&255]&255]^Hg[Bg[n>>>16&255]&255]^Ug[Bg[n>>>8&255]&255]^Wg[Bg[n>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3],i=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),s=this.inView.getUint32(12,!1),c,l,u,d;for(let i=1;i<10;i++){let a=i*4;c=Vg[e>>>24]^Hg[r>>>16&255]^Ug[n>>>8&255]^Wg[t&255]^this.roundkey[a],l=Vg[t>>>24]^Hg[e>>>16&255]^Ug[r>>>8&255]^Wg[n&255]^this.roundkey[a+1],u=Vg[n>>>24]^Hg[t>>>16&255]^Ug[e>>>8&255]^Wg[r&255]^this.roundkey[a+2],d=Vg[r>>>24]^Hg[n>>>16&255]^Ug[t>>>8&255]^Wg[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=Gg[e>>>24&255]&4278190080^Gg[r>>>16&255]&16711680^Gg[n>>>8&255]&65280^Gg[t>>>0&255]&255^this.roundkey[40],p=Gg[t>>>24&255]&4278190080^Gg[e>>>16&255]&16711680^Gg[r>>>8&255]&65280^Gg[n>>>0&255]&255^this.roundkey[41],m=Gg[n>>>24&255]&4278190080^Gg[t>>>16&255]&16711680^Gg[e>>>8&255]&65280^Gg[r>>>0&255]&255^this.roundkey[42],h=Gg[r>>>24&255]&4278190080^Gg[n>>>16&255]&16711680^Gg[t>>>8&255]&65280^Gg[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=i,this.iv[1]=a,this.iv[2]=o,this.iv[3]=s}},Xg=(e,t,n)=>{let r=!1,i=0,a=2**16,o=new Yg;return new ReadableStream({pull:async s=>{r||=(o.init(await t()),!0);let c=a+16,l=e.requestSliceRange(i,0,c);if(R(l)&&(l=await l),!l||l.length===0)throw Error(`Invalid ciphertext.`);let u=l.length;if(u%16!=0)throw Error(`Invalid ciphertext.`);let d=u===c?u-16:u,f=V(l,d),p=new Uint8Array(d);for(let e=0;e<d;e+=16)o.in.set(f.subarray(e,e+16)),o.decrypt(),p.set(o.out,e);if(d<u)s.enqueue(p),i+=d;else{let e=p[d-1];if(e===0||e>16)throw Error(`Invalid PKCS#7 padding. Incorrect key or corrupted data.`);let t=p.subarray(0,d-e);s.enqueue(t),s.close(),n()}},cancel:()=>{n()}})},Zg=class e extends Og{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=qf,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=/* @__PURE__ */ new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return jg({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1,n=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(R(r)&&(r=await r),!r)break;let i=e,a=Pg(r);if(!a)break;if(a.name===`ftyp`||a.name===`styp`){let e=xb(r,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(r.filePos,a.contentSize);if(R(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+a.totalSize,n=!0;break}else if(a.name===`moof`){if(!this.input._initInput)throw Error(`"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.`);await this.copyMetadataFromInitInput(this.input._initInput),t=!1,n=!0;break}e=i+a.totalSize}if(!n&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){I(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);R(e)&&(e=await e),I(e);let t=U(e),n=this.reader.fileSize-t;if(n>=0&&n<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(n,8,16);if(R(e)&&(e=await e),e){let t=Pg(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);R(n)&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}async copyMetadataFromInitInput(t){let n=await t._getDemuxer();if(n.constructor!==e)throw Error(`Init input must match the input's format.`);await n.readMetadata(),this.movieTimescale=n.movieTimescale,this.movieDurationInTimescale=n.movieDurationInTimescale,this.movieMatrix=n.movieMatrix,this.metadataTags=n.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=n.fragmentTrackDefaults,this.psshBoxes=n.psshBoxes;for(let e of n.tracks){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,matrix:e.matrix,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:e.maxBitrate,avgBitrate:e.avgBitrate,info:e.info};e.trackBacking&&(I(t.info),t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new $g(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new e_(t),this.tracks.push(t)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;I(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&Kh.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){I(e.info?.type===`audio`);let n=cg(e.info.codec),r=[],i=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],s=t.sampleToChunk[a+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let s=o.startSampleIndex+a*o.samplesPerChunk,c=s+o.samplesPerChunk,l=Op(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=Op(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,h=tp(r);h&&h.delta===m?h.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:p,count:1,delta:m});let g=o.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;i.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);R(t)&&(t=await t),I(t);let n=Pg(t);I(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);R(r)&&(r=await r),I(r),this.traverseBox(r);let i=this.lastReadFragment;I(i&&i.moofOffset===e);for(let[,e]of i.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(r)a_(e,r.timestamp);else{let t=Op(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];a_(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=Op(n,e.startTimestamp,e=>e.startTimestamp);if((r===-1||n[r].moofOffset!==i.moofOffset)&&n.splice(r+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){let n=await l_(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t<Math.min(e.samples.length,n.length);t++){let r=n[t];e.samples[t].encryption=r}}}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=Pg(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=Pg(e);if(!n)return!1;let r=e.filePos,i=t+n.totalSize;switch(n.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mvhd`:{let t=H(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=U(e),this.movieDurationInTimescale=gb(e)):(e.skip(8),this.movieTimescale=U(e),this.movieDurationInTimescale=U(e)),e.skip(16),this.movieMatrix=o_(e)}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...hm,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:qf,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(r,n.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new $g(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new e_(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=H(e),r=!!(lb(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=U(e),e.skip(4),t.durationInMovieTimescale=U(e);else if(n===1)e.skip(16),t.id=U(e),e.skip(4),t.durationInMovieTimescale=gb(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16),t.matrix=ep(o_(e),this.movieMatrix)}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=H(e);e.skip(3);let r=!1,i=0,a=U(e);for(let o=0;o<a;o++){let a=n===1?gb(e):U(e),o=n===1?_b(e):pb(e),s=Fg(e);if(r){dm._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){dm._warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=H(e);e.skip(3),n===0?(e.skip(8),t.timescale=U(e),t.durationInMediaTimescale=U(e)):n===1&&(e.skip(16),t.timescale=U(e),t.durationInMediaTimescale=gb(e));let r=cb(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;Wp(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=xb(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...bp},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,n.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=H(e);e.skip(3);let r=U(e);for(let i=0;i<r;i++){let r=e.filePos,i=Pg(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=cb(e),t.info.height=cb(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let n=a===`encv`?t.frmaCodecString:a;t.frmaCodecString=null,n===`avc1`||n===`avc3`?(t.info.codec=`avc`,t.info.avcType=n===`avc1`?1:3):n===`hvc1`||n===`hev1`?t.info.codec=`hevc`:n===`vp08`?t.info.codec=`vp8`:n===`vp09`?t.info.codec=`vp9`:n===`av01`?t.info.codec=`av1`:eg.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?dm._warn(`Unknown encrypted video codec due to missing frma box.`):dm._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=cb(e);e.skip(6);let s=cb(e),c=cb(e);e.skip(4);let l=U(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*U(e),e.skip(8)):o===2&&(e.skip(4),l=bb(e),s=U(e),e.skip(4),c=U(e),u=U(e),e.skip(8))),t.info.numberOfChannels=s,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let d=a===`enca`?t.frmaCodecString:a;if(t.frmaCodecString=null,d!==`mp4a`){if(d===`opus`)t.info.codec=`opus`,t.info.sampleRate=og;else if(d===`flac`)t.info.codec=`flac`;else if(d===`ulaw`)t.info.codec=`ulaw`;else if(d===`alaw`)t.info.codec=`alaw`;else if(d===`ac-3`)t.info.codec=`ac3`;else if(d===`ec-3`)t.info.codec=`eac3`;else if(tg.includes(d))t.info.codec=`dts`,t.info.dtsFormat=d;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(dm._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if(d===`sowt`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(dm._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if(d===`raw `)t.info.codec=`pcm-u8`;else if(d===`in24`)t.info.codec=t.info.pcmLittleEndian?`pcm-s24`:`pcm-s24be`;else if(d===`in32`)t.info.codec=t.info.pcmLittleEndian?`pcm-s32`:`pcm-s32be`;else if(d===`fl32`)t.info.codec=t.info.pcmLittleEndian?`pcm-f32`:`pcm-f32be`;else if(d===`fl64`)t.info.codec=t.info.pcmLittleEndian?`pcm-f64`:`pcm-f64be`;else if(d===`ipcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===16?t.info.codec=`pcm-s16`:e===24?t.info.codec=`pcm-s24`:e===32?t.info.codec=`pcm-s32`:(dm._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):e===16?t.info.codec=`pcm-s16be`:e===24?t.info.codec=`pcm-s24be`:e===32?t.info.codec=`pcm-s32be`:(dm._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if(d===`fpcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===32?t.info.codec=`pcm-f32`:e===64?t.info.codec=`pcm-f64`:(dm._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(dm._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if(d===`lpcm`&&u!==null){let e=c+7>>3,n=!!(u&1),r=!!(u&2),i=u&4?-1:0;c>0&&c<=64&&(n?c===32&&(t.info.codec=r?`pcm-f32be`:`pcm-f32`):i&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=r?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=r?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=r?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&dm._warn(`Unsupported PCM format.`)}else d===null?dm._warn(`Unknown encrypted audio codec due to missing frma box.`):dm._warn(`Unsupported audio codec (sample entry type '${i.name}').`)}}e.filePos=r+i.totalSize}}break;case`frma`:{let t=this.currentTrack;if(!t)break;t.frmaCodecString=xb(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=xb(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:dm._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=H(e);e.skip(3),e.skip(1);let r=H(e);if(n>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=r&15):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=H(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=H(e),t.encryptionInfo.defaultKid=wp(V(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=H(e),r=/* @__PURE__ */ new Uint8Array(16);r.set(V(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t||(I(t.info),n.contentSize===0))break;t.info.codecDescription=V(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t||(I(t.info),n.contentSize===0))break;t.info.codecDescription=V(e,n.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`video`),e.skip(4);let n=H(e),r=H(e),i=H(e),a=i>>4,o=i>>1&7,s=i&1,c=H(e),l=H(e),u=H(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`video`),e.skip(1);let r=H(e),i=r>>5,a=r&31,o=H(e),s=o>>7,c=o>>6&1,l=o>>5&1,u=o>>4&1,d=o>>3&1,f=o>>2&1,p=o&3,m=i===2&&c?l?12:10:c?10:8;e.skip(1);let h=sh(V(e,n.contentSize-4));t.info.av1CodecInfo={profile:i,level:a,tier:s,bitDepth:m,monochrome:u,chromaSubsamplingX:d,chromaSubsamplingY:f,chromaSamplePosition:p,videoFullRangeFlag:h?.videoFullRangeFlag??0,colourPrimaries:h?.colourPrimaries??2,transferCharacteristics:h?.transferCharacteristics??2,matrixCoefficients:h?.matrixCoefficients??2}}break;case`colr`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`video`);let n=xb(e,4);if(n!==`nclx`&&n!==`nclc`)break;let r=cb(e),i=cb(e),a=cb(e),o;n===`nclx`&&(o=!!(H(e)&128)),t.info.colorSpace={primaries:pp[r],transfer:hp[i],matrix:_p[a],fullRange:o}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`video`);let n=U(e),r=U(e);n>0&&r>0&&(n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n))}break;case`btrt`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=U(e),r=U(e);t.maxBitrate=n>0?n:null,t.avgBitrate=r>0?r:null}break;case`wave`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4),I(H(e)===3),Lg(e),e.skip(2);let n=H(e),r=!!(n&128),i=!!(n&64),a=!!(n&32);if(r&&e.skip(2),i){let t=H(e);e.skip(t)}a&&e.skip(2),I(H(e)===4);let o=Lg(e),s=e.filePos,c=H(e);if(c===64||c===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?t.info.codec=`mp3`:c===221?t.info.codec=`vorbis`:c===169?t.info.codec=`dts`:dm._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){I(H(e)===5);let n=Lg(e);if(t.info.codecDescription=V(e,n),t.info.codec===`aac`){let e=bm(t.info.codecDescription);e.outputNumberOfChannels!==null&&(t.info.numberOfChannels=e.outputNumberOfChannels),e.outputSampleRate!==null&&(t.info.sampleRate=e.outputSampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),t.info.pcmLittleEndian=!!(cb(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),e.skip(4);let n=H(e);t.info.pcmLittleEndian=!!(n&1),t.info.pcmSampleSize=H(e)}break;case`dOps`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),e.skip(1);let n=H(e),r=cb(e),i=U(e),a=ub(e),o=H(e),s;s=o===0?/* @__PURE__ */ new Uint8Array:V(e,2+n);let c=new Uint8Array(19+s.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,n),l.setUint16(10,r,!0),l.setUint32(12,i,!0),l.setInt16(16,a,!0),l.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),e.skip(4);let n=e.filePos;for(;e.filePos<i;){let n=H(e),r=lb(e);if((n&127)===hh.STREAMINFO){e.skip(10);let n=U(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let a=V(e,r-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`);let n=new _m(V(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=Dm[r]),t.info.numberOfChannels=_h[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`);let r=Ch(V(e,n.contentSize));if(!r){dm._warn(`Invalid dec3 box contents, ignoring.`);break}let i=wh(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=Th(r)}break;case`ddts`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`);let r=Hh(V(e,Math.min(n.contentSize,20)));if(!r){dm._warn(`Invalid ddts box contents, ignoring.`);break}t.info.sampleRate=r.sampleRate,r.numberOfChannels!==null&&(t.info.numberOfChannels=r.numberOfChannels)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e),r=0,i=0;for(let a=0;a<n;a++){let n=U(e),a=U(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e),r=0;for(let i=0;i<n;i++){let n=U(e),i=pb(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e),r=U(e);if(n===0)for(let n=0;n<r;n++){let n=U(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=H(e),r=U(e),i=new _m(V(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=U(e);for(let r=0;r<n;r++){let n=U(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e);for(let r=0;r<n;r++){let n=U(e)-1,r=U(e),i=U(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e);for(let r=0;r<n;r++){let n=U(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e);for(let r=0;r<n;r++){let n=gb(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mehd`:{let t=H(e);e.skip(3);let n=t===1?gb(e):U(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=U(e),n=U(e),r=U(e),i=U(e),a=U(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=H(e);e.skip(3);let n=U(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=U(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[H,cb,lb,U],l=c[a],u=c[o],d=c[s],f=U(e);for(let n=0;n<f;n++){let n=t===1?gb(e):U(e),i=t===1?gb(e):U(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:/* @__PURE__ */ new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(r,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(I(this.currentFragment),this.readContiguousBoxes(e.slice(r,n.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);cond:if(e){if(e.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break cond}e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let n=e.presentationTimestamps[t],r=e.samples[n.sampleIndex];e.firstKeyFrameTimestamp===null&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-n.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],n=e.samples[tp(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=n.presentationTimestamp+n.duration;let{currentFragmentState:r}=this.currentTrack;I(r),r.startTimestamp!==null&&(a_(e,r.startTimestamp),e.startTimestampIsFinal=!0),r.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=r.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=Mg(V(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{I(this.currentFragment),e.skip(1);let t=lb(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=U(e),u=this.tracks.find(e=>e.id===l);if(!u)break;let d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},n?u.currentFragmentState.baseDataOffset=gb(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=U(e)),i&&(u.currentFragmentState.defaultSampleDuration=U(e)),a&&(u.currentFragmentState.defaultSampleSize=U(e)),o&&(u.currentFragmentState.defaultSampleFlags=U(e)),s&&(u.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;I(t.currentFragmentState);let n=H(e);e.skip(3);let r=n===0?U(e):gb(e);t.currentFragmentState.startTimestamp=r}break;case`trun`:{let t=this.currentTrack;if(!t)break;I(this.currentFragment),I(t.currentFragmentState);let n=H(e),r=lb(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=U(e),d=null;i&&(d=pb(e));let f=null;a&&(f=U(e));let p;this.currentFragment.trackData.has(t.id)?(p=this.currentFragment.trackData.get(t.id),d!==null&&(p.currentOffset=t.currentFragmentState.baseDataOffset+d)):(p={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,p));for(let r=0;r<u;r++){let i;o?i=U(e):(I(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=U(e):(I(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=U(e):(I(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=n===0?U(e):pb(e));let m=!(u&65536);p.samples.push({presentationTimestamp:p.currentTimestamp+d,duration:i,byteOffset:p.currentOffset,byteSize:a,isKeyFrame:m,encryption:null}),p.currentOffset+=a,p.currentTimestamp+=i}this.currentFragment.implicitBaseDataOffset=p.currentOffset}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),lb(e)&1){let n=xb(e,4),r=U(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=H(e),r=U(e),i=null;n===0&&r>0&&(i=V(e,r));let a=c_(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=H(e);if(lb(e)&1){let n=xb(e,4),r=U(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=U(e);if(r===0)break;r>1&&dm._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?U(e):Number(gb(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=c_(t);a.offset=i}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;I(this.currentFragment);let n=this.currentFragment.trackData.get(t.id);if(!n)break;e.skip(1);let r=!!(lb(e)&2),i=U(e),a=t.encryptionInfo.defaultPerSampleIvSize;I(a!==null);for(let o=0;o<Math.min(i,n.samples.length);o++){let i=/* @__PURE__ */ new Uint8Array(16);a>0?i.set(V(e,a),0):i.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(r){let t=cb(e);s=[];for(let n=0;n<t;n++){let t=cb(e),n=U(e);s.push({clearLen:t,protectedLen:n})}}let c=n.samples[o];c.encryption={iv:i,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=Rg(n):this.metadataTags.raw[e.name]??=V(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=lp.decode(V(n,e.contentSize)):this.metadataTags.title??=Rg(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=Rg(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=Rg(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=Rg(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=Rg(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=Rg(n));break;case`©day`:if(!this.currentTrack){let e=new Date(Rg(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=Rg(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=Rg(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=U(e)!==0;this.currentMetadataKeys=/* @__PURE__ */ new Map,t?this.readContiguousBoxes(e.slice(r,n.contentSize)):this.readContiguousBoxes(e.slice(r+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=U(e);for(let n=0;n<t;n++){let t=U(e);e.skip(4);let r=lp.decode(V(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=zg(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof fm?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=op(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=op(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=i,!0}},Qg=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=/* @__PURE__ */ new WeakMap,this.packetToFragmentLocation=/* @__PURE__ */ new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(I(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Lp(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=t_(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!s_(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=Op(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=n_(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!s_(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=Mp(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let e=i_(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return I(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=r_(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=kg;else{let t=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(R(t)&&(t=await t),!t)return null;if(r=V(t,n.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){let n=await l_(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(t=n[e])}t??=u_(this.internalTrack.encryptionInfo),t&&(r=await d_(this.internalTrack,t,r,null))}}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new Ag(r,n.isKeyFrame?`key`:`delta`,i,a,e,n.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).samples[t];I(r);let i;if(n.metadataOnly)i=kg;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(R(t)&&(t=await t),!t)return null;if(i=V(t,r.byteSize),this.internalTrack.encryptionInfo){let t=r.encryption??u_(this.internalTrack.encryptionInfo);t&&(i=await d_(this.internalTrack,t,i,e))}}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new Ag(i,r.isKeyFrame?`key`:`delta`,a,o,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,n,r,i){let a=this.internalTrack.demuxer,o=null,s=null,c=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,i);n!==-1&&(s=e,c=n)}let l=Op(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=Op(this.internalTrack.fragmentPositionCache,n,e=>e.startTimestamp),f=d===-1?null:this.internalTrack.fragmentPositionCache[d],p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(m,8,16);if(R(e)&&(e=await e),!e)break;let n=m,l=Pg(e);if(!l)break;if(l.name===`moof`){o=await a.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,i);e!==-1&&(s=o,c=e)}m=n+l.totalSize}if(u&&(!s||s.moofOffset<u.moofOffset)){let e=this.internalTrack.fragmentLookupTable[l-1];I(!e||e.timestamp<u.timestamp);let n=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,n,r,i)}return s?this.fetchPacketInFragment(s,c,i):null}},$g=class extends Qg{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`video`}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Lm(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Km(e.data)}else if(this.internalTrack.info.codec===`vp9`&&(!this.internalTrack.info.vp9CodecInfo||!ah(this.internalTrack.info.vp9CodecInfo))){let e=await this.getFirstPacket({}),t=e&&ih(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else if(this.internalTrack.info.codec===`av1`&&(!this.internalTrack.info.av1CodecInfo||!ch(this.internalTrack.info.av1CodecInfo))){let e=await this.getFirstPacket({}),t=e&&sh(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else if(this.internalTrack.info.codec===`prores`&&!this.internalTrack.info.proresCodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&lh(e.data)}if(!vp(this.internalTrack.info.colorSpace)){let e=ig(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let e={codec:rg(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},e_=class extends Qg{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`audio`}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&zh(e.data)}return{codec:ag(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},t_=(e,t)=>{if(e.presentationTimestamps){let n=Op(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=Op(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},n_=(e,t)=>{if(!e.keySampleIndices)return t_(e,t);if(e.presentationTimestamps){let n=Op(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(Dp(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=t_(e,t),r=Op(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},r_=(e,t)=>{let n=Op(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=t)return null;let i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=Op(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=Op(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];I(l);let u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=0,m=d;if(e.sampleSizes.length===1)m+=s*(t-f),p+=s*l.samplesPerChunk;else for(let n=f;n<f+l.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(m+=r),p+=r}let h=r.delta;if(e.presentationTimestamps){let n=e.presentationTimestampIndexMap[t];I(n!==void 0),n<e.presentationTimestamps.length-1&&(h=e.presentationTimestamps[n+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:h,sampleOffset:m,sampleSize:s,chunkOffset:d,chunkSize:p,isKeyFrame:!e.keySampleIndices||Dp(e.keySampleIndices,t,e=>e)!==-1}},i_=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=Op(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},a_=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},o_=e=>[Fg(e),Fg(e),Ig(e),Fg(e),Fg(e),Ig(e),Fg(e),Fg(e),Ig(e)],s_=e=>e.sampleSizes.length===0,c_=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},l_=async(e,t,n)=>{if(n.resolved)return n.resolved;if(n.offset===null||n.sampleCount===0)throw Error(`Incomplete saiz/saio info; cannot resolve encryption data.`);let r=0;if(n.defaultSampleInfoSize>0)r=n.defaultSampleInfoSize*n.sampleCount;else{I(n.sampleSizes);for(let e=0;e<n.sampleCount;e++)r+=n.sampleSizes[e]}let i=e.requestSlice(n.offset,r);if(R(i)&&(i=await i),!i)throw Error(`Failed to read auxiliary encryption info.`);let a=t.defaultPerSampleIvSize;I(a!==null);let o=[];for(let e=0;e<n.sampleCount;e++){let r=n.defaultSampleInfoSize>0?n.defaultSampleInfoSize:n.sampleSizes[e],s=/* @__PURE__ */ new Uint8Array(16);a>0?s.set(V(i,a),0):s.set(t.defaultConstantIv,0);let c=null;if(r>a){let e=cb(i);c=[];for(let t=0;t<e;t++){let e=cb(i),t=U(i);c.push({clearLen:e,protectedLen:t})}}o.push({iv:s,subsamples:c})}return n.resolved=o,o},u_=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,d_=async(e,t,n,r)=>{I(e.encryptionInfo);let i=e.encryptionInfo;I(i.defaultKid!==null);let a=i.defaultKid,o,s=e.demuxer.decryptionKeyCache.get(a);if(s)o=await s;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error(`Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.`);let t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>e.keyIds===null||e.keyIds.includes(a));for(let e=0;e<t.length-1;e++)for(let n=e+1;n<t.length;n++)Ng(t[e],t[n])&&(t.splice(n,1),n--)}let n=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:t});if(!(typeof n==`string`&&n.length===32&&Cp.test(n)||n instanceof Uint8Array&&n.byteLength===16))throw TypeError(`resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.`);return n instanceof Uint8Array?n:Tp(n)})();e.demuxer.decryptionKeyCache.set(a,t),o=await t}return i.scheme===`cenc`||i.scheme===`cens`?f_(o,i,t,n):p_(o,i,t,n)},f_=async(e,t,n,r)=>{let i=/* @__PURE__ */ new Uint8Array(16);i.set(n.iv,0);let a=await crypto.subtle.importKey(`raw`,e,{name:`AES-CTR`},!1,[`decrypt`]),o=async e=>{let t=await crypto.subtle.decrypt({name:`AES-CTR`,counter:i,length:64},a,e);return new Uint8Array(t)};if(!n.subsamples)return o(r);I(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let s=m_(n.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),c=0;for(let e of s)for(let t of e.perSubsample)c+=t.length;let l=new Uint8Array(c),u=0;for(let e of s)for(let t of e.perSubsample)l.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;let d=await o(l),f=new Uint8Array(r),p=0;for(let e of s)for(let t of e.perSubsample)f.set(d.subarray(p,p+t.length),t.offset),p+=t.length;return f},p_=(e,t,n,r)=>{let i=new Yg;i.init({key:e,iv:n.iv});let a=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(I(a!==null&&o!==null),!n.subsamples){let e=new Uint8Array(r),t=Math.floor(r.length/16);for(let n=0;n<t;n++){let t=n*16;i.in.set(r.subarray(t,t+16)),i.decrypt(),e.set(i.out,t)}return e}if(a===0&&o===0)throw Error(`cbcs with subsamples requires pattern encryption.`);let s=new Uint8Array(r),c=m_(n.subsamples,a,o),l=new DataView(n.iv.buffer,n.iv.byteOffset,16);for(let e of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(let t of e.perSubsample){let e=t.length/16;for(let n=0;n<e;n++){let e=t.offset+n*16;i.in.set(r.subarray(e,e+16)),i.decrypt(),s.set(i.out,e)}}}return s},m_=(e,t,n)=>{let r=[],i=t!==0||n!==0,a=0;for(let o of e){a+=o.clearLen;let e=[];if(!i)o.protectedLen>0&&e.push({offset:a,length:o.protectedLen}),a+=o.protectedLen;else{let r=o.protectedLen,i=a;for(;r>0&&!(r<16*t);){let a=16*t;e.push({offset:i,length:a}),i+=a,r-=a;let o=Math.min(16*n,r);i+=o,r-=o}a+=o.protectedLen}r.push({perSubsample:e})}return r},z;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseYaw=30323]=`ProjectionPoseYaw`,e[e.ProjectionPosePitch=30324]=`ProjectionPosePitch`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(z||={});var h_=[z.EBML,z.Segment],g_=[z.SeekHead,z.Info,z.Cluster,z.Tracks,z.Cues,z.Attachments,z.Chapters,z.Tags],__=[...h_,...g_],v_=e=>{if(e.remainingLength<1)return null;let t=H(e);if(e.skip(-1),t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;return e.remainingLength<n?null:n},y_=e=>{if(e.remainingLength<1)return null;let t=H(e);if(t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;if(e.remainingLength<n-1)return null;let i=t&r-1;for(let t=1;t<n;t++)i*=256,i+=H(e);return i},B=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=H(e);return n},b_=(e,t)=>{if(t<1)throw Error(`Bad unsigned int size `+t);let n=0n;for(let r=0;r<t;r++)n<<=8n,n+=BigInt(H(e));return n},x_=e=>{let t=v_(e);return t===null||e.remainingLength<t?null:B(e,t)},S_=e=>{if(e.remainingLength<1)return null;if(H(e)===255)return;e.skip(-1);let t=y_(e);if(t===null)return null;if(t!==72057594037927940)return t},C_=e=>{I(e.remainingLength>=2);let t=x_(e);if(t===null)return null;let n=S_(e);return n===null?null:{id:t,size:n}},w_=(e,t)=>{let n=V(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},T_=(e,t)=>{let n=V(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return lp.decode(n.subarray(0,r))},E_=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?yb(e):bb(e)},D_=async(e,t,n,r)=>{let i=new Set(n),a=t;for(;r===null||a<r;){let t=e.requestSliceRange(a,2,16);if(R(t)&&(t=await t),!t)break;let n=C_(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};A_(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},O_=async(e,t,n,r)=>{let i=2**16,a=new Set(n),o=t;for(;o<r;){let t=e.requestSliceRange(o,0,Math.min(i,r-o));if(R(t)&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=x_(t);if(e!==null&&a.has(e))return o;o++}}return null},k_={avc:`V_MPEG4/ISO/AVC`,hevc:`V_MPEGH/ISO/HEVC`,vp8:`V_VP8`,vp9:`V_VP9`,av1:`V_AV1`,prores:`V_PRORES`,aac:`A_AAC`,mp3:`A_MPEG/L3`,opus:`A_OPUS`,vorbis:`A_VORBIS`,flac:`A_FLAC`,ac3:`A_AC3`,eac3:`A_EAC3`,dts:`A_DTS`,"pcm-u8":`A_PCM/INT/LIT`,"pcm-s16":`A_PCM/INT/LIT`,"pcm-s16be":`A_PCM/INT/BIG`,"pcm-s24":`A_PCM/INT/LIT`,"pcm-s24be":`A_PCM/INT/BIG`,"pcm-s32":`A_PCM/INT/LIT`,"pcm-s32be":`A_PCM/INT/BIG`,"pcm-f32":`A_PCM/FLOAT/IEEE`,"pcm-f64":`A_PCM/FLOAT/IEEE`,webvtt:`S_TEXT/WEBVTT`};function A_(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}var j_=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isWebM?`webm`:`x-matroska`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(`, `)}"`}return t},M_;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(M_||={});var N_;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(N_||={});var P_;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(P_||={});var F_=[{id:z.SeekHead,flag:`seekHeadSeen`},{id:z.Info,flag:`infoSeen`},{id:z.Tracks,flag:`tracksSeen`},{id:z.Cues,flag:`cuesSeen`}],I_=10*2**20,L_=class extends Og{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return j_({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`video`)),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`audio`)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let e of this.segments)e.metadataTagsCollected||=(this.reader.fileSize!==null&&await this.loadSegmentMetadata(e),!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,16);if(R(t)&&(t=await t),!t)break;let n=C_(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===z.EBML){A_(i);let e=this.reader.requestSlice(a,i);if(R(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===z.Segment){if(await this.readSegment(a,i),i===void 0||this.reader.fileSize===null)break}else if(r===z.Cluster){if(this.reader.fileSize===null)break;i===void 0&&(i=(await D_(this.reader,a,__,this.reader.fileSize)).pos-a);let e=tp(this.segments);e&&(e.elementEndPos=a+i)}A_(i),e=a+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(n,2,16);if(R(e)&&(e=await e),!e)break;let t=n,r=C_(e);if(!r||!g_.includes(r.id)&&r.id!==z.Void){let e=await O_(this.reader,t,g_,Math.min(this.currentSegment.elementEndPos??1/0,t+I_));if(e){n=e;continue}break}let{id:i,size:a}=r,o=e.filePos,s=F_.findIndex(e=>e.id===i);if(s!==-1){let e=F_[s].flag;this.currentSegment[e]=!0,A_(a);let t=this.reader.requestSlice(o,a);R(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(i===z.Tags||i===z.Attachments){i===z.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,A_(a);let e=this.reader.requestSlice(o,a);R(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(i===z.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(a===void 0)break;n=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=F_.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(R(r)&&(r=await r),!r)continue;let i=C_(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;A_(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);R(s)&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);let r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=r.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){let n=e.cuePoints[t],r=e.cuePoints[t+1];n.time===r.time&&(e.cuePoints.splice(t+1,1),t--)}}let i=null,a=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,2,16);R(n)&&(n=await n),I(n);let r=e,i=C_(n);I(i);let a=i.id;I(a===z.Cluster);let o=i.size,s=n.filePos;o===void 0&&(o=(await D_(this.reader,s,__,t.elementEndPos)).pos-s);let c=this.reader.requestSlice(s,o);R(c)&&(c=await c);let l={segment:t,elementStartPos:r,elementEndPos:s+o,dataStartPos:s,timestamp:-1,trackData:/* @__PURE__ */ new Map};this.currentCluster=l,c&&(l.elementEndPos=this.readContiguousElements(c,__));for(let[,e]of l.trackData){let t=e.track;I(e.blocks.length>0);let n=!1;for(let t=0;t<e.blocks.length;t++){let r=e.blocks[t];r.timestamp+=l.timestamp,n||=r.lacing!==M_.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){let r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[n+1].timestamp-i.timestamp:i.duration===0&&t.defaultDuration!=null&&i.lacing===M_.None&&(i.duration=t.defaultDuration)}n&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let i=e.blocks[e.presentationTimestamps[0].blockIndex],a=e.blocks[tp(e.presentationTimestamps).blockIndex];e.startTimestamp=i.timestamp,e.endTimestamp=a.timestamp+a.duration;let o=Op(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(o===-1||t.clusterPositionCache[o].elementStartPos!==r)&&t.clusterPositionCache.splice(o+1,0,{elementStartPos:l.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=l,l}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;n={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.lacing===M_.None)continue;r.decoded||=(r.data=this.decodeBlockData(t,r.data),!0);let i=ab.tempFromBytes(r.data),a=[],o=H(i)+1;switch(r.lacing){case M_.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;i.bufferPos<i.length;){let n=H(i);if(t+=n,n<255){a.push(t),e+=t;break}}}a.push(i.length-(i.bufferPos+e))}break;case M_.FixedSize:{let e=i.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)a.push(t)}break;case M_.Ebml:{let e=y_(i);I(e!==null);let t=e;a.push(t);let n=t;for(let e=1;e<o-1;e++){let e=i.bufferPos,r=y_(i);I(r!==null);let o=r-((1<<(i.bufferPos-e)*7-1)-1);t+=o,a.push(t),n+=t}a.push(i.length-(i.bufferPos+n))}break;default:I(!1)}I(a.length===o),e.splice(n,1);let s=r.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){let c=a[t],l=V(i,c),u=r.timestamp+s*t/o,d=s/o;e.splice(n+t,0,{timestamp:u,duration:d,isKeyFrame:r.isKeyFrame,data:l,lacing:M_.None,decoded:!0,postProcessed:!1,mainAdditional:r.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if((t.id!==z.Tags||e.tagsSeen)&&(t.id!==z.Attachments||e.attachmentsSeen))continue;let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(R(n)&&(n=await n),!n)continue;let r=C_(n);if(!r||r.id!==t.id)continue;let{size:i}=r;A_(i),I(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,i);R(a)&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===z.Tags?e.tagsSeen=!0:t.id===z.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let n=C_(e);if(!n||t&&t.includes(n.id))return!1;let{id:r,size:i}=n,a=e.filePos;switch(A_(i),r){case z.DocType:this.isWebM=w_(e,i)===`webm`;break;case z.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(a,i)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case z.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=B(e,i)}break;case z.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=B(e,i)}break;case z.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=B(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case z.Duration:if(!this.currentSegment)break;this.currentSegment.duration=E_(e,i);break;case z.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...hm,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:`eng`,hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,i)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==N_.Block||e.data.algorithm!==P_.HeaderStripping)&&(dm._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let e=this.currentTrack.codecId.indexOf(`/`),t=e===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if(this.currentTrack.info.type===`video`&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===k_.avc)this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===k_.hevc)this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===k_.vp8)this.currentTrack.info.codec=`vp8`;else if(t===k_.vp9)this.currentTrack.info.codec=`vp9`;else if(t===k_.av1)this.currentTrack.info.codec=`av1`;else if(t===k_.prores){let e=this.currentTrack.codecPrivate?lp.decode(this.currentTrack.codecPrivate):``;eg.includes(e)&&(this.currentTrack.info.codec=`prores`,this.currentTrack.info.proresFormat=e)}let e=this.currentTrack;this.currentTrack.trackBacking=new z_(e),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`){t===k_.aac?(this.currentTrack.info.codec=`aac`,this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes(`MPEG2`),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===k_.mp3?this.currentTrack.info.codec=`mp3`:t===k_.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=og):t===k_.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===k_.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===k_.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===k_.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===k_.dts?(this.currentTrack.info.codec=`dts`,this.currentTrack.codecId===`A_DTS/EXPRESS`?this.currentTrack.info.dtsFormat=`dtse`:this.currentTrack.codecId===`A_DTS/LOSSLESS`&&(this.currentTrack.info.dtsFormat=`dtsl`)):this.currentTrack.codecId===`A_PCM/INT/LIT`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32`):this.currentTrack.codecId===`A_PCM/INT/BIG`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16be`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24be`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32be`):this.currentTrack.codecId===`A_PCM/FLOAT/IEEE`&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec=`pcm-f32`:this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec=`pcm-f64`));let e=this.currentTrack;this.currentTrack.trackBacking=new B_(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case z.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=B(e,i);break;case z.TrackType:{if(!this.currentTrack)break;let t=B(e,i);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...bp},alphaMode:!1,proresFormat:null}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case z.FlagEnabled:if(!this.currentTrack)break;B(e,i)||(this.currentTrack=null);break;case z.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!B(e,i);break;case z.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!B(e,i);break;case z.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!B(e,i);break;case z.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!B(e,i);break;case z.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!B(e,i);break;case z.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!B(e,i);break;case z.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=w_(e,i);break;case z.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=V(e,i);break;case z.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=B(e,i);break;case z.Name:if(!this.currentTrack)break;this.currentTrack.name=T_(e,i);break;case z.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=w_(e,i),Wp(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case z.LanguageBCP47:{if(!this.currentTrack)break;let t=w_(e,i).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`,this.currentTrack.hasLanguageBcp47=!0}break;case z.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case z.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=B(e,i);break;case z.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=B(e,i);break;case z.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=B(e,i);break;case z.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=B(e,i);break;case z.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=B(e,i);break;case z.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=B(e,i)===1;break;case z.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case z.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`)break;let t=_p[B(e,i)];this.currentTrack.info.colorSpace.matrix=t}break;case z.Range:{if(this.currentTrack?.info?.type!==`video`)break;let t=B(e,i);this.currentTrack.info.colorSpace.fullRange=t===1||t===2?t===2:void 0}break;case z.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`)break;let t=hp[B(e,i)];this.currentTrack.info.colorSpace.transfer=t}break;case z.Primaries:{if(this.currentTrack?.info?.type!==`video`)break;let t=pp[B(e,i)];this.currentTrack.info.colorSpace.primaries=t}break;case z.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case z.ProjectionPoseYaw:{if(this.currentTrack?.info?.type!==`video`)break;let t=E_(e,i);try{let e=Kf(t);this.currentTrack.info.horizontalScale=Math.round(Math.cos(e*Wf))}catch{}}break;case z.ProjectionPosePitch:{if(this.currentTrack?.info?.type!==`video`)break;let t=E_(e,i);try{let e=Kf(t);this.currentTrack.info.verticalScale=Math.round(Math.cos(e*Wf))}catch{}}break;case z.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-E_(e,i);try{this.currentTrack.info.rotation=Kf(t)}catch{}}break;case z.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(a,i));break;case z.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=E_(e,i);break;case z.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=B(e,i);break;case z.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=B(e,i);break;case z.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,i)),this.currentCueTime=null;break;case z.CueTime:this.currentCueTime=B(e,i);break;case z.CueTrackPositions:{if(this.currentCueTime===null)break;I(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(a,i)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case z.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=B(e,i)}break;case z.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;I(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+B(e,i)}break;case z.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=B(e,i);break;case z.SimpleBlock:{if(!this.currentCluster)break;let t=y_(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=ub(e),o=H(e),s=o>>1&3,c=!!(o&128);n.track.info?.type===`audio`&&n.track.info.codec&&(c=!0);let l=V(e,i-(e.filePos-a)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case z.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,i)),this.currentBlock=null;break;case z.Block:{if(!this.currentCluster)break;let t=y_(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=ub(e),o=H(e)>>1&3,s=V(e,i-(e.filePos-a)),c=n.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:o,decoded:!c,postProcessed:!1,mainAdditional:null},n.blocks.push(this.currentBlock)}break;case z.BlockAdditions:this.readContiguousElements(e.slice(a,i));break;case z.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,i)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case z.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=V(e,i);break;case z.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=B(e,i);break;case z.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=B(e,i);break;case z.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case z.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,i));break;case z.Targets:this.readContiguousElements(e.slice(a,i));break;case z.TargetTypeValue:B(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case z.TagTrackUID:case z.TagEditionUID:case z.TagChapterUID:case z.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case z.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,i));break;case z.TagName:this.currentSimpleTagName=T_(e,i);break;case z.TagString:{if(!this.currentSimpleTagName)break;let t=T_(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case z.TagBinary:{if(!this.currentSimpleTagName)break;let t=V(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case z.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,i));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new pm(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith(`image/`)&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case z.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=b_(e,i);break;case z.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=T_(e,i);break;case z.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=w_(e,i);break;case z.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=V(e,i);break;case z.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=T_(e,i);break;case z.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,i)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case z.ContentEncoding:this.currentDecodingInstruction={order:0,scope:N_.Block,data:null},this.readContiguousElements(e.slice(a,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case z.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=B(e,i);break;case z.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=B(e,i);break;case z.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:P_.Zlib,settings:null},this.readContiguousElements(e.slice(a,i));break;case z.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=B(e,i);break;case z.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=V(e,i);break;case z.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`}}return e.filePos=a+i,!0}decodeBlockData(e,t){I(e.decodingInstructions.length>0);let n=t;for(let t of e.decodingInstructions)if(I(t.data),t.data.type===`decompress`)switch(t.data.algorithm){case P_.HeaderStripping:if(t.data.settings&&t.data.settings.length>0){let e=t.data.settings,r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length),n=r}}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t==`string`)switch(e.toLowerCase()){case`title`:n.title??=t;break;case`description`:n.description??=t;break;case`artist`:n.artist??=t;break;case`album`:n.album??=t;break;case`album_artist`:n.albumArtist??=t;break;case`genre`:n.genre??=t;break;case`comment`:n.comment??=t;break;case`lyrics`:n.lyrics??=t;break;case`date`:{let e=new Date(t);Number.isNaN(e.getTime())||(n.date??=e)}break;case`track_number`:case`part_number`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`disc_number`:case`disc`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let t=null;for(let n of e.tracks){I(n.trackBacking);let e=await n.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(t??1/0,e.timestamp))}let n=e.duration/e.timestampFactor;return n+=t??0,n}},R_=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=/* @__PURE__ */ new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.segments)for(let e of r.tracks)if(e.trackBacking.getType()===t&&n++,e===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Lp(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=Op(t.presentationTimestamps,n,e=>e.timestamp);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id);if(n.blockIndex+1<t.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=Mp(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=n);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>n.blockIndex);if(t!==-1)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.blocks.findIndex(e=>e.isKeyFrame);return I(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).blocks[t];if(I(r),r.decoded||=(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),!0),!r.postProcessed){if(this.internalTrack.info?.codec===`prores`&&!(r.data.length>=8&&r.data[4]===105&&r.data[5]===99&&r.data[6]===112&&r.data[7]===102)){let e=new Uint8Array(r.data.length+8);op(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(r.data,8),r.data=e}r.postProcessed=!0}let i=n.metadataOnly?kg:r.data,a=r.timestamp/this.internalTrack.segment.timestampFactor,o=r.duration/this.internalTrack.segment.timestampFactor,s={};r.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(s.alpha=n.metadataOnly?kg:r.mainAdditional,s.alphaByteLength=r.mainAdditional.byteLength);let c=new Ag(i,r.isKeyFrame?`key`:`delta`,a,o,e.dataStartPos+t,r.data.byteLength,s);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,n,r,i){let{demuxer:a,segment:o}=this.internalTrack,s=null,c=null,l=-1;if(e){let{blockIndex:n,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,n,i);n!==-1&&(c=e,l=n)}let u=Op(this.internalTrack.cuePoints,n,e=>e.time),d=u===-1?null:this.internalTrack.cuePoints[u],f=Op(this.internalTrack.clusterPositionCache,n,e=>e.startTimestamp),p=f===-1?null:this.internalTrack.clusterPositionCache[f],m=Math.max(d?.clusterPosition??0,p?.elementStartPos??0)||null,h;for(e?m===null||e.elementStartPos>=m?(h=e.elementEndPos,s=e):h=m:h=m??o.clusterSeekStartPos;o.elementEndPos===null||h<=o.elementEndPos-2;){if(s){let e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(h,2,16);if(R(e)&&(e=await e),!e)break;let n=h,u=C_(e);if(!u||!g_.includes(u.id)&&u.id!==z.Void){let e=await O_(a.reader,n,g_,Math.min(o.elementEndPos??1/0,n+I_));if(e){h=e;continue}break}let d=u.id,f=u.size,p=e.filePos;if(d===z.Cluster){s=await a.readCluster(n,o),f=s.elementEndPos-p;let{blockIndex:e,correctBlockFound:r}=t(s);if(r)return this.fetchPacketInCluster(s,e,i);e!==-1&&(c=s,l=e)}f===void 0&&(I(d!==z.Cluster),f=(await D_(a.reader,p,__,o.elementEndPos)).pos-p);let m=p+f;if(o.elementEndPos===null){let e=a.reader.requestSliceRange(m,2,16);if(R(e)&&(e=await e),!e)break;if(x_(e)===z.Segment){o.elementEndPos=m;break}}h=m}if(d&&(!c||c.elementStartPos<d.clusterPosition)){let e=this.internalTrack.cuePoints[u-1];I(!e||e.time<d.time);let n=e?.time??-1/0;return this.performClusterLookup(null,t,n,r,i)}return c?this.fetchPacketInCluster(c,l,i):null}},z_=class extends R_{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`video`}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getTransformationMatrix(){let e=this.internalTrack.info;return Jf(ep($f(e.horizontalScale,e.verticalScale),Zf(e.rotation)),e.width,e.height)}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec===`vp9`||this.internalTrack.info.codec===`av1`||this.internalTrack.info.codec===`prores`||this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let t={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec===`avc`&&e?Lm(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?Km(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?ih(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?sh(e.data):null,proresCodecInfo:this.internalTrack.info.codec===`prores`&&e?lh(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!vp(this.internalTrack.info.colorSpace)){let e=ig(t);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let n={codec:rg(t),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}},B_=class extends R_{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`audio`}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&zh(e.data)}return{codec:ag({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},V_=async(e,t,n,r=null)=>{let i=2**16,a=t;for(;n===null||a<n;){let t=n===null?i:Math.min(i,n-a),o=e.requestSliceRange(a,4,t);if(R(o)&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let t=o.filePos,n=wg(U(o),e.fileSize===null?null:e.fileSize-a);if(n.header&&(!r||n.header.sampleRate===r.sampleRate&&n.header.mpegVersionId===r.mpegVersionId&&n.header.layer===r.layer&&Dg(n.header.channel)===Dg(r.channel)))return{header:n.header,startPos:a};o.filePos=t+n.bytesAdvanced,a=o.filePos}}return null},H_=class extends Og{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new Sp,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw Error(`No valid MP3 frame found.`);this.trackBackings=[new U_(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(R(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Ob(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await V_(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Cg(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(R(r)&&(r=await r),r){let i=U(r);if(i===1483304551||i===1231971951){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+n+4,12);if(R(t)&&(t=await t),t){let e=op(V(t,12)),n=e.getUint32(0,!1);this.xingData={frameCount:n&Eg.FrameCount?e.getUint32(4,!1):null,fileSize:n&Eg.FileSize?e.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return`audio/mpeg`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let n=this.reader.requestSlice(e,10);if(R(n)&&(n=await n),!n)break;let r=Ob(n);if(!r)break;t=!0;let i=this.reader.requestSlice(n.filePos,r.size);if(R(i)&&(i=await i),!i)break;kb(i,r,this.metadataTags),e=n.filePos+r.size}if(!t&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);R(e)&&(e=await e),I(e),xb(e,3)===`TAG`&&Eb(e,this.metadataTags)}return this.metadataTags}finally{e()}}},U_=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(I(e.firstFrameHeader!==null),I(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){let t=Sg(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`mp3`}getInternalCodecId(){return null}getNumberOfChannels(){return I(this.demuxer.firstFrameHeader),Dg(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...hm}}async getDecoderConfig(){return I(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:Dg(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=kg;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(R(e)&&(e=await e),!e)return null;r=V(e,n.dataSize)}return new Ag(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=Dp(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Op(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},W_=79764919,G_=/* @__PURE__ */ new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^W_:t<<1;G_[e]=t>>>0&4294967295}var K_=e=>{let t=op(e),n=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++){let n=e[t];r=(r<<8^G_[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},q_=(e,t,n)=>{let r=0,i=null;if(e.length>0){if(t.codec===`vorbis`){I(t.vorbisInfo);let a=t.vorbisInfo.modeBlockflags.length,o=(1<<Vp(a-1))-1<<1,s=(e[0]&o)>>1;if(s>=t.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let c=n,l=t.vorbisInfo.modeBlockflags[s];if(i=t.vorbisInfo.blocksizes[l],l===1){let n=(o|1)+1,r=e[0]&n?1:0;c=t.vorbisInfo.blocksizes[r]}r=c===null?0:c+i>>2}else t.codec===`opus`&&(r=fh(e).durationInSamples)}return{durationInSamples:r,vorbisBlockSize:i}},J_=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},Y_=65307,X_=e=>{let t=e.filePos;if(fb(e)!==1399285583)return null;e.skip(1);let n=H(e),r=vb(e),i=fb(e),a=fb(e),o=fb(e),s=H(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=H(e);let l=27+s,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:n,granulePosition:r,serialNumber:i,sequenceNumber:a,checksum:o,lacingValues:c}},Z_=(e,t)=>{for(;e.filePos<t-3;){let t=fb(e),n=t&255,r=t>>>8&255,i=t>>>16&255,a=t>>>24&255;if(n===79||r===79||i===79||a===79){if(e.skip(-4),t===1399285583)return!0;e.skip(1)}}return!1},Q_=class extends Og{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(R(t)&&(t=await t),!t)break;let n=X_(t);if(!n||!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&t.data[0]===1&&t.data[1]===118&&t.data[2]===111&&t.data[3]===114&&t.data[4]===98&&t.data[5]===105&&t.data[6]===115?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&t.data[0]===79&&t.data[1]===112&&t.data[2]===117&&t.data[3]===115&&t.data[4]===72&&t.data[5]===101&&t.data[6]===97&&t.data[7]===100&&await this.readOpusMetadata(t,e),e.codecInfo.codec!==null&&this.trackBackings.push(new $_(e,this)))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r||(n=await this.findNextPacketStart(r),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||r.data[0]!==3||i.data[0]!==5)return;let a=[],o=e=>{for(;a.push(Math.min(255,e)),!(e<255);)e-=255};o(e.data.length),o(r.data.length);let s=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);s[0]=2,s.set(a,1),s.set(e.data,1+a.length),s.set(r.data,1+a.length+e.data.length),s.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=s,t.lastMetadataPacket=i;let c=op(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);let l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:ph(i.data).modeBlockflags},gh(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r)return;t.codecInfo.codec=`opus`,t.description=e.data,t.lastMetadataPacket=r;let i=uh(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=og,t.codecInfo.opusInfo={preSkip:i.preSkip},gh(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){I(t<e.lacingValues.length);let n=0;for(let r=0;r<t;r++)n+=e.lacingValues[r];let r=e,i=n,a=t,o=[];outer:for(;;){let t=this.reader.requestSlice(r.dataStartPos,r.dataSize);R(t)&&(t=await t),I(t);let s=V(t,r.dataSize);for(;;){if(a===r.lacingValues.length){o.push(s.subarray(n,i));break}let e=r.lacingValues[a];if(i+=e,e<255){o.push(s.subarray(n,i));break outer}a++}let c=r.headerStartPos+r.totalSize;for(;;){let t=this.reader.requestSliceRange(c,27,282);if(R(t)&&(t=await t),!t)return null;let n=X_(t);if(!n)return null;if(r=n,r.serialNumber===e.serialNumber)break;c=r.headerStartPos+r.totalSize}n=0,i=0,a=0}let s=o.reduce((e,t)=>e+t.length,0);if(s===0)return null;let c=new Uint8Array(s),l=0;for(let e=0;e<o.length;e++){let t=o[e];c.set(t,l),l+=t.length}return{data:c,endPage:r,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(e.endPage.headerType&4)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(t,27,282);if(R(n)&&(n=await n),!n)return null;let r=X_(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),J_({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},$_=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=/* @__PURE__ */ new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Sp,this.internalSampleRate=e.codecInfo.codec===`opus`?og:e.sampleRate}getType(){return`audio`}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return I(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return I(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...hm,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(I(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:i}=q_(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new Ag(n.metadataOnly?kg:e.data,`key`,Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),a}async getFirstPacket(e){I(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec===`opus`&&(I(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw Error(`Packet was not created from this track.`);let r=await this.demuxer.findNextPacketStart(n.packet);if(!r)return null;let i=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=Lp(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;I(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=r.startPage,a=this.demuxer.reader.fileSize,o=[i];outer:for(;i.headerStartPos+i.totalSize<a;){let e=i.headerStartPos,t=Math.floor((e+a)/2),r=t;for(;;){let e=Math.min(r+Y_,a-27),s=this.demuxer.reader.requestSlice(r,e-r);if(R(s)&&(s=await s),I(s),!Z_(s,e)){a=t+27;continue outer}let c=this.demuxer.reader.requestSliceRange(s.filePos,27,282);R(c)&&(c=await c),I(c);let l=X_(c);I(l);let u=!1;if(l.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(l.headerStartPos,l.totalSize);R(e)&&(e=await e),I(e),u=K_(V(e,l.totalSize))===l.checksum}if(!u){r=l.headerStartPos+4;continue}if(u&&l.serialNumber!==this.bitstream.serialNumber){r=l.headerStartPos+l.totalSize;continue}if(l.granulePosition===-1){r=l.headerStartPos+l.totalSize;continue}this.granulePositionToTimestampInSamples(l.granulePosition)>n?a=l.headerStartPos:(i=l,o.push(l));continue outer}}let s=r.startPage;for(let e of o){if(e.granulePosition===i.granulePosition)break;(!s||e.headerStartPos>s.headerStartPos)&&(s=e)}let c=s,l=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==i.granulePosition;){let e=c.headerStartPos+c.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);R(t)&&(t=await t),I(t);let n=X_(t);I(n),c=n,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}I(c.granulePosition!==-1);let u=null,d,f,p=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{d=0,f=!1;for(let e=c.lacingValues.length-1;e>=0;e--)if(c.lacingValues[e]<255){u=e+1;break}if(u===null)throw Error(`Invalid page with granule position: no packets end on this page.`);m=u-1;let e={data:kg,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){let e=tv(l,c,u);I(e);let t=ev(l,e.page,e.segmentIndex);t&&(c=t.page,u=t.segmentIndex)}else for(;;){let e=tv(l,c,u);if(!e)break;let t=ev(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,u=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,m=e.segmentIndex;break}}}let h=null,g=null;for(;c!==null;){I(u!==null);let e=await this.demuxer.readPacket(c,u);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&u<r.startSegmentIndex)){let r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d,vorbisLastBlocksize:g?.vorbisBlockSize??null},t);I(r);let i=this.encodedPacketToMetadata.get(r);if(I(i),!f&&e.endPage.headerStartPos===p.headerStartPos&&e.endSegmentIndex===m?(d=this.granulePositionToTimestampInSamples(c.granulePosition),f=!0,r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d-i.durationInSamples,vorbisLastBlocksize:g?.vorbisBlockSize??null},t),I(r),i=this.encodedPacketToMetadata.get(r),I(i)):d+=i.durationInSamples,h=r,g=i,f&&(Math.max(d,0)>n||Math.max(i.timestampInSamples,0)===n))break}let i=await this.demuxer.findNextPacketStart(e);if(!i)break;c=i.startPage,u=i.startSegmentIndex}return h}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let n=Lp(e*this.internalSampleRate);e=n/this.internalSampleRate;let r=Op(this.sequentialScanCache,n,e=>e.timestampInSamples),i;if(r!==-1){let e=this.sequentialScanCache[r];i=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else i=await this.getFirstPacket(t);let a=0;for(;i&&i.timestamp<e;){let n=await this.getNextPacket(i,t);if(!n||n.timestamp>e)break;if(i=n,a++,a===100){a=0;let e=this.encodedPacketToMetadata.get(i);I(e),this.sequentialScanCache.length>0&&I(tp(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return i}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},ev=(e,t,n)=>{let r=t,i=n;outer:for(;;){for(i--;i>=0;i--)if(r.lacingValues[i]<255){i++;break outer}if(I(i===-1),!(r.headerType&1)){i=0;break}let t=jp(e,e=>e.headerStartPos<r.headerStartPos);if(!t)return null;r=t,i=r.lacingValues.length}if(I(i!==-1),i===r.lacingValues.length){let t=e[e.indexOf(r)+1];I(t),r=t,i=0}return{page:r,segmentIndex:i}},tv=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=jp(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null},nv;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=`ALAW`,e[e.MULAW=7]=`MULAW`,e[e.EXTENSIBLE=65534]=`EXTENSIBLE`})(nv||={});var rv=class extends Og{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);R(e)&&(e=await e),I(e);let t=xb(e,4),n=t!==`RIFX`,r=t===`RF64`,i=db(e,n),a=r?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(xb(e,4)!==`WAVE`)throw Error(`Invalid WAVE file - wrong format`);let o=0,s=null,c=e.filePos;for(;a===null||c<a;){let e=this.reader.requestSlice(c,8);if(R(e)&&(e=await e),!e)break;let t=xb(e,4),i=db(e,n),l=e.filePos;if(r&&o===0&&t!==`ds64`)throw Error(`Invalid RF64 file: First chunk must be "ds64".`);if(t===`fmt `)await this.parseFmtChunk(l,i,n);else if(t===`data`){if(s??=i,this.dataStart=e.filePos,this.dataSize=Math.min(s,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(t===`ds64`){let e=this.reader.requestSlice(l,i);if(R(e)&&(e=await e),!e)break;let t=hb(e,n);s=hb(e,n),a=Math.min(t+8,this.reader.fileSize??1/0)}else t===`LIST`?await this.parseListChunk(l,i,n):(t===`ID3 `||t===`id3 `)&&await this.parseId3Chunk(l,i);c=l+i+(i&1),o++}if(!this.audioInfo)throw Error(`Invalid WAVE file - missing "fmt " chunk`);if(this.dataStart===-1)throw Error(`Invalid WAVE file - missing "data" chunk`);let l=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/l)*l,this.trackBackings.push(new av(this))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(R(r)&&(r=await r),!r)return;let i=sb(r,n),a=sb(r,n),o=db(r,n);r.skip(4);let s=sb(r,n),c;if(c=t===14?8:sb(r,n),t>=18&&i!==357){let e=sb(r,n),a=t-18;if(Math.min(a,e)>=22&&i===nv.EXTENSIBLE){r.skip(6);let e=V(r,16);i=e[0]|e[1]<<8}}if((i===nv.MULAW||i===nv.ALAW)&&(c=8),i!==nv.PCM&&i!==nv.IEEE_FLOAT&&i!==nv.ALAW&&i!==nv.MULAW)throw Error(`Unsupported WAVE codec (format tag ${i}). Only integer/float PCM, A-law, and μ-law are supported.`);if(i===nv.PCM&&![8,16,24,32].includes(c))throw Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(i===nv.IEEE_FLOAT&&![32,64].includes(c))throw Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:i,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(R(r)&&(r=await r),!r)return;let i=xb(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=xb(r,4),t=db(r,n),i=V(r,t),o=0;for(let e=0;e<i.length&&i[e]!==0;e++)o++;let s=String.fromCharCode(...i.subarray(0,o));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=s,e){case`INAM`:case`TITL`:this.metadataTags.title??=s;break;case`TIT3`:this.metadataTags.description??=s;break;case`IART`:this.metadataTags.artist??=s;break;case`IPRD`:this.metadataTags.album??=s;break;case`IPRT`:case`ITRK`:case`TRCK`:{let e=s.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`ICRD`:case`IDIT`:{let e=new Date(s);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`YEAR`:{let e=Number.parseInt(s,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case`IGNR`:case`GENR`:this.metadataTags.genre??=s;break;case`ICMT`:case`CMNT`:case`COMM`:this.metadataTags.comment??=s}a+=8+t+(t&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(R(n)&&(n=await n),!n)return;let r=Ob(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&kb(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(I(this.audioInfo),this.audioInfo.format===nv.MULAW)return`ulaw`;if(this.audioInfo.format===nv.ALAW)return`alaw`;if(this.audioInfo.format===nv.PCM){if(this.audioInfo.sampleSizeInBytes===1)return`pcm-u8`;if(this.audioInfo.sampleSizeInBytes===2)return`pcm-s16`;if(this.audioInfo.sampleSizeInBytes===3)return`pcm-s24`;if(this.audioInfo.sampleSizeInBytes===4)return`pcm-s32`}if(this.audioInfo.format===nv.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return`pcm-f32`;if(this.audioInfo.sampleSizeInBytes===8)return`pcm-f64`}I(!1)}async getMimeType(){return`audio/wav`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},iv=2048,av=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(I(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return I(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...hm}}async getPacketAtIndex(e,t){I(e>=0),I(this.demuxer.audioInfo);let n=e*iv*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let r=Math.min(iv*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);if(R(e)&&(e=await e),!e)return null}let i;if(t.metadataOnly)i=kg;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);R(e)&&(e=await e),I(e),i=V(e,r)}let a=e*iv/this.demuxer.audioInfo.sampleRate,o=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Ag(i,`key`,a,o,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){I(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/iv,(this.demuxer.dataSize-1)/(iv*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let r=await this.getPacketAtIndex(n,t);if(r)return r;if(n===0)return null;I(this.demuxer.reader.fileSize===null);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){let e=await this.getNextPacket(i,t);if(!e)break;i=e}return i}getNextPacket(e,t){I(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/iv);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},ov=e=>{let t=e.filePos,n=new _m(V(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},sv=1024,cv=class extends Og{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new Sp,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();I(this.firstFrameHeader),this.trackBackings=[new lv(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(R(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Ob(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(R(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=ov(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||=t;let n=vm[t.samplingFrequencyIndex];I(n!==void 0);let r=sv/n,i={timestamp:this.nextTimestampInSamples/n,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(i),this.nextTimestampInSamples+=sv,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return`audio/aac`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(R(t)&&(t=await t),!t)break;let n=Ob(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(R(r)&&(r=await r),!r)break;kb(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},lv=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/sv}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`aac`}getInternalCodecId(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){I(this.demuxer.firstFrameHeader);let e=ym[this.demuxer.firstFrameHeader.channelConfiguration];return I(e!==void 0),e}getSampleRate(){I(this.demuxer.firstFrameHeader);let e=vm[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return I(e!==void 0),e}getDisposition(){return{...hm}}async getDecoderConfig(){return I(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=kg;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(R(e)&&(e=await e),!e)return null;r=V(e,n.dataSize)}return new Ag(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=Dp(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Op(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},uv=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`uncommon-u16`:e>=8&&e<=15?2**e:null,dv=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return`uncommon-u8`;case 13:return`uncommon-u16`;case 14:return`uncommon-u16-10`;default:return null}},fv=e=>{let t=0,n=new _m(V(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new _m(V(e,i)),o=8-t-1;for(let e=0;e<o;e++)r.unshift(n.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){let t=a.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,n)=>e|t<<n,0)},pv=(e,t)=>{if(t===`uncommon-u16`)return cb(e)+1;if(t===`uncommon-u8`)return H(e)+1;if(typeof t==`number`)return t;Np(t),I(!1)},mv=(e,t)=>t===`uncommon-u16`?cb(e):t===`uncommon-u16-10`?cb(e)*10:t===`uncommon-u8`?H(e):typeof t==`number`?t:null,hv=e=>{let t=0;for(let n of e){t^=n;for(let e=0;e<8;e++)t&128?t=t<<1^7:t<<=1,t&=255}return t},gv=class extends Og{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Sp,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),I(this.trackBacking),[this.trackBacking]}async getMimeType(){return`audio/flac`}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(R(t)&&(t=await t),!t){this.lastSampleLoaded=!0;return}let n=Ob(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);R(r)&&(r=await r),I(r),kb(r,n,this.metadataTags),e=t.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(R(t)&&(t=await t),e+=4,t===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);I(t);let n=H(t),r=lb(t),i=!!(n&128);switch(n&127){case hh.STREAMINFO:{let t=this.reader.requestSlice(e,r);if(R(t)&&(t=await t),I(t),t===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let n=V(t,34),i=new _m(n),a=i.readBits(16),o=i.readBits(16),s=i.readBits(24),c=i.readBits(24),l=i.readBits(20),u=i.readBits(3)+1;i.readBits(5);let d=i.readBits(36);i.skipBits(128);let f=/* @__PURE__ */ new Uint8Array(42);f.set(new Uint8Array([102,76,97,67]),0),f.set(new Uint8Array([128,0,0,34]),4),f.set(n,8),this.audioInfo={numberOfChannels:u,sampleRate:l,totalSamples:d,minimumBlockSize:a,maximumBlockSize:o,minimumFrameSize:s,maximumFrameSize:c,description:f},this.trackBacking=new _v(this);break}case hh.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,r);R(t)&&(t=await t),I(t),gh(V(t,r),this.metadataTags);break}case hh.PICTURE:{let t=this.reader.requestSlice(e,r);R(t)&&(t=await t),I(t);let n=U(t),i=U(t),a=lp.decode(V(t,i)),o=U(t),s=lp.decode(V(t,o));t.skip(16);let c=U(t),l=V(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:l,mimeType:a,kind:n===3?`coverFront`:n===4?`coverBack`:`unknown`,description:s});break}}if(e+=r,i){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw Error(`Missing STREAMINFO metadata block! Corrupted FLAC file.`)})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){I(this.audioInfo);let n=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,r=this.audioInfo.minimumFrameSize||10,i=(this.audioInfo.maximumFrameSize||n)+16,a=await this.reader.requestSliceRange(e,16,i);if(!a)return null;let o=this.readFlacFrameHeader({slice:a,isFirstPacket:t});if(!o)return null;for(a.filePos=e+r;;){if(a.filePos>a.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:a.end-e,isLastFrame:!0};if(H(a)===255){let t=a.filePos;if(H(a)!==(this.blockingBit===1?249:248)){a.filePos=t;continue}a.skip(-2);let n=a.filePos-e,r=this.readFlacFrameHeader({slice:a,isFirstPacket:!1});if(!r){a.filePos=t;continue}if(this.blockingBit===0){if(r.num-o.num!==1){a.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){a.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,r=new _m(V(e,4));if(r.readBits(15)!==32764)return null;if(this.blockingBit===null){I(t);let e=r.readBits(1);this.blockingBit=e}else if(this.blockingBit===1){if(I(!t),r.readBits(1)!==1)return null}else if(this.blockingBit===0){if(I(!t),r.readBits(1)!==0)return null}else throw Error(`Invalid blocking bit`);let i=uv(r.readBits(4));if(!i)return null;I(this.audioInfo);let a=dv(r.readBits(4),this.audioInfo.sampleRate);if(!a||(r.readBits(4),r.readBits(3),r.readBits(1)!==0))return null;let o=fv(e),s=pv(e,i),c=mv(e,a);if(c===null||c!==this.audioInfo.sampleRate)return null;let l=e.filePos-n,u=H(e);return e.skip(-l),e.skip(-1),u===hv(V(e,l))?{num:o,blockSize:s,sampleRate:c}:null}async advanceReader(){await this.readMetadata(),I(this.lastLoadedPos!==null),I(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos+=t.size,this.loadedSamples.push(r),t.isLastFrame){this.lastSampleLoaded=!0;return}}},_v=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...hm}}async getDecoderConfig(){return I(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(I(this.demuxer.audioInfo),e<0)return null;let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Op(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[n];if(r.blockOffset/this.demuxer.audioInfo.sampleRate+r.blockSize/this.demuxer.audioInfo.sampleRate<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=kg;else{let e=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(R(e)&&(e=await e),!e)return null;r=V(e,n.byteSize)}I(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new Ag(r,`key`,i,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}},vv=9e4,yv=2**33,bv=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},xv=`PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.`,Sv=5,Cv=1212435798,wv=1212436562,Tv=1146376960,Ev=/* @__PURE__ */ new Set([133,134,162]),Dv=/* @__PURE__ */ new Set,Ov=class extends Og{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);R(e)&&(e=await e),I(e);let t=V(e,205);if(t[0]===71&&t[188]===71)this.packetOffset=0,this.packetStride=188;else if(t[0]===71&&t[204]===71)this.packetOffset=0,this.packetStride=204;else if(t[4]===71&&t[196]===71)this.packetOffset=4,this.packetStride=192;else throw Error(`Unreachable.`);this.minReferencePointByteDistance=256*this.packetStride;let n=this.packetOffset,r=null,i=!1,a=!1;for(;;){let e=await this.readPacketHeader(n);if(!e)break;if(e.payloadUnitStartIndicator===0){n+=this.packetStride;continue}if(a&&!this.elementaryStreams.some(t=>t.pid===e.pid)){n+=this.packetStride;continue}let t=await this.readSection(n,!0,!a);if(!t)break;let o=!1;if(!a&&t.pid!==0&&(t.payload[0]!==0||t.payload[1]!==0||t.payload[2]!==1)){let e=new _m(t.payload),n=e.readAlignedByte();e.skipBits(8*n),o=e.readBits(8)===2}if(t.pid===0&&!i){let e=new _m(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(14);let a=e.readBits(10);for(e.skipBits(40);8*(a+3)-e.pos>32;){let t=e.readBits(16);e.skipBits(3);let n=e.readBits(13);if(t!==0){if(r!==null)throw Error(`Only files with a single program are supported.`);r=n}}if(r===null)throw Error(`Program Association Table must link to a Program Map Table.`);i=!0}else if((t.pid===r||o)&&!a){let e=new _m(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10),o=e.pos+8*i,s=!1;for(;e.pos<o;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===Sv&&n>=4){let t=e.readBits(32);s||=t===Cv||t===wv}e.pos=r}for(e.pos=o;8*(r+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let n=e.readBits(13);e.skipBits(6);let r=e.readBits(10),i=e.pos+8*r,a=!1,o=!1,c=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===106)a=!0;else if(t===122||t===204)o=!0;else if(t===123)c=!0;else if(t===Sv&&n>=4){let t=e.readBits(32);c||=(t&4294967040)===Tv}e.pos=r}let l=null,u=s&&Ev.has(t)?130:t;switch(u){case 27:case 36:l={type:`video`,codec:t===27?`avc`:`hevc`,decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=u===3||u===4?`mp3`:u===15?`aac`:u===129?`ac3`:u===135?`eac3`:`dts`,l={type:`audio`,codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:o?l={type:`audio`,codec:`eac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:a?l={type:`audio`,codec:`ac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:c&&(l={type:`audio`,codec:`dts`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Dv.has(t)||(dm._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Dv.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}a=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);outer:if(e&&!e.initialized){let n=Av(this,t,!0);if(!n)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=t.randomAccessIndicator===1,this.input._initInput){let n=(await this.input._initInput._getDemuxer()).elementaryStreams.find(n=>n.pid===t.pid&&n.info.codec===e.info.codec);if(n){e.info=n.info,e.initialized=!0;break outer}}let r=new Fv(e,n);if(e.info.type===`video`){for(;;){let t=r;if(t.suppliedPacket=null,await r.markNextPacket(),e.info.codec===`avc`){if(!r.suppliedPacket)throw Error(`Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.`);if(e.info.avcCodecInfo=Lm(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;let t=e.info.avcCodecInfo.sequenceParameterSets[0];I(t);let n=Vm(t);e.info.width=n.displayWidth,e.info.height=n.displayHeight;let i=n.pixelAspectRatio.num,a=n.pixelAspectRatio.den;i>0&&a>0&&(i>a?(e.info.squarePixelWidth=Math.round(e.info.width*i/a),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*a/i))),e.info.colorSpace={primaries:pp[n.colourPrimaries],transfer:hp[n.transferCharacteristics],matrix:_p[n.matrixCoefficients],fullRange:!!n.fullRangeFlag},e.info.reorderSize=n.maxDecFrameBuffering;break}if(e.info.codec===`hevc`){if(!r.suppliedPacket)throw Error(`Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.`);if(e.info.hevcCodecInfo=Km(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Am.SPS_NUT).nalUnits[0];I(t);let n=Gm(t);e.info.width=n.displayWidth,e.info.height=n.displayHeight,n.pixelAspectRatio.num>n.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*n.pixelAspectRatio.num/n.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*n.pixelAspectRatio.den/n.pixelAspectRatio.num)),e.info.colorSpace={primaries:pp[n.colourPrimaries],transfer:hp[n.transferCharacteristics],matrix:_p[n.matrixCoefficients],fullRange:!!n.fullRangeFlag},e.info.reorderSize=n.maxDecFrameBuffering;break}throw Error(`Unhandled.`)}e.info.decoderConfig={codec:rg({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},(e.info.width!==e.info.squarePixelWidth||e.info.height!==e.info.squarePixelHeight)&&(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await r.markNextPacket(),!r.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if(e.info.codec===`aac`){let t=ov(ab.tempFromBytes(r.suppliedPacket.data));if(!t)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=ym[t.channelConfiguration],e.info.sampleRate=vm[t.samplingFrequencyIndex]}else if(e.info.codec===`mp3`){let t=wg(U(ab.tempFromBytes(r.suppliedPacket.data)),r.suppliedPacket.data.byteLength);if(!t.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=Dg(t.header.channel),e.info.sampleRate=t.header.sampleRate}else if(e.info.codec===`ac3`){let t=vh(r.suppliedPacket.data);if(!t)throw Error(`Invalid AC-3 audio stream; could not read sync frame from first packet.`);if(t.fscod===3)throw Error(`Invalid AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=_h[t.acmod]+t.lfeon,e.info.sampleRate=Dm[t.fscod]}else if(e.info.codec===`eac3`){let t=Sh(r.suppliedPacket.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let n=wh(t);if(n===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=Th(t),e.info.sampleRate=n}else if(e.info.codec===`dts`){let t=Rh(r.suppliedPacket.data);if(!t)throw Error(`Invalid DTS audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?`dtsh`:`dtsc`)}else throw Error(`Unhandled.`);e.info.decoderConfig={codec:ag({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}if(a&&this.elementaryStreams.every(e=>e.initialized))break;n+=this.packetStride}if(!a)throw Error(i?`No Program Map Table found in the file.`:`No Program Association Table found in the file.`);for(let e of this.elementaryStreams)e.initialized&&(e.info.type===`video`?this.trackBackingEntries.push(new Mv(e)):this.trackBackingEntries.push(new Nv(e)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),bv(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,n=!1){let r=e,i=e,a=[],o=0,s=null,c=!0,l=0;for(;;){let e=await this.readPacket(i);if(i+=this.packetStride,!e)break;if(s){if(e.pid!==s.pid){if(n)break;continue}if(e.payloadUnitStartIndicator===1)break}else{if(e.payloadUnitStartIndicator===0)break;s=e}let u=!!(e.adaptationFieldControl&2),d=!!(e.adaptationFieldControl&1),f=0;if(u&&(f=1+e.body[0],e===s&&f>1&&(l=e.body[1]>>6&1)),d&&(f===0?(a.push(e.body),o+=e.body.byteLength):(a.push(e.body.subarray(f)),o+=e.body.byteLength-f)),r=i,!t&&o>=64){c=!1;break}if(Dp(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=Op(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!s)return null;let u;if(a.length===1)u=a[0];else{let e=a.reduce((e,t)=>e+t.length,0);u=new Uint8Array(e);let t=0;for(let e of a)u.set(e,t),t+=e.length}return{startPos:e,endPos:t?r:null,pid:s.pid,payload:u,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(R(t)&&(t=await t),!t)return null;if(H(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=cb(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=H(t);a>>6;let o=a>>4&3;return a&15,{payloadUnitStartIndicator:r,pid:i,adaptationFieldControl:o}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(R(t)&&(t=await t),!t)return null;let n=V(t,188);if(n[0]!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let r=(n[1]<<8)+n[2];r>>15;let i=r>>14&1;r>>13&1;let a=r&8191,o=n[3];o>>6;let s=o>>4&3;return o&15,{payloadUnitStartIndicator:i,pid:a,adaptationFieldControl:s,body:n.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){let t=60*vv;this.timestampWrapInfo={reference:e-t,offset:e>=yv-t?-yv:yv}}let{reference:t,offset:n}=this.timestampWrapInfo;return n<0&&e>=t||n>0&&e<t?e+n:e}},kv=(e,t,n)=>{if(t.payload.byteLength<3)return null;let r=new _m(t.payload);if(r.readBits(24)!==1)return null;let i=r.readBits(8);if(r.skipBits(16),i===188||i===190||i===191||i===240||i===241||i===255||i===242||i===248)return null;r.skipBits(8);let a=r.readBits(2);r.skipBits(14);let o=null;if(a===2||a===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=e.normalizeTimestamp(o);else if(n)throw Error(xv);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}},Av=(e,t,n)=>{I(t.endPos!==null);let r=kv(e,t,n);if(!r)return null;let i=new _m(t.payload);i.skipBits(32);let a=i.readBits(16);i.skipBits(16);let o=i.readBits(8),s=i.pos+8*o;i.pos=s;let c=s/8;I(Number.isInteger(c));let l=t.payload.subarray(c,a>0?6+a:t.payload.byteLength);return{...r,data:l}},jv=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=/* @__PURE__ */ new WeakMap,this.packetSectionStarts=/* @__PURE__ */ new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,n=this.elementaryStream.info.type,r=0;for(let i of t.trackBackingEntries)if(i.getType()===n&&r++,I(i instanceof e),i.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...hm,primary:!1}}getTimeResolution(){return vv}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,n){let r;return r=this.allPacketsAreKeyPackets()||e.randomAccessIndicator===1?`key`:`delta`,new Ag(n.metadataOnly?kg:e.data,r,e.pts/vv,Math.max(t/vv,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;I(t);let n=Av(this.elementaryStream.demuxer,t,!0);I(n);let r=new Fv(this.elementaryStream,n),i=new Iv(this,r),a=await i.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,i),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){let r=await n.readNext();if(!r)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(i,n),this.packetSectionStarts.set(i,r.packet.sectionStartPos),i}let r=this.packetSectionStarts.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);let i=this.elementaryStream.demuxer,a=await i.readSection(r,!0);I(a);let o=Av(i,a,!0);I(o);let s=new Fv(this.elementaryStream,o);n=new Iv(this,s);let c=e.sequenceNumber;for(;;){let e=await n.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){let r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,n),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type===`key`)return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){let r=Lp(e*vv),i=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=i,s=this.elementaryStream.pid,c=async(e,t,n)=>{let r=e;for(;r<t;){let e=await i.readPacketHeader(r);if(!e)return null;if(e.pid===s&&e.payloadUnitStartIndicator===1){let e=await i.readSection(r,n);if(!e)return null;let t=kv(i,e,!1);if(t&&t.pts!==null)return{pesPacketHeader:t,section:e}}r+=i.packetStride}return null},l=this.elementaryStream.firstSection;I(l);let u=kv(i,l,!0);if(I(u),r<u.pts)return null;let d,f=this.elementaryStream.referencePesPackets,p=Op(f,r,e=>e.pts),m=p===-1?null:f[p];if(m&&r-m.pts<45e3)d=m.sectionStartPos;else{let e=0;if(a.fileSize!==null){let t=Math.ceil(a.fileSize/o);if(t>1){let n=0,a=t-1;for(e=n;n<=a;){let t=Math.floor((n+a)/2),s=Bp(t*o,i.packetStride)+u.sectionStartPos,l=await c(s,s+o,!1);if(!l){a=t-1;continue}l.pesPacketHeader.pts<=r?(e=t,n=t+1):a=t-1}}}d=Bp(e*o,i.packetStride)+u.sectionStartPos}let h=(await c(d,a.fileSize??1/0,!1))?.pesPacketHeader??null;h||=u;let g=this.getReorderSize(),_=async(e,t)=>{let a=await i.readSection(e,!0);I(a);let o=Av(i,a,!0);I(o);let s=new Fv(this.elementaryStream,o),c=new Iv(this,s);for(;!((tp(c.presentationOrderPackets)?.pts??-1/0)>=r||!await c.readNextPacket()););let l=Mp(c.presentationOrderPackets,t);if(l===-1)return null;let u=c.presentationOrderPackets[l],d=l===0?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=d;let f=await c.readNext();I(f);let p=this.createEncodedPacket(f.packet,f.duration,n);return this.packetBuffers.set(p,c),this.packetSectionStarts.set(p,f.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){outer:for(;;){let e=h.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=kv(i,t,!1);if(e&&e.pts!==null){if(e.pts>r)break outer;h=e,Pv(this.elementaryStream,h);break}}}e+=i.packetStride}}outer:for(let e=0;e<g+1;e++){let e=h.sectionStartPos-i.packetStride;for(;e>=i.packetOffset;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=kv(i,t,!1);if(e&&e.pts!==null){h=e;break}}}e-=i.packetStride}}return _(h.sectionStartPos,e=>e.pts<=r)}{let e=d,t=null,n=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let d=null,f=e<=u.sectionStartPos,p,m=null;if(f)p=u,m=l;else{let t=await c(e,a.fileSize??1/0,n);p=t?.pesPacketHeader??null,m=t?.section??null}let h=!1,v=0;outer:for(;p&&!(t!==null&&p.sectionStartPos>=t);){if(p.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=p.randomAccessIndicator===1;else{I(m);let t=Av(i,m,!0);I(t);let n=new Fv(this.elementaryStream,t);await n.markNextPacket(),e=n.suppliedPacket?.randomAccessIndicator===1}e&&(d=p)}if(p.pts>r&&(h=!0),h&&(v++,v>g))break;let e=p.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,n);if(t){let e=kv(i,t,!1);if(e&&e.pts!==null){p=e,m=t,Pv(this.elementaryStream,p);break}}}e+=i.packetStride}}if(d){let e=d;if(v===0)outer:for(let t=0;t<g;t++){let t=e.sectionStartPos-i.packetStride;for(;t>=i.packetOffset;){let r=await i.readPacketHeader(t);if(!r)break outer;if(r.pid===s&&r.payloadUnitStartIndicator===1){let r=await i.readSection(t,n);if(r){let t=kv(i,r,!1);if(t&&t.pts!==null){e=t;break}}}t-=i.packetStride}}let t=await _(e.sectionStartPos,e=>e.pts<=r&&e.randomAccessIndicator===1);return I(t),t}if(f)return null;t=e,e=Math.max(Bp(e-u.sectionStartPos-o,i.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}},Mv=class extends jv{getType(){return`video`}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getTransformationMatrix(){return[...qf]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return I(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Nv=class extends jv{getType(){return`audio`}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return I(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},Pv=(e,t)=>{let n=e.referencePesPackets,r=Op(n,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){let i=n[r];if(t.pts<=i.pts)return!1;let a=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-i.sectionStartPos<a)return!1;if(r<n.length-1){let e=n[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<a)return!1}}return n.splice(r+1,0,t),!0},Fv=class{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return I(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let t=tp(this.pesPackets).sectionEndPos;for(I(t!==null);;){let n=await this.demuxer.readPacketHeader(t);if(!n)return;if(n.pid===this.pid){let n=await this.demuxer.readSection(t,!0);if(!n)return;let r=Av(this.demuxer,n,!1);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,r=n+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(n,r);let i=new Uint8Array(e);i.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),n=e-a;if(n<=t.data.byteLength){i.set(t.data.subarray(0,n),a);break}i.set(t.data,a),a+=t.data.byteLength}return i}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){let t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){I(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type===`video`){let t=e.info.codec,n=1024;if(t!==`avc`&&t!==`hevc`)throw Error(`Unhandled.`);let r=t===`avc`?1:2,i=null,a=!1,o=0;for(;;){let e=this.ensureBuffered(n);if(R(e)&&(e=await e),e===0)break;let s=this.currentPos,c=this.readBytes(e),l=c.byteLength,u=0;for(;u<l;){let e=c.indexOf(0,u);if(e===-1||e>=l)break;u=e;let n=s+u;if(u+3>=l){this.seekTo(n);break}let d=c[u+1],f=c[u+2],p=c[u+3],m=0;if(d===0&&f===0&&p===1?m=4:d===0&&f===1&&(m=3),m===0){u++;continue}let h=n;i??=h;let g=u+m,_=g+r;if(_+(t===`avc`?6:1)>l){this.seekTo(n);break}let v=c[g],y,b,x;if(t===`avc`)y=Pm(v),b=y===km.NON_IDR_SLICE||y===km.SLICE_DPA||y===km.IDR,x=y===km.SEI||y===km.SPS||y===km.PPS||y===km.AUD;else{if(y=Wm(v),((v&1)<<5|c[g+1]>>3)>0){u+=m;continue}b=y<=Am.RASL_R||y>=Am.BLA_W_LP&&y<=21,x=y>=Am.VPS_NUT&&y<=37||y===Am.PREFIX_SEI_NUT||y>=41&&y<=44||y>=48&&y<=55}let S=!1;if(b){let e;if(t===`avc`){let t=L(new _m(c.subarray(_,_+6)));e=!a||t<=o,o=t}else e=c[_]>>7==1;e&&(a?S=!0:a=!0)}else x&&a&&(S=!0);if(S){let e=h-i;return this.seekTo(i),this.supplyPacket(e,0)}u+=m}if(e<n)break}if(i!==null&&this.endPos>i){let e=this.endPos-i;return this.seekTo(i),this.supplyPacket(e,0)}}else{let t=e.info.codec;for(;;){let n=this.ensureBuffered(128);R(n)&&(n=await n);let r=this.currentPos;for(;this.currentPos-r<n;){let n=this.readU8();if(t===`aac`){if(n!==255)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(9);if(R(r)&&(r=await r),r<9)return;let i=this.readBytes(9),a=ov(ab.tempFromBytes(i));if(a){this.seekTo(t);let n=this.ensureBuffered(a.frameLength);return R(n)&&(n=await n),this.supplyPacket(n,Math.round(sv*vv/e.info.sampleRate))}this.seekTo(t+1)}else if(t===`mp3`){if(n!==255)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(4);if(R(r)&&(r=await r),r<4)return;let i=wg(op(this.readBytes(4)).getUint32(0),null);if(i.header){this.seekTo(t);let n=this.ensureBuffered(i.header.totalSize);R(n)&&(n=await n);let r=i.header.audioSamplesInFrame*vv/e.info.sampleRate;return this.supplyPacket(n,Math.round(r))}this.seekTo(t+1)}else if(t===`ac3`){if(n!==11)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(5);if(R(r)&&(r=await r),r<5)return;let i=this.readBytes(5);if(i[0]!==11||i[1]!==119){this.seekTo(t+1);continue}let a=i[4]>>6,o=i[4]&63;if(a===3||o>37){this.seekTo(t+1);continue}let s=yh[3*o+a];I(s!==void 0),this.seekTo(t),r=this.ensureBuffered(s),R(r)&&(r=await r);let c=Math.round(bh*vv/e.info.sampleRate);return this.supplyPacket(r,c)}else if(t===`eac3`){if(n!==11)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(5);if(R(r)&&(r=await r),r<5)return;let i=this.readBytes(5);if(i[0]!==11||i[1]!==119){this.seekTo(t+1);continue}let a=(((i[2]&7)<<8|i[3])+1)*2,o=xh[i[4]>>6==3?3:i[4]>>4&3];this.seekTo(t),r=this.ensureBuffered(a),R(r)&&(r=await r);let s=o*256,c=Math.round(s*vv/e.info.sampleRate);return this.supplyPacket(r,c)}else if(t===`dts`){if(n!==127&&n!==100)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(18);if(R(r)&&(r=await r),r<18)return;let i=this.readBytes(18),a=Bh(i),o=a?null:Vh(i);if(!a&&!o){this.seekTo(t+1);continue}if(o&&!o.asset){this.seekTo(t);let e=Math.min(o.frameSize,Eh),n=this.ensureBuffered(e);R(n)&&(n=await n),o=Vh(this.readBytes(n))??o}let s=a?a.frameSize:o.frameSize;if(a){let e=Math.ceil(a.frameSize/4)*4;for(;;){this.seekTo(t);let n=e+10,r=this.ensureBuffered(n);if(R(r)&&(r=await r),r<n)break;this.seekTo(t+e);let i=Vh(this.readBytes(10));if(!i)break;e+=i.frameSize,s=e}}let c=a?.sampleCount??o.asset?.sampleCount;if(c===void 0){this.seekTo(t+1);continue}this.seekTo(t),r=this.ensureBuffered(s),R(r)&&(r=await r);let l=Math.round(c*vv/e.info.sampleRate);return this.supplyPacket(r,l)}else throw Error(`Unhandled.`)}if(n<128)break}}}supplyPacket(e,t){let n=this.getCurrentPesPacket(),r;if(this.lastSuppliedPesPacket===n)I(this.nextPts!==null),r=this.nextPts;else{if(n.pts===null)throw Error(xv);r=n.pts,Pv(this.elementaryStream,n)}this.lastSuppliedPesPacket=n,this.nextPts=r+t;let i=n.sectionStartPos,a=i+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),s=n.randomAccessIndicator;if(s===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type===`audio`)s=1;else if(this.elementaryStream.info.decoderConfig){let e=mh(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)===`key`;s=Number(e)}}this.suppliedPacket={pts:r,data:o,sequenceNumber:a,sectionStartPos:i,randomAccessIndicator:s},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Iv=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),I(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);I(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(I(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer[e];this.presentationOrderPackets.push(t),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}},Lv=`application/vnd.apple.mpegurl`,Rv=`#EXT-X-STREAM-INF:`,zv=`#EXT-X-I-FRAME-STREAM-INF:`,Bv=`#EXT-X-MEDIA:`,Vv=`#EXTINF:`,Hv=`#EXT-X-MAP:`,Uv=`#EXT-X-KEY:`,Wv=`#EXT-X-MEDIA-SEQUENCE:`,Gv=`#EXT-X-BYTERANGE:`,Kv=`#EXT-X-PROGRAM-DATE-TIME:`,qv=`#EXT-X-TARGETDURATION:`,Jv=e=>e.length===0||e.startsWith(`#`)&&!e.startsWith(`#EXT`),Yv=class{constructor(e){this._attributes={};let t=``,n=``,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];o===`"`?i=!i:o===`=`&&!r&&!i?r=!0:o===`,`&&!i?(t&&(this._attributes[t.trim().toLowerCase()]=n),t=``,n=``,r=!1):r?n+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=n)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}},Xv=class{constructor(e,t,n){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=/* @__PURE__ */ new WeakMap,this.firstTimestampCache=/* @__PURE__ */ new WeakMap,this.input=e,this.path=t,this.trackDeclarations=n}async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(t??=await this.getFirstSegment({}),!t||t.unixEpochTimestamp===null)return null;let n=e-t.timestamp;return t.unixEpochTimestamp+n}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type===`video`){let n=rm(e,e=>e.getType()===`video`)+1;e.push(new Qv(this,t,n))}else if(t.type===`audio`){let n=rm(e,e=>e.getType()===`audio`)+1;e.push(new $v(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let t=await this.getInputForSegment(this.firstSegment).getTracks();for(let n of t)if(n.type===`video`){let t=rm(e,e=>e.getType()===`video`)+1;e.push(new Qv(this,{id:e.length+1,type:`video`},t))}else if(n.type===`audio`){let t=rm(e,e=>e.getType()===`audio`)+1;e.push(new $v(this,{id:e.length+1,type:`audio`},t))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(t!==void 0)return t;let n=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,n),n}async getMediaOffset(e,t){let n=e.firstSegment??e,r;if(this.firstSegmentFirstTimestamps.has(n))r=this.firstSegmentFirstTimestamps.get(n);else{let e=this.getInputForSegment(n);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(n,r)}if(n===e)return n.timestamp-r;let i=await this.getFirstTimestampForInput(t),a=e.timestamp-n.timestamp,o=i-r-a;return Math.abs(o)<=Math.min(.25,a)?n.timestamp-r:e.timestamp-i}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}},Zv=class{constructor(e,t,n){this.packetInfos=/* @__PURE__ */ new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw Error(`Missing first segment, can't retrieve track.`);let e=this.segmentedInput.firstSegment,t=null;for(;e&&(t=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,!t);)e=await this.segmentedInput.getNextSegment(e,{});if(!t)throw Error(`No matching track found in underlying media data.`);this.firstInputTrack=t,this.firstSegment=e})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),I(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,n){I(e.sequenceNumber>=0),I(this.segmentedInput.firstSegment);let r=await this.segmentedInput.getMediaOffset(t,n.input),i=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:zp(e.timestamp+r,await n.getTimeResolution()),sequenceNumber:Math.floor(1e8*i)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:n,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),I(this.firstInputTrack),I(this.firstSegment);let t=this.firstInputTrack,n=this.firstSegment;for(;;){if(t){let r=await t._backing.getFirstPacket(e);if(r)return this.createAdjustedPacket(r,n,t)}if(n=await this.segmentedInput.getNextSegment(n,{skipLiveWait:e.skipLiveWait}),!n)break;t=(await this.segmentedInput.getInputForSegment(n).getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,n){let r=this.packetInfos.get(e);if(!r)throw Error(`Packet was not created from this track.`);let i=n?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(i)return this.createAdjustedPacket(i,r.segment,r.track);let a=r.segment;for(;;){let e=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!e)return null;let n=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){a=e;continue}let i=await n._backing.getFirstPacket(t);return i?this.createAdjustedPacket(i,e,n):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,n){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){let i=this.segmentedInput.getInputForSegment(r),a=(await i.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!a){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}let o=e-await this.segmentedInput.getMediaOffset(r,i),s=n?await a._backing.getKeyPacket(o,t):await a._backing.getPacket(o,t);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(s,r,a)}return null}},Qv=class extends Zv{getType(){return`video`}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getTransformationMatrix(){return this.delegate(()=>this.firstInputTrack._backing.getTransformationMatrix())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},$v=class extends Zv{getType(){return`audio`}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}};(/* @__PURE__ */ e(((e,t)=>{t.exports={}})))(),em();var ey=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var ty=class extends cm{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<`u`&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new rb;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,ey),e=this._getFileSize(),I(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new rb;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw TypeError(`length, when provided, must be a non-negative integer.`);return new cy(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new ny(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},ny=class{constructor(e){if(this._freed=!1,e._disposed)throw Error(`Cannot ref a disposed source.`);e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error(`Can't get source; ref has already been freed.`);return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error(`Illegal operation: double free on SourceRef.`);let e=this.source;I(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},ry=class extends ty{constructor(e,t){if(typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`requestHandler must be a function.`);super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=e=>{if(!(e instanceof ty||e instanceof ny))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof ty?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return R(t)?t.then(n):n(t)}},iy=(e,t)=>e.path===t.path,ay=class extends ry{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,n,r){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{let t=e instanceof ty?e.ref():e;return this._root=t,this._rootRequest=null,t};R(e)?this._rootRequest=e.then(t):(t(e),I(this._root))}if(this._rootRequest)return this._rootRequest.then(i=>i.source._read(e,t,n,r))}return this._root.source._read(e,t,n,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},oy=class extends ty{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=ap(e),this._view=op(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}};typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e.cancel().catch(()=>{})});var sy=class extends ty{constructor(e,t={}){if(!(e instanceof ReadableStream))throw TypeError(`stream must be a ReadableStream.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);if(t.maxCacheSize!==void 0&&(!tm(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._cacheMissErrorMessage=`Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.`,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20,this._handleUnhandledError=t.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let n=Op(this._cache,e,e=>e.start),r=n===-1?null:this._cache[n];if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let i=e,a=new Uint8Array(t-e);if(n!==-1)for(let r=n;r<this._cache.length;r++){let n=this._cache[r];if(n.start>=t)break;let o=Math.max(e,n.start);o>i&&this._throwDueToCacheMiss();let s=Math.min(t,n.end);o<s&&(a.set(n.bytes.subarray(o-n.start,s-n.start),o-e),i=s)}if(i===t)return{bytes:a,view:op(a),offset:e};this._currentIndex>i&&this._throwDueToCacheMiss();let{promise:o,resolve:s,reject:c}=kp();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:s,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(e);else throw e})),o}_throwDueToCacheMiss(){throw Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,r=this._currentIndex+t.byteLength;this._dispatchRead(n,r);for(let e=0;e<this._pendingSlices.length;e++){let i=this._pendingSlices[e],a=Math.max(n,i.start),o=Math.min(r,i.end);a<o&&(i.bytes.set(t.subarray(a-n,o-n),a-i.start),o===i.end&&(i.resolve({bytes:i.bytes,view:op(i.bytes),offset:i.start}),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:n,end:r,bytes:t,view:op(t),age:0});this._cache.length>0;){let e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(let e of this._pendingSlices)e.reject(new rb);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},cy=class extends ty{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw Error(`Cannot create a slice of a disposed source.`);this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length===null?void 0:this._length:e===null?this._length===null?null:this._length:Ip(e-this._offset,0,this._length??1/0)}_read(e,t,n,r){if(this._length!==null&&t>this._length)return null;let i=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+r),a=e=>e?(e.offset-=this._offset,e):null;return R(i)?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},ly=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},uy=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r}),dy=/^0[xX][0-9a-fA-F]+$/,fy=/^data:.*;base64,/i,py=class extends Xv{constructor(e,t,n,r){super(e.input,t,n),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await om(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){let t={stack:[],error:void 0,hasError:!1};try{let n=ly(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=await new ib(n.source).requestEntireFile();I(r),e=Sb(r,r.length,{ignore:Jv}),n.source instanceof ry&&(this.rootPath=n.source.rootPath)}catch(e){t.error=e,t.hasError=!0}finally{uy(t)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=!1,r=0,i=null,a=null,o=null,s=0,c=null,l=null,u=null,d=null,f=null,p=null,m=!1,h=tp(this.segments)??null,g=e=>{let t=e.indexOf(`@`),n=Number(t===-1?e:e.slice(0,t));if(!Number.isInteger(n)||n<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(t!==-1&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:n,offset:r}},_=e=>{s=e,h&&(I(h.sequenceNumber!==null),h.sequenceNumber<e&&(r=h.timestamp+h.duration,c=h.firstSegment,l=h.initSegment,f=h.lastProgramDateTimeSeconds,i=h.unixEpochTimestamp===null?null:h.unixEpochTimestamp+h.duration,h=null))};for(let v=0;v<e.length;v++){let y=e[v];if(!n){if(y!==`#EXTM3U`)throw Error(`Invalid M3U8 file; expected first line to be #EXTM3U.`);n=!0;continue}if(!y.startsWith(`#`)){if(!h){if(a===null)throw Error(`Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.`);let e=o;if(e&&e.method===`AES-128`&&!e.iv){let t=/* @__PURE__ */ new Uint8Array(16),n=op(t);n.setUint32(8,Math.floor(s/2**32)),n.setUint32(12,s),e={...e,iv:t}}let t={path:nm(this.rootPath,y),offset:d?.offset??0,length:d?.length??null},n={timestamp:r,unixEpochTimestamp:i,firstSegment:c,sequenceNumber:s,location:t,duration:a,encryption:e,initSegment:l,lastProgramDateTimeSeconds:f};c??=n,r+=a,i!==null&&(i+=a),this.segments.push(n)}a=null,d===null?u=null:d=null,_(s+1)}if(y.startsWith(`#EXTINF:`)){if(h){m=!0;continue}m||=(f===null&&s>0&&p!==null&&(r=s*p),!0);let e=y.slice(Vv.length),t=e.indexOf(`,`),n=t===-1?e:e.slice(0,t),i=Number(n);if(!Number.isFinite(i)||i<0)throw Error(`Invalid #EXTINF tag duration '${n}'.`);a=i}else if(y.startsWith(`#EXT-X-MAP:`)){let e=new Yv(y.slice(Hv.length)),t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-MAP tag; missing URI attribute.`);let n=e.get(`byterange`),s=null;if(n!==null&&(s=g(n)),s&&s.offset===null)throw Error(`Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.`);if(!h){let e={path:nm(this.rootPath,t),offset:s?.offset??0,length:s?.length??null};if(o?.method===`AES-128`&&!o.iv)throw Error(`IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.`);l={timestamp:r,unixEpochTimestamp:i,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:f}}a=null,d===null?u=null:d=null}else if(y.startsWith(`#EXT-X-KEY:`)){let e=new Yv(y.slice(Uv.length)),t=e.get(`method`);if(t===`NONE`)o=null;else if(t===`AES-128`){let t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-KEY: AES-128 requires a URI attribute.`);let n=null,r=e.get(`iv`);if(r){if(!dy.test(r))throw Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,`0`),e=e.slice(-32),n=/* @__PURE__ */ new Uint8Array(16);for(let t=0;t<16;t++){let r=2*t;n[t]=parseInt(e.slice(r,r+2),16)}}let i=e.get(`keyformat`)??`identity`;if(i!==`identity`)throw Error(`For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.`);o={method:`AES-128`,keyUri:nm(this.rootPath,t),iv:n,keyFormat:i}}else if(t===`SAMPLE-AES`||t===`SAMPLE-AES-CTR`){let n=e.get(`uri`);if(!n)throw Error(`Invalid #EXT-X-KEY: ${t} requires a URI attribute.`);if((e.get(`keyformat`)??`identity`)===`identity`)throw Error(`For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.`);let r=null;if(fy.test(n)){let e=n.indexOf(`,`),t=Qp(n.slice(e+1));if(t.length>=8&&t[4]===112&&t[5]===115&&t[6]===115&&t[7]===104){let e=op(t).getUint32(0);r=Mg(t.subarray(8,Math.min(e,t.length)))}}o={method:t,psshBox:r}}else throw Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`)}else if(y.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)){let e=y.slice(Wv.length),t=Number(e);if(!Number.isInteger(t)||t<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);_(t)}else if(y.startsWith(`#EXT-X-BYTERANGE:`)){let e=g(y.slice(Gv.length));if(e.offset===null){if(u===null)throw Error(`Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.`);e.offset=u}d=e,u=e.offset+e.length}else if(y.startsWith(`#EXT-X-PROGRAM-DATE-TIME:`)){if(h)continue;let e=y.slice(Kv.length),n=Date.parse(e);if(!Number.isFinite(n))continue;let a=n/1e3;if(f===a)continue;if(f===null&&this.segments.length>0){let e=tp(this.segments),n=a-(e.timestamp+e.duration);for(let e of this.segments)e.unixEpochTimestamp=e.timestamp+n,t&&(e.timestamp=e.unixEpochTimestamp)}f=a,i=a,t&&(r=a)}else if(y===`#EXT-X-DISCONTINUITY`)c=null;else if(y.startsWith(`#EXT-X-TARGETDURATION:`)){let e=y.slice(qv.length),t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,p=t}else if(y===`#EXT-X-ENDLIST`){this.streamHasEnded=!0;break}else y.startsWith(`#EXT-X-PLAYLIST-TYPE:`)&&y.slice(21).toLowerCase()===`vod`&&(this.streamHasEnded=!0)}if(!n)throw Error(`Invalid M3U8 file; no #EXTM3U header.`)}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let r=Op(this.segments,e,e=>e.timestamp);if(r===-1)return null;if(r<this.segments.length-1||this.streamHasEnded||n)return this.segments[r];let i=this.segments[r];if(e<i.timestamp+i.duration)return i;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,t){let n=this.segments.indexOf(e);I(n!==-1);let r=n+1,i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(r<this.segments.length)return this.segments[r];if(this.streamHasEnded||i)return null;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return I(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,n=this.inputCache.find(e=>e.segment===t);if(n)return n.age=this.nextInputCacheAge++,n.input;let r=null;(t.initSegment||t.firstSegment)&&(r=this.getInputForSegment(t.initSegment??t.firstSegment));let i={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||t.encryption.method!==`SAMPLE-AES`&&t.encryption.method!==`SAMPLE-AES-CTR`||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let n=e.psshBoxes,{psshBox:r}=t.encryption;return(r.keyIds===null||r.keyIds.includes(e.keyId))&&!n.some(e=>Ng(e,r))&&(n=[...n,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:n})})}},a=new tb({source:new ay(t.location.path,async e=>{I(e.isRoot);let n={...e,isRoot:!1},r,i=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method===`SAMPLE-AES`||t.encryption.method===`SAMPLE-AES-CTR`){if(r=await this.input._getSourceCached(n),i){let e=r.source.slice(t.location.offset,t.location.length??void 0).ref();r.free(),r=e}}else if(t.encryption.method===`AES-128`){let e=t.encryption;I(e.iv);let a=await this.input._getSourceCached(n);if(i){let e=a.source.slice(t.location.offset,t.location.length??void 0).ref();a.free(),a=e}r=new sy(Xg(new ib(a.source),async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new ib(ly(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},2),!1).source).requestSlice(0,16);if(!n)throw Error(`Invalid AES-128 key; expected at least 16 bytes of data.`);return{key:V(n,16),iv:e.iv}}catch(e){t.error=e,t.hasError=!0}finally{uy(t)}},()=>{a.free()})).ref()}else I(!1);return r}),formats:this.input._formats.filter(e=>!(e instanceof Ny)),initInput:r??void 0,formatOptions:i});if(a._onFormatDetermined=e=>{if((t.encryption?.method===`SAMPLE-AES`||t.encryption?.method===`SAMPLE-AES-CTR`)&&!e._isIsobmff)throw Error(`The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.`)},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){let e=im(this.inputCache,e=>e.age);I(e!==-1),this.inputCache.splice(e,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}},my=class extends Og{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{I(this.input._rootSource instanceof ry);let e=await this.input._reader.requestEntireFile();I(e);let t=Sb(e,e.length,{ignore:Jv}),{rootPath:n}=this.input._rootSource,r=[],i=[];for(let e=1;e<t.length;e++){let a=t[e];if(a.startsWith(`#EXT-X-STREAM-INF:`)){let i=e,o=t[++e];if(o===void 0)throw Error(`Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.`);let s=nm(n,o),c=new Yv(a.slice(Rv.length));if(c.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);r.push({fullPath:s,attributes:c,lineNumber:i,hasOnlyKeyPackets:!1})}else if(a.startsWith(`#EXT-X-I-FRAME-STREAM-INF:`)){let t=new Yv(a.slice(zv.length)),i=t.get(`uri`);if(i===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.`);if(t.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);let o=nm(n,i);r.push({fullPath:o,attributes:t,lineNumber:e,hasOnlyKeyPackets:!0})}else if(a.startsWith(`#EXT-X-MEDIA:`)){let t=new Yv(a.slice(Bv.length));if(t.get(`type`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.`);if(t.get(`group-id`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.`);let r=null,o=t.get(`uri`);o!==null&&(r=nm(n,o)),i.push({fullPath:r,attributes:t,lineNumber:e})}else if(a!==`#EXT-X-I-FRAMES-ONLY`&&a.startsWith(`#EXTINF:`)){let e=new py(this,n,null,t);this.segmentedInputs=[e],this.hasMasterPlaylist=!1,this.trackBackings=await e.getTrackBackings();return}}let a=[...new Set(i.filter(e=>e.attributes.get(`type`).toLowerCase()===`video`).map(e=>e.attributes.get(`group-id`)))],o=[...new Set(i.filter(e=>e.attributes.get(`type`).toLowerCase()===`audio`).map(e=>e.attributes.get(`group-id`)))],s=await Promise.all(r.map(async(e,t)=>{let r=[],s=e.attributes.get(`codecs`),c;if(s)c=s.split(`,`).map(e=>e.trim());else{let t=await this.getSegmentedInputForPath(e.fullPath).getTrackBackings(),n=await Promise.all(t.map(async e=>({track:e,codec:await e.getCodec()})));c=await Promise.all(n.filter(e=>e.codec!==null).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let l=e.attributes.get(`video`),u=e.attributes.get(`audio`),d=c.some(e=>Gh.includes(lg(e))),f=c.some(e=>Jh.includes(lg(e)));if(l!==null&&!d){if(!a.includes(l))throw Error(`Invalid M3U8 file; variant stream references video group "${l}" which is not defined in any #EXT-X-MEDIA tags.`);let e=i.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===l&&n.toLowerCase()===`video`});outer:if(e){let t=e.attributes.get(`uri`);if(t===null)break outer;let r=nm(n,t),i=(await this.getSegmentedInputForPath(r).getTrackBackings()).find(e=>e.getType()===`video`);if(!i||await i.getCodec()===null)break outer;let a=await i.getDecoderConfig().then(e=>e?.codec??null);I(a!==null),c.push(a)}}if(u!==null&&!f){if(!o.includes(u))throw Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);let e=i.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===u&&n.toLowerCase()===`audio`});outer:if(e){let t=e.attributes.get(`uri`);if(t===null)break outer;let r=nm(n,t),i=(await this.getSegmentedInputForPath(r).getTrackBackings()).find(e=>e.getType()===`audio`);if(!i||await i.getCodec()===null)break outer;let a=await i.getDecoderConfig().then(e=>e?.codec??null);I(a!==null),c.push(a)}}c=[...new Set(c)];let p=null,m=null,h=e.attributes.getAsNumber(`bandwidth`);I(h!==null);let g=e.attributes.getAsNumber(`average-bandwidth`),_=e.attributes.get(`name`);for(let n of c){let s=lg(n);if(s!==null){if(Gh.includes(s)){if(p!==null)throw Error(`Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.`);p=n;let o=e.attributes.get(`video`);if(o===null){let n=e.attributes.get(`resolution`),i=null,a=null;if(n){let e=n.match(/^(\d+)x(\d+)$/);e&&(i=Number(e[1]),a=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:h,averageBitrate:g,name:_,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:i,height:a}})}else{if(!a.includes(o))throw Error(`Invalid M3U8 file; variant stream references video group "${o}" which is not defined in any #EXT-X-MEDIA tags.`);for(let n of i){let i=n.attributes.get(`group-id`),a=n.attributes.get(`type`);if(i!==o||a.toLowerCase()!==`video`)continue;let s=n.attributes.get(`resolution`)??e.attributes.get(`resolution`),c=null,l=null;if(s){let e=s.match(/^(\d+)x(\d+)$/);e&&(c=Number(e[1]),l=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:vy(n.attributes),autoselect:vy(n.attributes)||yy(n.attributes),languageCode:by(n.attributes.get(`language`)),lineNumber:n.lineNumber,fullPath:n.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:n.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:c,height:l}})}}}else if(Jh.includes(s)){if(m!==null)throw Error(`Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.`);m=n;let a=e.attributes.get(`audio`);if(a===null){let n=e.attributes.get(`channels`),i=n===null?null:Number(n.split(`/`)[0]);r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(t),peakBitrate:h,averageBitrate:g,name:_,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:i!==null&&Number.isInteger(i)&&i>0?i:null}})}else{if(!o.includes(a))throw Error(`Invalid M3U8 file; variant stream references audio group "${a}" which is not defined in any #EXT-X-MEDIA tags.`);for(let n of i){let i=n.attributes.get(`group-id`),o=n.attributes.get(`type`);if(i!==a||o.toLowerCase()!==`audio`)continue;let s=n.attributes.get(`channels`)??e.attributes.get(`channels`),c=s===null?null:Number(s.split(`/`)[0]);r.push({id:-1,demuxer:this,backingTrack:null,default:vy(n.attributes),autoselect:vy(n.attributes)||yy(n.attributes),languageCode:by(n.attributes.get(`language`)),lineNumber:n.lineNumber,fullPath:n.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:n.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:c!==null&&Number.isInteger(c)&&c>0?c:null}})}}}}}return r})),c=[],l=e=>{let t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||=e.default,t.autoselect||=e.autoselect,t.lineNumber=Math.min(t.lineNumber,e.lineNumber),e.peakBitrate!==null&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),e.averageBitrate!==null&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===`und`&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(let e of s)for(let t of e)l(t);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(let e of c)e.info.type===`video`?this.trackBackings.push(new gy(e)):this.trackBackings.push(new _y(e));this.internalTracks=c})()}async getTrackBackings(){return await this.readMetadata(),I(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))),t=new py(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Lv}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},hy=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,n=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(n.length===1)t=n[0];else if(this instanceof gy){for(let e of n)if(await e.getCodec()===this.getCodec()){t=e;break}}else{I(this instanceof _y);for(let e of n)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw Error(`Could not find matching track in underlying media data.`);this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw Error(`Not implemented on base class.`)}getDisposition(){return{...hm,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){I(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},gy=class extends hy{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return lg(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},_y=class extends hy{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return lg(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels===null?this.delegate(()=>this.backingAudioTrack.getNumberOfChannels()):this.internalTrack.info.numberOfChannels}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},vy=e=>{let t=e.get(`default`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},yy=e=>{let t=e.get(`autoselect`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},by=e=>e===null?`und`:e.split(`-`)[0]||`und`,xy=class{constructor(){this._isIsobmff=!1}},Sy=class extends xy{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(R(t)&&(t=await t),!t)return null;t.skip(4);let n=xb(t,4);return n!==`ftyp`&&n!==`styp`?null:xb(t,4)}_createDemuxer(e){return new Zg(e)}},Cy=class extends Sy{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!==`qt `;let n=0;for(let t=0;t<10;t++){let t=e._reader.requestSlice(n,8);if(R(t)&&(t=await t),!t)return!1;let r=U(t),i=8;if(r===1){let t=e._reader.requestSlice(n+8,8);if(R(t)&&(t=await t),!t)return!1;r=gb(t),i=16}if(r<i)return!1;let a=xb(t,4);if(a===`moof`||a===`sidx`)return!0;if(a===`emsg`||a===`prft`||a===`free`)n+=r;else return!1}return!1}get name(){return`MP4`}get mimeType(){return`video/mp4`}},wy=class extends Sy{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},Ty=class extends xy{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(R(n)&&(n=await n),!n)return!1;let r=v_(n);if(r===null||r<1||r>8||B(n,r)!==z.EBML)return!1;let i=S_(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(R(a)&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=C_(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case z.EBMLVersion:if(B(a,r)!==1)return!1;break;case z.EBMLReadVersion:if(B(a,r)!==1)return!1;break;case z.DocType:if(w_(a,r)!==t)return!1;break;case z.DocTypeVersion:if(B(a,r)>4)return!1}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new L_(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},Ey=class extends Ty{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},Dy=class extends xy{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(R(n)&&(n=await n),!n)break;let r=Ob(n);if(!r)break;t=n.filePos+r.size}let n=await V_(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=Cg(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(R(a)&&(a=await a),!a)return!1;let o=U(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await V_(e._reader,t,t+4);if(!s)return!1;let c=s.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new H_(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},Oy=class extends xy{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(R(t)&&(t=await t),!t)return!1;let n=xb(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),xb(t,4)===`WAVE`)}_createDemuxer(e){return new rv(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},ky=class extends xy{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return R(t)&&(t=await t),t?xb(t,4)===`OggS`:!1}_createDemuxer(e){return new Q_(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},Ay=class extends xy{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(R(n)&&(n=await n),!n)break;let r=Ob(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSlice(t,4);return R(n)&&(n=await n),n?xb(n,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new gv(e)}},jy=class extends xy{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(R(n)&&(n=await n),!n)break;let r=Ob(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSliceRange(t,7,9);if(R(n)&&(n=await n),!n)return!1;let r=ov(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),R(n)&&(n=await n),!n))return!1;let i=ov(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new cv(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},My=class extends xy{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(R(t)&&(t=await t),!t)return!1;let n=V(t,205);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71||n[4]===71&&n[196]===71}_createDemuxer(e){return new Ov(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},Ny=class extends xy{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(R(t)&&(t=await t),!t||xb(t,7)!==`#EXTM3U`)return!1;if(!(e._rootSource instanceof ry))throw TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new my(e)}get name(){return`HTTP Live Streaming (HLS)`}get mimeType(){return Lv}},Py=[/* @__PURE__ */ new Ny,/* @__PURE__ */ new Cy,/* @__PURE__ */ new wy,/* @__PURE__ */ new Ty,/* @__PURE__ */ new Ey,/* @__PURE__ */ new Oy,/* @__PURE__ */ new ky,/* @__PURE__ */ new Ay,/* @__PURE__ */ new Dy,/* @__PURE__ */ new jy,/* @__PURE__ */ new My],Fy=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`${t}, when provided, must be an object.`);if(e.isobmff!==void 0){if(!e.isobmff||typeof e.isobmff!=`object`)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(e.isobmff.resolveKeyId!==void 0&&typeof e.isobmff.resolveKeyId!=`function`)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(e.hls!==void 0){if(!e.hls||typeof e.hls!=`object`)throw TypeError(`${t}.hls, when provided, must be an object.`);if(e.hls.offsetTimestampsByDateTime!==void 0&&typeof e.hls.offsetTimestampsByDateTime!=`boolean`)throw TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}},Iy=[],Ly=[],Ry=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`);if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!=`boolean`)throw TypeError(`options.skipLiveWait, when defined, must be a boolean.`)},zy=e=>{if(!tm(e))throw TypeError(`timestamp must be a number.`)},By=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,Vy=class{constructor(e){if(!(e instanceof Hy))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(Ry(e),this._track.input._disposed)throw new rb;return By(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Ry(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(zy(e),Ry(t),this._track.input._disposed)throw new rb;return By(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Ag))throw TypeError(`packet must be an EncodedPacket.`);if(Ry(t),this._track.input._disposed)throw new rb;return By(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(zy(e),Ry(t),this._track.input._disposed)throw new rb;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(I(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof Ag))throw TypeError(`packet must be an EncodedPacket.`);if(Ry(t),this._track.input._disposed)throw new rb;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(I(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof Ag))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof Ag))throw TypeError(`endPacket must be an EncodedPacket.`);if(Ry(n),this._track.input._disposed)throw new rb;let r=[],{promise:i,resolve:a}=kp(),{promise:o,resolve:s}=kp(),c=!1,l=!1,u=null,d=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>p()){({promise:o,resolve:s}=kp()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=kp(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{d||(u=e,d=!0,a())});let m=this._track;return{async next(){for(;;)if(m.input._disposed)throw new rb;else if(l)return{value:void 0,done:!0};else if(d)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Hy=class e{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Gy}isAudioTrack(){return this instanceof Ky}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Uy(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Uy(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return Uy(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Uy(this._backing.getTimeResolution(),`timeResolution`,`getTimeResolution`)}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Uy(this._backing.getDisposition(),`disposition`,`getDisposition`)}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return zp((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new Vy(this),r=1/0,i=-1/0,a=0,o=0;for await(let s of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&s.timestamp>=i)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,o+=s.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(i-r)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an InputTrack.`);return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Xy({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Xy({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Xy({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Xy({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Xy({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Wy(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Wy(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Wy(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},Uy=(e,t,n)=>{if(R(e))throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},Wy=e=>{if(e!==void 0&&typeof e!=`function`)throw TypeError(`predicate, when provided, must be a function.`);return e?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`predicate must return or resolve to a boolean value.`);return e},r=e(t);return R(r)?r.then(n):n(r)}:void 0},Gy=class extends Hy{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return`video`}async getCodec(){return this._backing.getCodec()}get codec(){return Uy(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()===`prores`}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Uy(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Uy(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Yf(await this._backing.getTransformationMatrix())}get rotation(){return Yf(Uy(this._backing.getTransformationMatrix(),`rotation`,`getRotation`))}async getFlip(){return Xf(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Uy(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Uy(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=am({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=am({num:Uy(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*Uy(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:Uy(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*Uy(this._backing.getCodedWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)})}async getDisplayWidth(){return await this._backing.getMetadataDisplayWidth?.()??(await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let t=Uy(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}return Uy(Yf(Uy(this._backing.getTransformationMatrix(),`displayWidth`,`getDisplayWidth`))%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight(),`displayWidth`,`getDisplayWidth`)}async getDisplayHeight(){return await this._backing.getMetadataDisplayHeight?.()??(await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let t=Uy(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}return Uy(Yf(Uy(this._backing.getTransformationMatrix(),`displayHeight`,`getDisplayHeight`))%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth(),`displayHeight`,`getDisplayHeight`)}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pq`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return I(t!==null),Iy.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return dm._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof Ag))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();if(t===null)return null;let n=await this.getDecoderConfig();return I(n),mh(t,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!tm(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError(`options.targetPacketCount must be a non-negative number.`);let t=await this.getTimeResolution(),n=e.targetPacketCount??256,r=new Vy(this),i=[],a=-1/0,o=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(i.length>=n&&e.timestamp>=a)break;i.push(e.timestamp),a=Math.max(a,e.timestamp),o++}let s=new Float64Array(i.length);for(let e=0;e<i.length;e++)s[e]=Math.round(i[e]*t);s.sort();let c=1;for(let e=1;e<s.length;e++)s[e]!==s[c-1]&&(s[c++]=s[e]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};let l=s.subarray(0,c),u=Qy(l,t),d=u??t,f=u===null?null:t/u,p=/* @__PURE__ */ new Map,m=1/0,h=-1/0,g=0;for(let e=1;e<c;e++){let t=l[e]-l[e-1],n=f===null?t:Math.max(1,Math.round(t/f));p.set(n,(p.get(n)??0)+1),m=Math.min(m,n),h=Math.max(h,n),g+=n}let _=c-1,v=[...p.keys()].sort((e,t)=>e-t),y=_-1>>1,b=_>>1,x=0,S=0,C=0;for(let e of v)if(C+=p.get(e),x===0&&C>y&&(x=e),C>b){S=e;break}let w=(d/x+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:u===null?eb(w):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:w,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},Ky=class extends Hy{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return Uy(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Uy(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Uy(this._backing.getSampleRate(),`sampleRate`,`getSampleRate`)}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return I(t!==null),Ly.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return dm._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof Ag))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}},qy=e=>-(e??-1/0),Jy=e=>-e,Yy=e=>{if(typeof e!=`object`||!e)throw TypeError(`query must be an object.`);if(e.filter!==void 0&&typeof e.filter!=`function`)throw TypeError(`query.filter, when provided, must be a function.`);if(e.sortBy!==void 0&&typeof e.sortBy!=`function`)throw TypeError(`query.sortBy, when provided, must be a function.`);return{filter:e.filter?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`query.filter must return or resolve to a boolean.`);return e},r=e.filter(t);return R(r)?r.then(n):n(r)}:void 0,sortBy:e.sortBy?t=>{let n=e=>{if(typeof e!=`number`&&(!Array.isArray(e)||!e.every(e=>typeof e==`number`)))throw TypeError(`query.sortBy must return or resolve to a number or an array of numbers.`);return e},r=e.sortBy(t);return R(r)?r.then(n):n(r)}:void 0}},Xy=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return R(r)?r.then(i):i(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?n=>{let r=e?.sortBy?.(n)??[],i=t?.sortBy?.(n)??[],a=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return R(r)||R(i)?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),Zy=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>R(e))){let t=await Promise.all(r);n=e.filter((e,n)=>t[n])}else n=e.filter((e,t)=>r[t])}if(!t?.sortBy)return n;let r=n.map(e=>t.sortBy(e)),i=r.some(e=>R(e))?await Promise.all(r):r;return n.map((e,t)=>({track:e,sortValue:i[t]})).sort((e,t)=>{let n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}).map(e=>e.track)},Qy=(e,t)=>{let n=1e6,r=.98,i=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;let o=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let n=e[t]-e[t-1];if(!(n>0))return null;o[t-1]=n}let s=o.slice();s.sort();let c=s[Math.floor(s.length*.05)];for(let e=0;e<6;e++){let e=0,t=0;for(let n of o){let r=Math.max(1,Math.round(n/c));Math.abs(n-r*c)>=i||(e+=n,t+=r)}if(t===0)return null;let n=e/t;if(Math.abs(n-c)<=1e-12*Math.max(1,c)){c=n;break}c=n}let l=0,u=0,d=0;for(let e of o){let t=Math.max(1,Math.round(e/c));Math.abs(e-t*c)>=i||(l++,u+=e,d+=t)}if(l/o.length<r)return null;c=u/d;let f=1/Math.min(d,1e3),p=Math.max(2**-52,c-f),m=c+f,h=t/m,g=t/p,_=t/c,v=null,y=1/0;for(let e of a){if(e<h||e>g)continue;let t=Math.abs(e/_-1);t<y&&(v=e,y=t)}if(v===null){let e=$y(p,m,n),r=$y(h,g,n);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))v=r.num/r.den;else if(e)v=t*e.den/e.num;else return null}let b=t/v,x=0;for(let e of o){let t=Math.max(1,Math.round(e/b));Math.abs(e-t*b)<i&&x++}return x/o.length<r?null:v},$y=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return am({num:n,den:r})}return null},eb=e=>{let t=[24/1.001,30/1.001,60/1.001,120/1.001],n=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(let n of t)if(Math.abs(n/e-1)<=5e-4)return n;let r=e,i=1/0;for(let t of n){let n=Math.abs(t/e-1);n<=.025&&n<i&&(r=t,i=n)}return r};em();var tb=class e extends cm{get disposed(){return this._disposed}constructor(t){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=/* @__PURE__ */ new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof xy)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof ty||t.source instanceof ny))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof ty&&t.source._disposed)throw TypeError(`options.source must not be a disposed Source.`);if(t.initInput!==void 0&&!(t.initInput instanceof e))throw TypeError(`options.initInput, when provided, must be an Input.`);t.formatOptions!==void 0&&Fy(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof ty?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){I(this._rootSource instanceof ry);let t=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){let n=this._sourceCache.find(n=>n.cacheGroup===t&&iy(n.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let r=this._sourceCachePromises.find(n=>n.cacheGroup===t&&iy(n.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());let i=(async()=>{let n=await this._getSourceUncached(e);if(rm(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=im(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1?e.age:1/0);I(e!==-1);let n=this._sourceCache[e];this._sourceCache.splice(e,1),n.sourceRef.free(),Ap(this._sourceRefs,n.sourceRef)}this._sourceRefs.push(n);let r=this._sourceCachePromises.findIndex(t=>t.request===e);return I(r!==-1),this._sourceCachePromises.splice(r,1),{request:e,sourceRef:n,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:i}),i.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new ib(this._rootSource),this._emit(`source`,{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new nb})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),I(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof nb)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(e=>e!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...n.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null);if(n.length===0)return 0;let r=await Promise.all(n.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null),r=(await Promise.all(n.map(e=>e.getDurationFromMetadata(t)))).filter(e=>e!==null);return r.length===0?null:Math.max(...r)}async getTracks(e){return e&&=Yy(e),Zy((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=Yy(e),Zy((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=Yy(e),Zy((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=Yy(e);let t=Xy(e,{sortBy:async e=>[Jy((await e.getDisposition()).default),Jy(await e.hasPairableAudioTrack()),Jy(!await e.hasOnlyKeyPackets()),qy(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=Yy(e);let t=await this.getPrimaryVideoTrack(),n=Xy(e,{sortBy:async e=>[Jy(!t||e.canBePairedWith(t)),Jy((await e.getDisposition()).default),qy(await e.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let n=e.getType()===`video`?new Gy(this,e):new Ky(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},nb=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},rb=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},ib=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw Error(`Reading file size too early; read required first.`);return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new rb;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=/* @__PURE__ */ new Uint8Array;return new ab(t,op(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,ey);return R(r)?r.then(t=>t?new ab(t.bytes,t.view,t.offset,e,n):null):r?new ab(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new rb;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Ip(this.fileSizeNonStrict-e,t,n));{let r=this.requestSlice(e,n),i=r=>r||(I(this.fileSizeNonStrict!==null),this.requestSlice(e,Ip(this.fileSizeNonStrict-e,t,n)));return R(r)?r.then(i):i(r)}}requestEntireFile(){return this.fileSizeNonStrict===null?(async()=>{let e=[],t=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let n=this.requestSliceRange(t,0,1024);if(R(n)&&(n=await n),!n||n.length===0)break;let r=V(n,n.length);e.push(r),t+=n.length}let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new ab(n,op(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},ab=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,op(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},ob=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},V=(e,t)=>{ob(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},H=e=>(ob(e,1),e.view.getUint8(e.bufferPos++)),sb=(e,t)=>{ob(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},cb=e=>{ob(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},lb=e=>{ob(e,3);let t=Pp(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},ub=e=>{ob(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},db=(e,t)=>{ob(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},U=e=>{ob(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},fb=e=>{ob(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},pb=e=>{ob(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},mb=e=>{ob(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},hb=(e,t)=>{let n,r;return t?(n=db(e,!0),r=db(e,!0)):(r=db(e,!1),n=db(e,!1)),r*4294967296+n},gb=e=>{let t=U(e),n=U(e);return t*4294967296+n},_b=e=>{let t=pb(e),n=U(e);return t*4294967296+n},vb=e=>{let t=fb(e);return mb(e)*4294967296+t},yb=e=>{ob(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},bb=e=>{ob(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},xb=(e,t)=>{ob(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},Sb=(e,t,n)=>lp.decode(V(e,t)).split(`
|
|
4
|
-
`).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e)),Cb;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(Cb||={});var wb;(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(wb||={});var Tb=/* @__PURE__ */ `Blues.Classic rock.Country.Dance.Disco.Funk.Grunge.Hip-hop.Jazz.Metal.New age.Oldies.Other.Pop.Rhythm and blues.Rap.Reggae.Rock.Techno.Industrial.Alternative.Ska.Death metal.Pranks.Soundtrack.Euro-techno.Ambient.Trip-hop.Vocal.Jazz & funk.Fusion.Trance.Classical.Instrumental.Acid.House.Game.Sound clip.Gospel.Noise.Alternative rock.Bass.Soul.Punk.Space.Meditative.Instrumental pop.Instrumental rock.Ethnic.Gothic.Darkwave.Techno-industrial.Electronic.Pop-folk.Eurodance.Dream.Southern rock.Comedy.Cult.Gangsta.Top 40.Christian rap.Pop/funk.Jungle music.Native US.Cabaret.New wave.Psychedelic.Rave.Showtunes.Trailer.Lo-fi.Tribal.Acid punk.Acid jazz.Polka.Retro.Musical.Rock 'n' roll.Hard rock.Folk.Folk rock.National folk.Swing.Fast fusion.Bebop.Latin.Revival.Celtic.Bluegrass.Avantgarde.Gothic rock.Progressive rock.Psychedelic rock.Symphonic rock.Slow rock.Big band.Chorus.Easy listening.Acoustic.Humour.Speech.Chanson.Opera.Chamber music.Sonata.Symphony.Booty bass.Primus.Porn groove.Satire.Slow jam.Club.Tango.Samba.Folklore.Ballad.Power ballad.Rhythmic Soul.Freestyle.Duet.Punk rock.Drum solo.A cappella.Euro-house.Dance hall.Goa music.Drum & bass.Club-house.Hardcore techno.Terror.Indie.Britpop.Negerpunk.Polsk punk.Beat.Christian gangsta rap.Heavy metal.Black metal.Crossover.Contemporary Christian.Christian rock.Merengue.Salsa.Thrash metal.Anime.Jpop.Synthpop.Christmas.Art rock.Baroque.Bhangra.Big beat.Breakbeat.Chillout.Downtempo.Dub.EBM.Eclectic.Electro.Electroclash.Emo.Experimental.Garage.Global.IDM.Illbient.Industro-Goth.Jam Band.Krautrock.Leftfield.Lounge.Math rock.New romantic.Nu-breakz.Post-punk.Post-rock.Psytrance.Shoegaze.Space rock.Trop rock.World music.Neoclassical.Audiobook.Audio theatre.Neue Deutsche Welle.Podcast.Indie rock.G-Funk.Dubstep.Garage rock.Psybient`.split(`.`),Eb=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=V(e,125),e.filePos=n;let r=Db(e,30);r&&(t.title??=r);let i=Db(e,30);i&&(t.artist??=i);let a=Db(e,30);a&&(t.album??=a);let o=Db(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(String(s)));let c=V(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=Db(e,28),e.skip(2)}else e.skip(-30),l=Db(e,30);l&&(t.comment??=l);let u=H(e);u<Tb.length&&(t.genre??=Tb[u])},Db=(e,t)=>{let n=V(e,t),r=Xp(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},Ob=e=>{let t=e.filePos,n=xb(e,3),r=H(e),i=H(e),a=H(e),o=U(e);if(n!==`ID3`||r===255||i===255||o&2155905152)return e.filePos=t,null;let s=Tg(o);return a&Cb.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},kb=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){dm._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new Ab(t,V(e,t.flags&Cb.Footer?t.size-10:t.size));if(t.flags&Cb.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&Cb.ExtendedHeader){let e=r.readU32();t.majorVersion===3?r.pos+=e:r.pos+=e-4}for(;r.pos<=r.bytes.length-r.frameHeaderSize();){let e=r.readId3V2Frame();if(!e)break;let i=r.pos,a=r.pos+e.size,o=!1,s=!1,c=!1;if(t.majorVersion===3?(o=!!(e.flags&64),s=!!(e.flags&128)):t.majorVersion===4&&(o=!!(e.flags&4),s=!!(e.flags&8),c=!!(e.flags&2)||!!(t.flags&Cb.Unsynchronisation)),o){dm._warn(`Skipping encrypted ID3v2 frame ${e.id}`),r.pos=a;continue}if(s){dm._warn(`Skipping compressed ID3v2 frame ${e.id}`),r.pos=a;continue}if(c&&r.ununsynchronizeRegion(r.pos,a),n.raw??={},e.id===`TXXX`){let e=n.raw.TXXX??={},t=r.readId3V2TextEncoding(),i=r.readId3V2Text(t,a),o=r.readId3V2Text(t,a);e[i]??=o}else e.id[0]===`T`?n.raw[e.id]??=r.readId3V2EncodingAndText(a):n.raw[e.id]??=r.readBytes(e.size);switch(r.pos=i,e.id){case`TIT2`:case`TT2`:n.title??=r.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=r.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=r.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=r.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=r.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`TPOS`:case`TPA`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break;case`TCON`:case`TCO`:{let e=r.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(Tb[e]!==void 0){n.genre??=Tb[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(Tb[e]!==void 0){n.genre??=Tb[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=r.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=r.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(String(t)))}break;case`USLT`:case`ULT`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.lyrics??=r.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.comment??=r.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=r.readId3V2TextEncoding(),i;if(t.majorVersion===2){let e=r.readAscii(3);i=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else i=r.readId3V2Text(e,a);let o=r.readU8(),s=r.readId3V2Text(e,a).trimEnd(),c=a-r.pos;if(c>=0){let e=r.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:i,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:r.pos+=e.size}r.pos=a}},Ab=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let r=e;r<t;r++){let e=this.bytes[r];n.push(e),e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}let r=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+n.length+i.length),this.bytes.set(r,0),this.bytes.set(n,r.length),this.bytes.set(i,r.length+n.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t=``;for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?Tg(t):t,r=this.readU16(),i=this.pos,a=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if(t!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!a(n)){let e=this.header.majorVersion===4?t:Tg(t);a(e)&&(n=e)}return this.pos=i,{id:e,size:n,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case wb.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case wb.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new cp(`utf-16le`),t=Xp(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(r[0]===254&&r[1]===255){let e=new cp(`utf-16be`),t=Xp(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{let e=Xp(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),lp.decode(r.subarray(0,e))}case wb.UTF_16_BE_NO_BOM:{let e=new cp(`utf-16be`),t=Xp(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case wb.UTF_8:{let e=Xp(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),lp.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},jb=class{constructor(e){this.mutex=new Sp,this.trackTimestampInfo=/* @__PURE__ */ new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},Mb=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Nb=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},Pb=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);I(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},W=/* #__PURE__ */ new Uint8Array(8),Fb=/* #__PURE__ */ new DataView(W.buffer),Ib=e=>[(e%256+256)%256],G=e=>(Fb.setUint16(0,e,!1),[W[0],W[1]]),Lb=e=>(Fb.setInt16(0,e,!1),[W[0],W[1]]),Rb=e=>(Fb.setUint32(0,e,!1),[W[1],W[2],W[3]]),K=e=>(Fb.setUint32(0,e,!1),[W[0],W[1],W[2],W[3]]),zb=e=>(Fb.setInt32(0,e,!1),[W[0],W[1],W[2],W[3]]),Bb=e=>(Fb.setUint32(0,Math.floor(e/2**32),!1),Fb.setUint32(4,e,!1),[W[0],W[1],W[2],W[3],W[4],W[5],W[6],W[7]]),Vb=e=>(Fb.setInt32(0,Math.floor(e/2**32),!1),Fb.setUint32(4,e,!1),[W[0],W[1],W[2],W[3],W[4],W[5],W[6],W[7]]),Hb=e=>(Fb.setInt16(0,256*e,!1),[W[0],W[1]]),Ub=e=>(Fb.setInt32(0,2**16*e,!1),[W[0],W[1],W[2],W[3]]),Wb=e=>(Fb.setInt32(0,2**30*e,!1),[W[0],W[1],W[2],W[3]]),Gb=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},Kb=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},qb=e=>[Ub(e[0]),Ub(e[1]),Wb(e[2]),Ub(e[3]),Ub(e[4]),Wb(e[5]),Ub(e[6]),Ub(e[7]),Wb(e[8])],q=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),Jb=(e,t,n,r,i)=>q(e,[Ib(t),Rb(n),r??[]],i),Yb=e=>e.isQuickTime?q(`ftyp`,[Kb(`qt `),K(512),Kb(`qt `)]):e.fragmented?e.cmaf?q(`ftyp`,[Kb(`iso5`),K(512),Kb(`iso5`),Kb(`iso6`),Kb(`mp41`),Kb(`cmfc`),Kb(`dash`)]):q(`ftyp`,[Kb(`iso5`),K(512),Kb(`iso5`),Kb(`iso6`),Kb(`mp41`)]):q(`ftyp`,[Kb(`isom`),K(512),Kb(`isom`),e.holdsAvc?Kb(`avc1`):[],Kb(`mp41`)]),Xb=()=>q(`styp`,[Kb(`iso5`),K(0),Kb(`iso5`),Kb(`iso6`),Kb(`mp41`),Kb(`cmfc`),Kb(`dash`)]),Zb=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),Jb(`sidx`,1,0,[K(1),K(kS),Bb(MS(n,kS)),Bb(0),G(0),G(1),K(t&2147483647),K(MS(r,kS)),K(0)])},Qb=e=>({type:`mdat`,largeSize:e}),$b=e=>({type:`free`,size:e}),ex=e=>q(`moov`,void 0,[tx(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>nx(t,e.creationTime)),e.isFragmented?Gx(e.trackDatas):null,oS(e)]),tx=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,MS(NS(e),kS)+MS(e.startTimestampOffset??0,kS)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!np(e)||!np(n),a=i?Bb:K;return Jb(`mvhd`,+i,0,[a(e),a(e),K(kS),a(n),Ub(1),Hb(1),Array(10).fill(0),qb(qf),Array(24).fill(0),K(r)])},nx=(e,t)=>{let n=jS(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return q(`trak`,void 0,[rx(e,t),r?ix(e):null,ax(e,t),n.name===void 0?null:q(`udta`,void 0,[q(`name`,[...up.encode(n.name)])])])},rx=(e,t)=>{let n=Math.max(0,MS(NS(e),kS)+MS(e.startTimestampOffset??0,kS)),r=!np(t)||!np(n),i=r?Bb:K,a;if(e.type===`video`&&e.track.metadata.transformationMatrix)a=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata;a=Jf(ep(Zf(t??0),$f(n?-1:1,1)),e.info.width,e.info.height)}else a=qf;let o=2;e.track.metadata.disposition?.default!==!1&&(o|=1);let s=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:Np(e);return Jb(`tkhd`,+r,o,[i(t),i(t),K(e.track.id),K(0),i(n),Array(8).fill(0),G(0),G(s),Hb(+(e.type===`audio`)),G(0),qb(a),Ub(e.type===`video`?e.info.width:0),Ub(e.type===`video`?e.info.height:0)])},ix=e=>{let t=e.startTimestampOffset;if(I(t!==null),t>0){let n=MS(t,kS),r=MS(NS(e),kS),i=!np(n)||!np(r),a=i?Bb:K,o=i?Vb:zb;return q(`edts`,void 0,[Jb(`elst`,+!!i,0,[K(2),a(n),o(-1),Ub(1),a(r),o(0),Ub(1)])])}{let n=MS(-t,e.timescale),r=Math.max(0,MS(NS(e),kS)+MS(t,kS)),i=!rp(n)||!np(r),a=i?Bb:K,o=i?Vb:zb;return q(`edts`,void 0,[Jb(`elst`,+!!i,0,[K(1),a(r),o(n),Ub(1)])])}},ax=(e,t)=>q(`mdia`,void 0,[ox(e,t),lx(!0,sx[e.type],cx[e.type]),ux(e)]),ox=(e,t)=>{let n=MS(NS(e),e.timescale),r=!np(t)||!np(n),i=r?Bb:K;return Jb(`mdhd`,+r,0,[i(t),i(t),K(e.timescale),i(n),G(bS(e.track.metadata.languageCode??`und`)),G(0)])},sx={video:`vide`,audio:`soun`,subtitle:`text`},cx={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},lx=(e,t,n,r=`\0\0\0\0`)=>Jb(`hdlr`,0,0,[e?Kb(`mhlr`):K(0),Kb(t),Kb(r),K(0),K(0),Kb(n,!0)]),ux=e=>q(`minf`,void 0,[dx[e.type](),fx(),hx(e)]),dx={video:()=>Jb(`vmhd`,0,1,[G(0),G(0),G(0),G(0)]),audio:()=>Jb(`smhd`,0,0,[G(0),G(0)]),subtitle:()=>Jb(`nmhd`,0,0)},fx=()=>q(`dinf`,void 0,[px()]),px=()=>Jb(`dref`,0,0,[K(1)],[mx()]),mx=()=>Jb(`url `,0,1),hx=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return q(`stbl`,void 0,[gx(e),Rx(e),t?Ux(e):null,t?Wx(e):null,Bx(e),Vx(e),Hx(e),zx(e)])},gx=e=>{let t;if(e.type===`video`)t=_x(mS(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=gS(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);I(n),t=Tx(n,e)}else e.type===`subtitle`&&(t=Ix(vS[e.track.source._codec],e));return I(t),Jb(`stsd`,0,0,[K(1)],[t])},_x=(e,t)=>q(e,[[,,,,,,].fill(0),G(1),G(0),G(0),Array(12).fill(0),G(t.info.width),G(t.info.height),K(4718592),K(4718592),K(0),G(1),Ib(10),Kb(`Mediabunny`),Array(21).fill(0),G(t.info.hasAlphaChannel?32:24),Lb(65535)],[hS[t.track.source._codec]?.(t)??null,yx(t),yp(t.info.decoderConfig.colorSpace)?null:bx(t),vx(t)]),vx=e=>e.avgBitrate===0&&e.maxBitrate===0?null:q(`btrt`,[K(0),K(e.maxBitrate),K(e.avgBitrate)]),yx=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:q(`pasp`,[K(e.info.pixelAspectRatio.num),K(e.info.pixelAspectRatio.den)]),bx=e=>{let t=e.info.decoderConfig.colorSpace;return q(`colr`,[Kb(e.muxer.isQuickTime?`nclc`:`nclx`),G(t?.primaries==null?2:fp[t.primaries]),G(t?.transfer==null?2:mp[t.transfer]),G(t?.matrix==null?2:gp[t.matrix]),e.muxer.isQuickTime?[]:Ib(!!t?.fullRange<<7)])},xx=e=>e.info.decoderConfig&&q(`avcC`,[...ap(e.info.decoderConfig.description)]),Sx=e=>e.info.decoderConfig&&q(`hvcC`,[...ap(e.info.decoderConfig.description)]),Cx=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?fp[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?mp[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?gp[t.colorSpace.matrix]:1;return Jb(`vpcC`,1,0,[Ib(r),Ib(i),Ib(c),Ib(l),Ib(u),Ib(d),G(0)])},wx=e=>q(`av1C`,ng(e.info.decoderConfig.codec)),Tx=(e,t)=>{let n=0,r,i=16,a=Kh.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=cg(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),G(1),G(n),G(0),K(0),G(t.info.numberOfChannels),G(i),G(0),G(0),G(t.info.sampleRate<2**16?t.info.sampleRate:0),G(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),G(1),G(n),G(0),K(0),G(t.info.numberOfChannels),G(Math.min(i,16)),Lb(e),G(0),G(t.info.sampleRate<2**16?t.info.sampleRate:0),G(0),a?[K(1),K(i/8),K(t.info.numberOfChannels*i/8)]:[K(0),K(0),K(0)],K(2)]}return q(e,r,[_S(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,vx(t)])},Ex=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...Ib(t),...Ib(21),...Rb(0),...K(e.maxBitrate),...K(e.avgBitrate)];if(e.info.decoderConfig.description){let t=ap(e.info.decoderConfig.description);n=[...n,...Ib(5),...Gb(t.byteLength),...t]}return n=[...G(1),...Ib(0),...Ib(4),...Gb(n.length),...n,...Ib(6),...Ib(1),...Ib(2)],n=[...Ib(3),...Gb(n.length),...n],Jb(`esds`,0,0,n)},Dx=e=>q(`wave`,void 0,[Ox(e),kx(e),q(`\0\0\0\0`)]),Ox=e=>q(`frma`,[Kb(gS(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),kx=e=>{let{littleEndian:t}=cg(e.track.source._codec);return q(`enda`,[G(+t)])},Ax=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=/* @__PURE__ */ new Uint8Array,s=e.info.decoderConfig?.description;if(s){I(s.byteLength>=18);let e=uh(ap(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return q(`dOps`,[Ib(0),Ib(t),G(n),K(r),Lb(i),Ib(a),...o])},jx=e=>{let t=e.info.decoderConfig?.description;return I(t),Jb(`dfLa`,0,0,[...ap(t).subarray(4)])},Mx=e=>{let{littleEndian:t,sampleSize:n}=cg(e.track.source._codec);return Jb(`pcmC`,0,0,[Ib(+t),Ib(8*n)])},Nx=e=>{I(e.info.primingPacket);let t=vh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=/* @__PURE__ */ new Uint8Array(3),r=new _m(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),q(`dac3`,[...n])},Px=e=>{I(e.info.primingPacket);let t=Sh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new _m(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return q(`dec3`,[...i])},Fx=e=>{I(e.info.primingPacket);let t=Rh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return q(`ddts`,[...Uh(t)])},Ix=(e,t)=>q(e,[[,,,,,,].fill(0),G(1)],[yS[t.track.source._codec](t),vx(t)]),Lx=e=>q(`vttC`,[...up.encode(e.info.config.description)]),Rx=e=>Jb(`stts`,0,0,[K(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[K(e.sampleCount),K(e.sampleDelta)])]),zx=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return Jb(`stss`,0,0,[K(t.length),t.map(([e])=>K(e+1))])},Bx=e=>Jb(`stsc`,0,0,[K(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[K(e.firstChunk),K(e.samplesPerChunk),K(1)])]),Vx=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=cg(e.track.source._codec);return Jb(`stsz`,0,0,[K(t*e.info.numberOfChannels),K(e.samples.reduce((t,n)=>t+MS(n.duration,e.timescale),0))])}return Jb(`stsz`,0,0,[K(0),K(e.samples.length),e.samples.map(e=>K(e.size))])},Hx=e=>e.finalizedChunks.length>0&&tp(e.finalizedChunks).offset>=2**32?Jb(`co64`,0,0,[K(e.finalizedChunks.length),e.finalizedChunks.map(e=>Bb(e.offset))]):Jb(`stco`,0,0,[K(e.finalizedChunks.length),e.finalizedChunks.map(e=>K(e.offset))]),Ux=e=>Jb(`ctts`,1,0,[K(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[K(e.sampleCount),zb(e.sampleCompositionTimeOffset)])]),Wx=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;I(e.compositionTimeOffsetTable.length>0),I(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,MS(n.timestamp,e.timescale)),i=Math.max(i,MS(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:Jb(`cslg`,0,0,[zb(a),zb(t),zb(n),zb(r),zb(i)])},Gx=e=>q(`mvex`,void 0,e.map(Kx)),Kx=e=>Jb(`trex`,0,0,[K(e.track.id),K(1),K(0),K(0),K(0)]),qx=(e,t)=>q(`moof`,void 0,[Jx(e),...t.map(Xx)]),Jx=e=>Jb(`mfhd`,0,0,[K(e)]),Yx=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Xx=e=>q(`traf`,void 0,[Zx(e),Qx(e),$x(e)]),Zx=e=>{I(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:Yx(n)};return Jb(`tfhd`,0,t,[K(e.track.id),K(r.duration),K(r.size),K(r.flags)])},Qx=e=>(I(e.currentChunk),Jb(`tfdt`,1,0,[Bb(MS(e.currentChunk.startTimestamp,e.timescale))])),$x=e=>{I(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Yx),i=e.currentChunk.samples.map(t=>MS(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,Jb(`trun`,1,m,[K(e.currentChunk.samples.length),K(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?K(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?K(t[a]):[],d?K(n[a]):[],f?K(r[a]):[],p?zb(i[a]):[]])])},eS=e=>q(`mfra`,void 0,[...e.map(tS),nS()]),tS=e=>Jb(`tfra`,1,0,[K(e.track.id),K(63),K(e.finalizedChunks.length),e.finalizedChunks.map(t=>[Bb(MS(t.samples[0].timestamp,e.timescale)),Bb(t.moofOffset),K(t.trafIndex+1),K(1),K(1)])]),nS=()=>Jb(`mfro`,0,0,[K(0)]),rS=()=>q(`vtte`),iS=(e,t,n,r,i)=>q(`vttc`,void 0,[i===null?null:q(`vsid`,[zb(i)]),n===null?null:q(`iden`,[...up.encode(n)]),t===null?null:q(`ctim`,[...up.encode(Nb(t))]),r===null?null:q(`sttg`,[...up.encode(r)]),q(`payl`,[...up.encode(e)])]),aS=e=>q(`vtta`,[...up.encode(e)]),oS=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=dS(r);e&&t.push(e)}else if(n===`mdta`){let e=fS(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&sS(t,e.output._metadataTags);return t.length===0?null:q(`udta`,void 0,t)},sS=(e,t)=>{for(let{key:n,value:r}of Zp(t))switch(n){case`title`:e.push(cS(`©nam`,r));break;case`description`:e.push(cS(`©des`,r));break;case`artist`:e.push(cS(`©ART`,r));break;case`album`:e.push(cS(`©alb`,r));break;case`albumArtist`:e.push(cS(`albr`,r));break;case`genre`:e.push(cS(`©gen`,r));break;case`date`:e.push(cS(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(cS(`©cmt`,r));break;case`lyrics`:e.push(cS(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:Np(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(cS(n,r)):r instanceof Uint8Array&&e.push(q(n,Array.from(r))))}},cS=(e,t)=>{let n=up.encode(t);return q(e,[G(n.length),G(bS(`und`)),Array.from(n)])},lS={"image/jpeg":13,"image/png":14,"image/bmp":27},uS=(e,t)=>{let n=[];for(let{key:r,value:i}of Zp(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:pS(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:pS(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:pS(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:pS(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:pS(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:pS(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:pS(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:pS(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:pS(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:q(`data`,[K(lS[e.mimeType]??0),K(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:pS(t)})}else n.push({key:`trkn`,value:q(`data`,[K(0),K(0),G(0),G(i),G(e.tracksTotal??0),G(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:q(`data`,[K(0),K(0),G(0),G(i),G(e.discsTotal??0),G(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Np(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:pS(i)}):i instanceof Uint8Array?n.push({key:r,value:q(`data`,[K(0),K(0),Array.from(i)])}):i instanceof fm&&n.push({key:r,value:q(`data`,[K(lS[i.mimeType]??0),K(0),Array.from(i.data)])}))}return n},dS=e=>{let t=uS(e,!1);return t.length===0?null:Jb(`meta`,0,0,void 0,[lx(!1,`mdir`,``,`appl`),q(`ilst`,void 0,t.map(e=>q(e.key,void 0,[e.value])))])},fS=e=>{let t=uS(e,!0);return t.length===0?null:q(`meta`,void 0,[lx(!1,`mdta`,``),Jb(`keys`,0,0,[K(t.length)],t.map(e=>q(`mdta`,[...up.encode(e.key)]))),q(`ilst`,void 0,t.map((e,t)=>q(String.fromCharCode(...K(t+1)),void 0,[e.value])))])},pS=e=>q(`data`,[K(1),K(0),...up.encode(e)]),mS=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},hS={avc:xx,hevc:Sx,vp8:Cx,vp9:Cx,av1:wx,prores:null},gS=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},_S=(e,t)=>{switch(e){case`aac`:return Ex;case`mp3`:return Ex;case`opus`:return Ax;case`vorbis`:return Ex;case`flac`:return jx;case`ac3`:return Nx;case`eac3`:return Px;case`dts`:return Fx}if(t)switch(e){case`pcm-s24`:return Dx;case`pcm-s24be`:return Dx;case`pcm-s32`:return Dx;case`pcm-s32be`:return Dx;case`pcm-f32`:return Dx;case`pcm-f32be`:return Dx;case`pcm-f64`:return Dx;case`pcm-f64be`:return Dx}else switch(e){case`pcm-s16`:return Mx;case`pcm-s16be`:return Mx;case`pcm-s24`:return Mx;case`pcm-s24be`:return Mx;case`pcm-s32`:return Mx;case`pcm-s32be`:return Mx;case`pcm-f32`:return Mx;case`pcm-f32be`:return Mx;case`pcm-f64`:return Mx;case`pcm-f64be`:return Mx}return null},vS={webvtt:`wvtt`},yS={webvtt:Lx},bS=e=>{I(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},xS=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){I(!this.started),this.target._start(),this.started=!0}write(e){I(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return I(this.started&&!this.finalized),this.target._flush()}async finalize(){I(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=/* @__PURE__ */ new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},SS=class extends cm{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new DS(this,e)}},CS=2**16,wS=2**32,TS=class extends SS{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in/* @__PURE__ */ new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(CS,{maxByteLength:wS})}catch{this._buffer=new ArrayBuffer(CS),this._supportsResize=!1}else this._buffer=new ArrayBuffer(CS);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>wS)throw Error(`ArrayBuffer exceeded maximum size of ${wS} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},ES=class extends SS{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit(`finalized`)}async _close(){}},DS=class extends SS{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},OS=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},kS=57600,AS=2082844800,jS=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},MS=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},NS=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},PS=class extends jb{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new TS,this.auxWriter=new xS(this.auxTarget,!1),this.auxBoxWriter=new Pb(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=kp(),this.creationTime=Math.floor(Date.now()/1e3)+AS,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof WS,this.isCmaf=t instanceof US,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof US?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof TS:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new Pb(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof TS&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new xS(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Pb(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(I(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Yb({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(I(this.writer),I(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Qb(!0),this.boxWriter.writeBox(this.mdat))}await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return jg({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;hg(n,e.source._codec),I(n),I(n.decoderConfig);let i={...n.decoderConfig};I(i.codedWidth!==void 0),I(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=Lm(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Rm(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=Km(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=eh(e),a=!0}let o=Kp(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:am({num:s*i.codedHeight,den:c*i.codedWidth}),u=i.codec===`ap4h`||i.codec===`ap4x`,d={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a,hasAlphaChannel:u},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;_g(n,e.source._codec),I(n),I(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=ov(ab.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=vm[e.samplingFrequencyIndex],r=ym[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=Cm({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),a=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Kh.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,primingPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;vg(t),I(t),I(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */ new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...jm(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=Im(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=ov(ab.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=cg(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=MS(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=cg(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=/* @__PURE__ */ new Set([]);for(let r of e.cueQueue)I(r.timestamp<=t),I(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=rS();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;Mb.lastIndex=0;let r=Mb.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=aS(n.notes);this.auxBoxWriter.writeBox(e)}let c=iS(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:MS(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){I(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=MS(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=tp(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=MS(r.timestamp-r.decodeTimestamp,e.timescale),a=MS(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){I(e.lastSample);let t=MS(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(I(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=tp(e.timeToSampleTable);if(I(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=tp(e.compositionTimeOffsetTable);I(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=MS(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,I(e.lastSample),I(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){I(t.type===`key`);let n=MS(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(I(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),I(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(I(!this.isFragmented),I(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+MS(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||tp(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)I(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(I(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(I(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;I(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=ex(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){I(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Pb(this.writer);let e=this.boxWriter.measureBox(Xb()),t=this.boxWriter.measureBox(Zb(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}I(this.writer),I(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=qx(n,t),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e=0;e<t.length;e++){let n=t[e];I(n.currentChunk),I(n.startTimestampOffset!==null),n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e,n.currentChunk.startTimestamp-=n.startTimestampOffset;for(let e of n.currentChunk.samples)o+=e.size,e.timestamp-=n.startTimestampOffset,e.decodeTimestamp-=n.startTimestampOffset;s=Math.min(s,n.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=qx(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}I(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=Qb(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){I(this.writer),I(this.boxWriter),this.ensureOneEnabledTrack();let e=ex(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;I(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Qb(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){I(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;I(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){I(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e);let t=NS(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(I(this.writer),I(this.boxWriter),this.fastStart===`in-memory`){this.mdat=Qb(!1);let e;for(let t=0;t<2;t++){let t=ex(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)I(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=ex(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)I(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(Xb()),this.boxWriter.writeBox(Zb(this,e))}else{let e=this.writer.getPos(),t=eS(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{I(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);I(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=ex(this);if(this.fastStart===`reserve`){I(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox($b(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}},FS=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},IS=class extends FS{constructor(e){if(super(),this._connectedTrack=null,!Gh.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${Gh.join(`, `)}.`);this._codec=e}},LS=class extends FS{constructor(e){if(super(),this._connectedTrack=null,!Jh.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${Jh.join(`, `)}.`);this._codec=e}},RS=class extends LS{constructor(e){super(e)}add(e,t){if(!(e instanceof Ag))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},zS=class extends FS{constructor(e){if(super(),this._connectedTrack=null,!Yh.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Yh.join(`, `)}.`);this._codec=e}},BS=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Gh.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Jh.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Yh.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},VS=class extends BS{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!tm(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new PS(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},HS=class extends VS{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Gh,...qh,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Yh]}_codecUnsupportedHint(e){return new WS().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},US=class extends VS{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Gh,...qh,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Yh]}},WS=class extends VS{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...Gh,...Jh]}_codecUnsupportedHint(e){return new HS().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},GS=[`video`,`audio`,`subtitle`],KS=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=sm(this.metadata.group),r=sm(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},qS=class extends KS{constructor(e,t,n,r){super(e,t,`video`,n,r)}},JS=class extends KS{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},YS=class extends KS{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},XS=class e{constructor(){this._pairedGroups=/* @__PURE__ */ new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},ZS=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Wp(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&gm(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof XS)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof XS))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},QS=class extends cm{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(R(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new XS,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=/* @__PURE__ */ new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Sp,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof BS))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof SS||e.target instanceof OS))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof SS&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof SS)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof SS&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){I(this._target instanceof OS);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof SS))throw TypeError(`getTarget must return a Target.`);return e};return R(t)?t.then(n):n(t)}async _getTarget(e){I(this._target instanceof OS);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(I(this._initTarget!==null),this._initTarget instanceof SS)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof SS)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return R(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new xS(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof IS))throw TypeError(`source must be a VideoSource.`);if(ZS(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.decoderConfig!==void 0&&hg({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof Ag))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new qS(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof LS))throw TypeError(`source must be an AudioSource.`);if(ZS(t),t.decoderConfig!==void 0&&_g({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof Ag))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new JS(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof zS))throw TypeError(`source must be a SubtitleSource.`);ZS(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new YS(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(mm(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of GS)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of GS){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(dm._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&dm._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(dm._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,e}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};function $S(e){let t=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);return Uint8Array.from(t)}function eC(e,t){return{codec:e.codec,codedWidth:e.codedWidth??t.codedWidth,codedHeight:e.codedHeight??t.codedHeight,description:e.description===void 0?void 0:$S(e.description),colour:t.colour}}function tC(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,description:e.description===void 0?void 0:$S(e.description)}}function nC(e){return{primaries:el(Zc,e?.primaries),transfer:el(Qc,e?.transfer),matrix:el($c,e?.matrix),range:rC(e?.fullRange)}}function rC(e){return e===!0?`full`:e===!1?`limited`:`unspecified`}var iC=class{async read(e){let t=new tb({formats:Py,source:new oy(e)});try{let[e,n]=await Promise.all([t.getVideoTracks(),t.getAudioTracks()]);return{video:await Promise.all(e.map((e,t)=>aC(e,t))),audio:(await Promise.all(n.map(e=>sC(e)))).flat()}}catch(e){throw cC(e)}finally{t.dispose()}}};async function aC(e,t){let[n,r,i]=await Promise.all([oC(e),e.getCodedWidth(),e.getCodedHeight()]);if(n===null)throw new A(`codec-unsupported`,`video track ${t} has no decoder configuration in its sample entry`);let a={trackIndex:t,codedWidth:r,codedHeight:i,codec:n.codec,colour:nC(n.colorSpace)};return{trackId:e.id,description:a,configuration:eC(n,a)}}async function oC(e){try{return await e.getDecoderConfig()}catch{return null}}async function sC(e){let t=await e.getDecoderConfig();return t===null?[]:[{trackId:e.id,configuration:tC(t)}]}function cC(e){return ie(e)||e instanceof A?e:new A(`unsupported-container`,`the movie box is not a readable movie`,{cause:e})}var lC=class{capacity;queue=[];roomWaiters=[];takeWaiter;isClosedNow=!1;failure;constructor(e){this.capacity=e}get isClosed(){return this.isClosedNow}push(e){this.isClosedNow||(this.queue.push(e),this.wakeTaker())}waitForRoom(){return this.queue.length<this.capacity||this.isClosedNow?Promise.resolve():new Promise(e=>{this.roomWaiters.push(e)})}close(){this.isClosedNow=!0,this.wakeTaker(),this.wakeRoomWaiters()}fail(e){this.failure??=e instanceof Error?e:new A(`decode`,`audio re-packaging failed`,{cause:e}),this.close()}segments(e=dC){return new uC({take:()=>this.take(),close:()=>{this.close()},onEnd:e})}async take(){for(;this.queue.length===0&&!this.isClosedNow;)await this.nextPush();let e=this.queue.shift();if(e)return this.wakeRoomWaiters(),e;if(this.failure)throw this.failure}nextPush(){return j(this.takeWaiter===void 0,`a segment channel has one consumer`),new Promise(e=>{this.takeWaiter=e})}wakeTaker(){let e=this.takeWaiter;this.takeWaiter=void 0,e?.()}wakeRoomWaiters(){if(this.queue.length>=this.capacity&&!this.isClosedNow)return;let e=this.roomWaiters;this.roomWaiters=[];for(let t of e)t()}},uC=class{parts;hasEnded=!1;constructor(e){this.parts=e}async next(){if(this.hasEnded)return yl;try{let e=await this.parts.take();return e===void 0||this.wasEnded()?this.end():{done:!1,value:e}}catch(e){throw this.end(),e}}return(){return this.parts.close(),Promise.resolve(this.end())}[Symbol.asyncIterator](){return this}wasEnded(){return this.hasEnded}end(){return this.hasEnded||this.parts.onEnd(),this.hasEnded=!0,yl}};function dC(){}var fC=1,pC=2,mC=`mp4a.40.`,hC=`aac`,gC=class{segmentsOf(e,t){let n=_C(t);return{mimeType:`audio/mp4; codecs="${t.codec}"`,duration:e.duration,segmentsFrom:r=>({[Symbol.asyncIterator]:()=>vC({samples:e,configuration:t,codec:n},r)})}}};function _C(e){if(e.codec.startsWith(mC))return hC;throw new A(`codec-unsupported`,`audio in ${e.codec} cannot be re-packaged for playback`)}function vC(e,t){let n=new lC(pC),r=new QS({format:CC(n),target:new ES}),i=new RS(e.codec);r.addAudioTrack(i);let a=e.samples.samplesFrom(t)[Symbol.asyncIterator](),o=bC({samples:a,configuration:e.configuration,output:r,source:i,channel:n});return n.segments(()=>{a.return?.(),yC(o,r)})}async function yC(e,t){if(await e,t.state!==`finalized`)try{await t.cancel()}catch{}}async function bC(e){try{await e.output.start();let t={decoderConfig:SC(e.configuration)};for(let n=await e.samples.next();n.done!==!0;n=await e.samples.next()){if(await e.channel.waitForRoom(),e.channel.isClosed)return;await e.source.add(xC(n.value),t),t=void 0}if(e.channel.isClosed)return;await e.output.finalize(),e.channel.close()}catch(t){e.channel.fail(t)}}function xC(e){return new Ag(e.data,`key`,e.timestamp,e.duration)}function SC(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,...e.description&&{description:e.description}}}function CC(e){let t=new wC(e);return new HS({fastStart:`fragmented`,minimumFragmentDuration:fC,onFtyp:e=>{t.begin(e)},onMoov:e=>{t.end(e)},onMoof:e=>{t.begin(e)},onMdat:e=>{t.end(e)}})}var wC=class{channel;opening;constructor(e){this.channel=e}begin(e){j(this.opening===void 0,`a segment began before the last one ended`),this.opening=new Uint8Array(e)}end(e){let{opening:t}=this;j(t!==void 0,`a segment ended that never began`);let n=new Uint8Array(t.byteLength+e.byteLength);n.set(t),n.set(e,t.byteLength),this.opening=void 0,this.channel.push(n)}};function TC(e){let t=e.range===`unspecified`?void 0:{fullRange:e.range===`full`},n={...e.primaries!==`unspecified`&&{primaries:e.primaries},...e.transfer!==`unspecified`&&{transfer:e.transfer},...e.matrix!==`unspecified`&&{matrix:e.matrix},...t};return Object.keys(n).length===0?void 0:EC(n)??t}function EC(e){try{return new VideoColorSpace(e).toJSON()}catch{return}}var DC=`no-preference`,OC=class{async isSupported(e){if(typeof VideoDecoder>`u`)throw AC();try{return(await VideoDecoder.isConfigSupported(this.toWebCodecsConfig(e))).supported===!0}catch{return!1}}create(e,t){try{return Promise.resolve(this.configureDecoder(e,t))}catch(e){return Promise.reject(re(e,`codec-unsupported`,`the decoder rejected its configuration`))}}configureDecoder(e,t){if(typeof VideoDecoder>`u`)throw AC();return new kC(this.toWebCodecsConfig(e),t)}toWebCodecsConfig(e){let{description:t}=e,n=TC(e.colour);return{codec:e.codec,codedWidth:e.codedWidth,codedHeight:e.codedHeight,...t&&{description:t},...n&&{colorSpace:n},hardwareAcceleration:DC,optimizeForLatency:!1}}},kC=class{decoder;failure;constructor(e,t){this.decoder=new VideoDecoder({output:e=>{t.onFrame(MC(e))},error:e=>{this.failure??=new A(`decode`,`video decoder failed: ${e.message}`,{cause:e}),t.onError(this.failure)}});try{this.decoder.configure(e)}catch(e){throw this.decoder.close(),e}}get pendingCount(){return this.decoder.decodeQueueSize}decode(e){if(this.failure)throw this.failure;try{this.decoder.decode(jC(e))}catch(e){throw new A(`decode`,`the decoder refused a packet: ${oe(e)}`,{cause:e})}}waitForPendingBelow(e){return this.decoder.decodeQueueSize<e?Promise.resolve():new Promise(t=>{let n=()=>{this.decoder.decodeQueueSize>=e&&this.decoder.state===`configured`||(this.decoder.removeEventListener(`dequeue`,n),t())};this.decoder.addEventListener(`dequeue`,n)})}async flush(){if(this.decoder.state!==`configured`)throw this.failure??new A(`decode`,`flush on a closed decoder`);try{await this.decoder.flush()}catch(e){throw this.failure??new A(`decode`,`the decoder could not be flushed`,{cause:e})}}close(){this.decoder.state!==`closed`&&this.decoder.close()}};function AC(){return new A(`webcodecs-unavailable`,globalThis.isSecureContext?`this browser has no WebCodecs VideoDecoder`:`WebCodecs exists only in secure contexts (HTTPS), and this page is not one`)}function jC(e){return new EncodedVideoChunk({type:e.isKeyFrame?`key`:`delta`,timestamp:vt(e.timestamp),duration:vt(e.duration),data:e.data})}function MC(e){return{timestamp:ht(pt(e.timestamp)),handle:e,close:()=>{e.close()}}}function NC(e){return`url`in e}function PC(e){return NC(e)?ia(e.url):e.name}var FC=15e3;function IC(e={}){let t=e.http??{},n=e.probeTimeoutMs??FC;return{sources:LC(t),codecReader:new iC,audioPackager:new gC,decoderPort:new OC,locatorFor:e=>new Uf(BC(t,e)),probeDeadline:()=>VC(n)}}function LC(e){return{open:(t,n)=>NC(t)?RC(t,e,n):zC(t)}}function RC(e,t,n){let r=new zf(e.url,BC(t,e),n);return{source:new ff(r),stream:new uf(r)}}function zC(e){let t=new Qd(e.blob);return{source:t,stream:new xl(t)}}function BC(e,t){let{credentials:n}=t;return n===void 0?e:{...e,requestInit:{...e.requestInit,credentials:n}}}function VC(e){let t=new Du;return setTimeout(()=>{t.resolve()},e),t}function HC(e,t,n){let r=new AbortController;return n?.addEventListener(`abort`,()=>{r.abort()},{once:!0,signal:r.signal}),new Promise(n=>{for(let i of t)e.addEventListener(i,()=>{r.abort(),n(i)},{once:!0,signal:r.signal})})}var UC=`ManagedMediaSource`,WC=`MediaSource`;function GC(e){return typeof e==`function`&&typeof e.isTypeSupported==`function`}function KC(e){let t=Reflect.get(globalThis,e);return GC(t)?t:void 0}function qC(){return KC(UC)??KC(WC)}function JC(e){return qC()?.isTypeSupported(e)??!1}var YC=1e4;async function XC(e,t){let n=new t,r=ZC(e,n),i=URL.createObjectURL(n);e.disableRemotePlayback=!0,e.src=i;let a={mediaSource:n,detach:()=>{e.src===i&&(e.removeAttribute(`src`),e.load()),URL.revokeObjectURL(i)}},o=await r;if(o!==`sourceopen`)throw a.detach(),new A(`decode`,`the audio element could not open its media source (${o})`);return a}async function ZC(e,t){let n=new AbortController;try{return await Promise.race([HC(t,[`sourceopen`],n.signal),HC(e,[`error`],n.signal),QC(YC,n.signal)])}finally{n.abort()}}function QC(e,t){return new Promise(n=>{let r=setTimeout(()=>{n(`timeout`)},e);t.addEventListener(`abort`,()=>{clearTimeout(r)},{once:!0})})}var $C=30,ew=30,tw=60,nw=1,rw=[`timeupdate`,`seeking`,`waiting`,`play`],iw=class{parts;stop=new ku;run=Promise.resolve();failureValue;constructor(e){this.parts=e}get failure(){return this.failureValue}restartFrom(e){this.stop.stop();let t=new ku;this.stop=t,this.run=this.feedAfter(this.run,e,t)}dispose(){this.stop.stop()}async feedAfter(e,t,n){await e,await this.feed(t,n)}async feed(e,t){try{if(await this.settlePendingAppend(),t.wasStopped||this.hasElementFailed()||this.hasAllAudioFrom(e))return;await this.feedFrom(this.startOf(e),t)}catch(e){this.failureValue??=re(e,`decode`,`feeding the audio buffer failed`)}}async feedFrom(e,t){let n=this.parts.source.segmentsFrom(e)[Symbol.asyncIterator]();try{await this.pump(n,t)&&this.endStream()}finally{n.return?.()}}hasAllAudioFrom(e){let{buffered:t}=this.parts.element,n=this.bufferedEndAt(e);return this.parts.mediaSource.readyState===`ended`&&n>e&&n===t.end(t.length-1)}startOf(e){let t=this.bufferedEndAt(e);return F(t>e?t:Math.max(0,e-nw))}async pump(e,t){let n=await this.nextWhenNeeded(e,t);for(;n!==Ou;){if(n.done===!0)return!0;if(this.hasElementFailed())return!1;this.evictBehind(),await this.append(n.value),n=await this.nextWhenNeeded(e,t)}return!1}async nextWhenNeeded(e,t){return await this.waitUntilNeeded(t),t.race(()=>e.next())}async waitUntilNeeded(e){for(;!e.wasStopped&&this.bufferedAhead()>=$C;){let t=new AbortController;await e.race(()=>HC(this.parts.element,rw,t.signal)),t.abort()}}bufferedAhead(){let{currentTime:e}=this.parts.element;return F(this.bufferedEndAt(e)-e)}bufferedEndAt(e){let{buffered:t}=this.parts.element;for(let n=0;n<t.length;n+=1)if(t.start(n)<=e&&e<t.end(n))return t.end(n);return e}evictBehind(){let{buffered:e,currentTime:t}=this.parts.element;t-(e.length>0?e.start(0):t)<tw||this.parts.sourceBuffer.updating||this.parts.sourceBuffer.remove(0,t-ew)}async append(e){let{sourceBuffer:t}=this.parts;await this.settlePendingAppend();let n=HC(t,[`updateend`,`error`]);try{t.appendBuffer(e)}catch(e){throw new A(`decode`,`the audio buffer rejected a segment`,{cause:e})}if(await n===`error`)throw new A(`decode`,`the audio buffer could not parse a segment`)}hasElementFailed(){return this.parts.element.error!==null}async settlePendingAppend(){this.parts.sourceBuffer.updating&&await HC(this.parts.sourceBuffer,[`updateend`])}endStream(){let{mediaSource:e,sourceBuffer:t}=this.parts;e.readyState===`open`&&!t.updating&&e.endOfStream()}},aw=class e{element;feeder;attached;standingEnd;constructor(e,t,n){this.element=e,this.feeder=t,this.attached=n}static isSupported(e){return JC(e.mimeType)}static async open(t,n){let r=qC();if(!r?.isTypeSupported(n.mimeType))throw new A(`codec-unsupported`,`${n.mimeType} cannot play through Media Source Extensions here`);let i=await XC(t,r);try{let r=i.mediaSource.addSourceBuffer(n.mimeType);i.mediaSource.duration=n.duration;let a=new iw({element:t,mediaSource:i.mediaSource,sourceBuffer:r,source:n});return a.restartFrom(F(0)),new e(t,a,i)}catch(e){throw i.detach(),cw(e)}}get currentTime(){return this.standingEnd??F(this.element.currentTime)}get isRunning(){return!this.element.paused}get hasEnded(){return this.standingEnd!==void 0||this.element.ended}get failure(){return this.feeder.failure??sw(this.element)}async start(){if(!this.hasEnded)try{await this.element.play()}catch(e){if(ie(e))return;let t=ow(e,`NotAllowedError`);throw new A(t?`playback-blocked`:`decode`,t?`the browser refused to start audio playback; a user gesture is needed`:`audio playback failed to start`,{cause:e})}}pause(){this.element.pause()}seek(e){let t=this.attached.mediaSource.duration;if(e>=t){this.standAtEnd(F(t));return}this.standingEnd=void 0,this.element.currentTime=e,this.feeder.restartFrom(e)}dispose(){this.feeder.dispose(),this.element.pause(),this.attached.detach()}standAtEnd(e){this.element.pause(),this.standingEnd=e}};function ow(e,t){return e instanceof Error&&e.name===t}function sw(e){let{error:t}=e;return t===null?void 0:new A(`decode`,`the audio element failed (media error ${t.code})`,{cause:t})}function cw(e){return e instanceof A?e:new A(ow(e,`NotSupportedError`)?`codec-unsupported`:`decode`,`the audio element refused the recording's sound: ${oe(e)}`,{cause:e})}var lw=1e3,uw=1001,dw=1002,fw=1003,pw=1004,mw=1005,hw=1006,gw=1007,_w=1008,vw=1009,yw=1010,bw=1011,xw=1012,Sw=1013,Cw=1014,ww=1015,Tw=1016,Ew=1017,Dw=1018,Ow=1020,kw=35902,Aw=35899,jw=1021,Mw=1022,Nw=1023,Pw=1026,Fw=1027,Iw=1028,Lw=1029,Rw=1030,zw=1031,Bw=1033,Vw=33776,Hw=33777,Uw=33778,Ww=33779,Gw=35840,Kw=35841,qw=35842,Jw=35843,Yw=36196,Xw=37492,Zw=37496,Qw=37488,$w=37489,eT=37490,tT=37491,nT=37808,rT=37809,iT=37810,aT=37811,oT=37812,sT=37813,cT=37814,lT=37815,uT=37816,dT=37817,fT=37818,pT=37819,mT=37820,hT=37821,gT=36492,_T=36494,vT=36495,yT=36283,bT=36284,xT=36285,ST=36286,CT=2300,wT=2301,TT=2302,ET=2303,DT=2400,OT=2401,kT=2402,AT=3200,jT=`srgb`,MT=`srgb-linear`,NT=`linear`,PT=`srgb`,FT=7680,IT=35044,LT=`300 es`,RT=2e3;function zT(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function BT(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function VT(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function HT(){let e=VT(`canvas`);return e.style.display=`block`,e}var UT={};function WT(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function GT(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function J(...e){e=GT(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function Y(...e){e=GT(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function KT(...e){let t=e.join(` `);t in UT||(UT[t]=!0,J(...e))}function qT(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var JT={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},YT=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},XT=/* @__PURE__ */ `00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),ZT=Math.PI/180,QT=180/Math.PI;function $T(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(XT[e&255]+XT[e>>8&255]+XT[e>>16&255]+XT[e>>24&255]+`-`+XT[t&255]+XT[t>>8&255]+`-`+XT[t>>16&15|64]+XT[t>>24&255]+`-`+XT[n&63|128]+XT[n>>8&255]+`-`+XT[n>>16&255]+XT[n>>24&255]+XT[r&255]+XT[r>>8&255]+XT[r>>16&255]+XT[r>>24&255]).toLowerCase()}function eE(e,t,n){return Math.max(t,Math.min(n,e))}function tE(e,t){return(e%t+t)%t}function nE(e,t,n){return(1-n)*e+n*t}function rE(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}function iE(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}var aE=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`THREE.Vector2: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`THREE.Vector2: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=eE(this.x,e.x,t.x),this.y=eE(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=eE(this.x,e,t),this.y=eE(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(eE(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(eE(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},oE=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:J(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(eE(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},X=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`THREE.Vector3: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`THREE.Vector3: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(cE.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(cE.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=eE(this.x,e.x,t.x),this.y=eE(this.y,e.y,t.y),this.z=eE(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=eE(this.x,e,t),this.y=eE(this.y,e,t),this.z=eE(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(eE(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return sE.copy(this).projectOnVector(e),this.sub(sE)}reflect(e){return this.sub(sE.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(eE(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},sE=/*@__PURE__*/ new X,cE=/*@__PURE__*/ new oE,Z=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return KT(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(lE.makeScale(e,t)),this}rotate(e){return KT(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(lE.makeRotation(-e)),this}translate(e,t){return KT(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(lE.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},lE=/*@__PURE__*/ new Z,uE=/*@__PURE__*/ new Z().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),dE=/*@__PURE__*/ new Z().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function fE(){let e={enabled:!0,workingColorSpace:MT,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=mE(e.r),e.g=mE(e.g),e.b=mE(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=hE(e.r),e.g=hE(e.g),e.b=hE(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?NT:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return KT(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return KT(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[MT]:{primaries:t,whitePoint:r,transfer:NT,toXYZ:uE,fromXYZ:dE,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:jT},outputColorSpaceConfig:{drawingBufferColorSpace:jT}},[jT]:{primaries:t,whitePoint:r,transfer:PT,toXYZ:uE,fromXYZ:dE,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:jT}}}),e}var pE=/*@__PURE__*/ fE();function mE(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function hE(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var gE,_E=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{gE===void 0&&(gE=VT(`canvas`)),gE.width=e.width,gE.height=e.height;let t=gE.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=gE}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=VT(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=mE(i[e]/255)*255;return n.putImageData(r,0,0),t}if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(mE(t[e]/255)*255):t[e]=mE(t[e]);return{data:t,width:e.width,height:e.height}}return J(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},vE=0,yE=class{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:vE++}),this.uuid=$T(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<`u`&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(bE(r[t].image)):e.push(bE(r[t]))}else e=bE(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function bE(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?_E.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(J(`Texture: Unable to serialize Texture.`),{})}var xE=0,SE=/*@__PURE__*/ new X,CE=class e extends YT{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=uw,i=uw,a=hw,o=_w,s=Nw,c=vw,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:xE++}),this.uuid=$T(),this.name=``,this.source=new yE(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new aE(0,0),this.repeat=new aE(1,1),this.center=new aE(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Z,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(SE).x}get height(){return this.source.getSize(SE).y}get depth(){return this.source.getSize(SE).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){J(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){J(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case lw:e.x-=Math.floor(e.x);break;case uw:e.x=e.x<0?0:1;break;case dw:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case lw:e.y-=Math.floor(e.y);break;case uw:e.y=e.y<0?0:1;break;case dw:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};CE.DEFAULT_IMAGE=null,CE.DEFAULT_MAPPING=300,CE.DEFAULT_ANISOTROPY=1;var wE=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`THREE.Vector4: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`THREE.Vector4: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=eE(this.x,e.x,t.x),this.y=eE(this.y,e.y,t.y),this.z=eE(this.z,e.z,t.z),this.w=eE(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=eE(this.x,e,t),this.y=eE(this.y,e,t),this.z=eE(this.z,e,t),this.w=eE(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(eE(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},TE=class extends YT{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:hw,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new wE(0,0,e,t),this.scissorTest=!1,this.viewport=new wE(0,0,e,t),this.textures=[];let r=new CE({width:e,height:t,depth:n.depth}),i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:hw,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),e!==null&&e.renderTarget===null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new yE(n)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null){if(e.depthTexture.renderTarget===e){let t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture}return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:`dispose`})}},EE=class extends TE{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},DE=class extends CE{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=fw,this.minFilter=fw,this.wrapR=uw,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=/* @__PURE__ */ new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},OE=class extends CE{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=fw,this.minFilter=fw,this.wrapR=uw,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}},kE=class e{static{e.prototype.isMatrix4=!0}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,r=1/AE.setFromMatrixColumn(e,0).length(),i=1/AE.setFromMatrixColumn(e,1).length(),a=1/AE.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(ME,e,NE)}lookAt(e,t,n){let r=this.elements;return IE.subVectors(e,t),IE.lengthSq()===0&&(IE.z=1),IE.normalize(),PE.crossVectors(n,IE),PE.lengthSq()===0&&(Math.abs(n.z)===1?IE.x+=1e-4:IE.z+=1e-4,IE.normalize(),PE.crossVectors(n,IE)),PE.normalize(),FE.crossVectors(IE,PE),r[0]=PE.x,r[4]=FE.x,r[8]=IE.x,r[1]=PE.y,r[5]=FE.y,r[9]=IE.y,r[2]=PE.z,r[6]=FE.z,r[10]=IE.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],ee=r[2],k=r[6],te=r[10],ne=r[14],A=r[3],re=r[7],ie=r[11],ae=r[15];return i[0]=a*x+o*T+s*ee+c*A,i[4]=a*S+o*E+s*k+c*re,i[8]=a*C+o*D+s*te+c*ie,i[12]=a*w+o*O+s*ne+c*ae,i[1]=l*x+u*T+d*ee+f*A,i[5]=l*S+u*E+d*k+f*re,i[9]=l*C+u*D+d*te+f*ie,i[13]=l*w+u*O+d*ne+f*ae,i[2]=p*x+m*T+h*ee+g*A,i[6]=p*S+m*E+h*k+g*re,i[10]=p*C+m*D+h*te+g*ie,i[14]=p*w+m*O+h*ne+g*ae,i[3]=_*x+v*T+y*ee+b*A,i[7]=_*S+v*E+y*k+b*re,i[11]=_*C+v*D+y*te+b*ie,i[15]=_*w+v*O+y*ne+b*ae,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15],_=s*f-c*d,v=o*f-c*u,y=o*d-s*u,b=a*f-c*l,x=a*d-s*l,S=a*u-o*l;return t*(m*_-h*v+g*y)-n*(p*_-h*b+g*x)+r*(p*v-m*b+g*S)-i*(p*y-m*x+h*S)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[1],a=e[5],o=e[9],s=e[2],c=e[6],l=e[10];return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=t*o-n*a,v=t*s-r*a,y=t*c-i*a,b=n*s-r*o,x=n*c-i*o,S=r*c-i*s,C=l*m-u*p,w=l*h-d*p,T=l*g-f*p,E=u*h-d*m,D=u*g-f*m,O=d*g-f*h,ee=_*O-v*D+y*E+b*T-x*w+S*C;if(ee===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let k=1/ee;return e[0]=(o*O-s*D+c*E)*k,e[1]=(r*D-n*O-i*E)*k,e[2]=(m*S-h*x+g*b)*k,e[3]=(d*x-u*S-f*b)*k,e[4]=(s*T-a*O-c*w)*k,e[5]=(t*O-r*T+i*w)*k,e[6]=(h*y-p*S-g*v)*k,e[7]=(l*S-d*y+f*v)*k,e[8]=(a*D-o*T+c*C)*k,e[9]=(n*T-t*D-i*C)*k,e[10]=(p*x-m*y+g*_)*k,e[11]=(u*y-l*x-f*_)*k,e[12]=(o*w-a*E-s*C)*k,e[13]=(t*E-n*w+r*C)*k,e[14]=(m*v-p*b-h*_)*k,e[15]=(l*b-u*v+d*_)*k,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let i=this.determinantAffine();if(i===0)return n.set(1,1,1),t.identity(),this;let a=AE.set(r[0],r[1],r[2]).length(),o=AE.set(r[4],r[5],r[6]).length(),s=AE.set(r[8],r[9],r[10]).length();i<0&&(a=-a),jE.copy(this);let c=1/a,l=1/o,u=1/s;return jE.elements[0]*=c,jE.elements[1]*=c,jE.elements[2]*=c,jE.elements[4]*=l,jE.elements[5]*=l,jE.elements[6]*=l,jE.elements[8]*=u,jE.elements[9]*=u,jE.elements[10]*=u,t.setFromRotationMatrix(jE),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=RT,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=RT,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},AE=/*@__PURE__*/ new X,jE=/*@__PURE__*/ new kE,ME=/*@__PURE__*/ new X(0,0,0),NE=/*@__PURE__*/ new X(1,1,1),PE=/*@__PURE__*/ new X,FE=/*@__PURE__*/ new X,IE=/*@__PURE__*/ new X,LE=/*@__PURE__*/ new kE,RE=/*@__PURE__*/ new oE,zE=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(eE(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-eE(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(eE(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-eE(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(eE(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-eE(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:J(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return LE.makeRotationFromQuaternion(e),this.setFromRotationMatrix(LE,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return RE.setFromEuler(this),this.setFromQuaternion(RE,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};zE.DEFAULT_ORDER=`XYZ`;var BE=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return!!(this.mask&(1<<e|0))}},VE=0,HE=/*@__PURE__*/ new X,UE=/*@__PURE__*/ new oE,WE=/*@__PURE__*/ new kE,GE=/*@__PURE__*/ new X,KE=/*@__PURE__*/ new X,qE=/*@__PURE__*/ new X,JE=/*@__PURE__*/ new oE,YE=/*@__PURE__*/ new X(1,0,0),XE=/*@__PURE__*/ new X(0,1,0),ZE=/*@__PURE__*/ new X(0,0,1),QE={type:`added`},$E={type:`removed`},eD={type:`childadded`,child:null},tD={type:`childremoved`,child:null},nD=class e extends YT{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:VE++}),this.uuid=$T(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new X,n=new zE,r=new oE,i=new X(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new kE},normalMatrix:{value:new Z}}),this.matrix=new kE,this.matrixWorld=new kE,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new BE,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return UE.setFromAxisAngle(e,t),this.quaternion.multiply(UE),this}rotateOnWorldAxis(e,t){return UE.setFromAxisAngle(e,t),this.quaternion.premultiply(UE),this}rotateX(e){return this.rotateOnAxis(YE,e)}rotateY(e){return this.rotateOnAxis(XE,e)}rotateZ(e){return this.rotateOnAxis(ZE,e)}translateOnAxis(e,t){return HE.copy(e).applyQuaternion(this.quaternion),this.position.add(HE.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(YE,e)}translateY(e){return this.translateOnAxis(XE,e)}translateZ(e){return this.translateOnAxis(ZE,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(WE.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?GE.copy(e):GE.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),KE.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?WE.lookAt(KE,GE,this.up):WE.lookAt(GE,KE,this.up),this.quaternion.setFromRotationMatrix(WE),r&&(WE.extractRotation(r.matrixWorld),UE.setFromRotationMatrix(WE),this.quaternion.premultiply(UE.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(Y(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(QE),eD.child=e,this.dispatchEvent(eD),eD.child=null):Y(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent($E),tD.child=e,this.dispatchEvent(tD),tD.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),WE.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),WE.multiply(e.parent.matrixWorld)),e.applyMatrix4(WE),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(QE),eD.child=e,this.dispatchEvent(eD),eD.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(KE,e,qE),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(KE,JE,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,i=this.matrix.elements;i[12]+=t-i[0]*t-i[4]*n-i[8]*r,i[13]+=n-i[1]*t-i[5]*n-i[9]*r,i[14]+=r-i[2]*t-i[6]*n-i[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let r=this.parent;if(e===!0&&r!==null&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),t===!0){let e=this.children;for(let t=0,r=e.length;t<r;t++)e[t].updateWorldMatrix(!1,!0,n)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,r.name=this.name,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,r.visible=this.visible,r.frustumCulled=this.frustumCulled,r.renderOrder=this.renderOrder,r.static=this.static,r.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0){if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material)}if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}dispose(){this.dispatchEvent({type:`dispose`})}};nD.DEFAULT_UP=/*@__PURE__*/ new X(0,1,0),nD.DEFAULT_MATRIX_AUTO_UPDATE=!0,nD.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var rD=class extends nD{constructor(){super(),this.isGroup=!0,this.type=`Group`}},iD={type:`move`},aD=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new rD,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new rD,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new X,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new X),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new rD,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new X,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new X,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position);c.inputState.pinching&&o>.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(iD)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new rD;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},oD={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},sD={h:0,s:0,l:0},cD={h:0,s:0,l:0};function lD(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var uD=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=jT){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,pE.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=pE.workingColorSpace){return this.r=e,this.g=t,this.b=n,pE.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=pE.workingColorSpace){if(e=tE(e,1),t=eE(t,0,1),n=eE(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=lD(i,r,e+1/3),this.g=lD(i,r,e),this.b=lD(i,r,e-1/3)}return pE.colorSpaceToWorking(this,r),this}setStyle(e,t=jT){function n(t){t!==void 0&&parseFloat(t)<1&&J(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:J(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);J(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=jT){let n=oD[e.toLowerCase()];return n===void 0?J(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=mE(e.r),this.g=mE(e.g),this.b=mE(e.b),this}copyLinearToSRGB(e){return this.r=hE(e.r),this.g=hE(e.g),this.b=hE(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=jT){return pE.workingToColorSpace(dD.copy(this),e),Math.round(eE(dD.r*255,0,255))*65536+Math.round(eE(dD.g*255,0,255))*256+Math.round(eE(dD.b*255,0,255))}getHexString(e=jT){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=pE.workingColorSpace){pE.workingToColorSpace(dD.copy(this),t);let n=dD.r,r=dD.g,i=dD.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=pE.workingColorSpace){return pE.workingToColorSpace(dD.copy(this),t),e.r=dD.r,e.g=dD.g,e.b=dD.b,e}getStyle(e=jT){pE.workingToColorSpace(dD.copy(this),e);let t=dD.r,n=dD.g,r=dD.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(sD),this.setHSL(sD.h+e,sD.s+t,sD.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(sD),e.getHSL(cD);let n=nE(sD.h,cD.h,t),r=nE(sD.s,cD.s,t),i=nE(sD.l,cD.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},dD=/*@__PURE__*/ new uD;uD.NAMES=oD;var fD=class extends nD{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new zE,this.environmentIntensity=1,this.environmentRotation=new zE,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}},pD=/*@__PURE__*/ new X,mD=/*@__PURE__*/ new X,hD=/*@__PURE__*/ new X,gD=/*@__PURE__*/ new X,_D=/*@__PURE__*/ new X,vD=/*@__PURE__*/ new X,yD=/*@__PURE__*/ new X,bD=/*@__PURE__*/ new X,xD=/*@__PURE__*/ new X,SD=/*@__PURE__*/ new X,CD=/*@__PURE__*/ new wE,wD=/*@__PURE__*/ new wE,TD=/*@__PURE__*/ new wE,ED=class e{constructor(e=new X,t=new X,n=new X){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),pD.subVectors(e,t),r.cross(pD);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){pD.subVectors(r,t),mD.subVectors(n,t),hD.subVectors(e,t);let a=pD.dot(pD),o=pD.dot(mD),s=pD.dot(hD),c=mD.dot(mD),l=mD.dot(hD),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,gD)!==null&&gD.x>=0&&gD.y>=0&&gD.x+gD.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,gD)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,gD.x),s.addScaledVector(a,gD.y),s.addScaledVector(o,gD.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return CD.setScalar(0),wD.setScalar(0),TD.setScalar(0),CD.fromBufferAttribute(e,t),wD.fromBufferAttribute(e,n),TD.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(CD,i.x),a.addScaledVector(wD,i.y),a.addScaledVector(TD,i.z),a}static isFrontFacing(e,t,n,r){return pD.subVectors(n,t),mD.subVectors(e,t),pD.cross(mD).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return pD.subVectors(this.c,this.b),mD.subVectors(this.a,this.b),pD.cross(mD).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;_D.subVectors(r,n),vD.subVectors(i,n),bD.subVectors(e,n);let s=_D.dot(bD),c=vD.dot(bD);if(s<=0&&c<=0)return t.copy(n);xD.subVectors(e,r);let l=_D.dot(xD),u=vD.dot(xD);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(_D,a);SD.subVectors(e,i);let f=_D.dot(SD),p=vD.dot(SD);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(vD,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return yD.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(yD,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(_D,a).addScaledVector(vD,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},DD=class{constructor(e=new X(1/0,1/0,1/0),t=new X(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(kD.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(kD.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=kD.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,kD):kD.fromBufferAttribute(r,t),kD.applyMatrix4(e.matrixWorld),this.expandByPoint(kD);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),AD.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),AD.copy(e.boundingBox)),AD.applyMatrix4(e.matrixWorld),this.union(AD)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,kD),kD.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(LD),RD.subVectors(this.max,LD),jD.subVectors(e.a,LD),MD.subVectors(e.b,LD),ND.subVectors(e.c,LD),PD.subVectors(MD,jD),FD.subVectors(ND,MD),ID.subVectors(jD,ND);let t=[0,-PD.z,PD.y,0,-FD.z,FD.y,0,-ID.z,ID.y,PD.z,0,-PD.x,FD.z,0,-FD.x,ID.z,0,-ID.x,-PD.y,PD.x,0,-FD.y,FD.x,0,-ID.y,ID.x,0];return!VD(t,jD,MD,ND,RD)||(t=[1,0,0,0,1,0,0,0,1],!VD(t,jD,MD,ND,RD))?!1:(zD.crossVectors(PD,FD),t=[zD.x,zD.y,zD.z],VD(t,jD,MD,ND,RD))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,kD).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(kD).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(OD[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),OD[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),OD[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),OD[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),OD[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),OD[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),OD[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),OD[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(OD),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},OD=[/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X],kD=/*@__PURE__*/ new X,AD=/*@__PURE__*/ new DD,jD=/*@__PURE__*/ new X,MD=/*@__PURE__*/ new X,ND=/*@__PURE__*/ new X,PD=/*@__PURE__*/ new X,FD=/*@__PURE__*/ new X,ID=/*@__PURE__*/ new X,LD=/*@__PURE__*/ new X,RD=/*@__PURE__*/ new X,zD=/*@__PURE__*/ new X,BD=/*@__PURE__*/ new X;function VD(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){BD.fromArray(e,a);let o=i.x*Math.abs(BD.x)+i.y*Math.abs(BD.y)+i.z*Math.abs(BD.z),s=t.dot(BD),c=n.dot(BD),l=r.dot(BD);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var HD=/*@__PURE__*/ new X,UD=/*@__PURE__*/ new aE,WD=0,GD=class extends YT{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:WD++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=IT,this.updateRanges=[],this.gpuType=ww,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)UD.fromBufferAttribute(this,t),UD.applyMatrix3(e),this.setXY(t,UD.x,UD.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)HD.fromBufferAttribute(this,t),HD.applyMatrix3(e),this.setXYZ(t,HD.x,HD.y,HD.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)HD.fromBufferAttribute(this,t),HD.applyMatrix4(e),this.setXYZ(t,HD.x,HD.y,HD.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)HD.fromBufferAttribute(this,t),HD.applyNormalMatrix(e),this.setXYZ(t,HD.x,HD.y,HD.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)HD.fromBufferAttribute(this,t),HD.transformDirection(e),this.setXYZ(t,HD.x,HD.y,HD.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=rE(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=iE(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=rE(t,this.array)),t}setX(e,t){return this.normalized&&(t=iE(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=rE(t,this.array)),t}setY(e,t){return this.normalized&&(t=iE(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=rE(t,this.array)),t}setZ(e,t){return this.normalized&&(t=iE(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=rE(t,this.array)),t}setW(e,t){return this.normalized&&(t=iE(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=iE(t,this.array),n=iE(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=iE(t,this.array),n=iE(n,this.array),r=iE(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=iE(t,this.array),n=iE(n,this.array),r=iE(r,this.array),i=iE(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:`dispose`})}},KD=class extends GD{constructor(e,t,n){super(new Uint16Array(e),t,n)}},qD=class extends GD{constructor(e,t,n){super(new Uint32Array(e),t,n)}},JD=class extends GD{constructor(e,t,n){super(new Float32Array(e),t,n)}},YD=/*@__PURE__*/ new DD,XD=/*@__PURE__*/ new X,ZD=/*@__PURE__*/ new X,QD=class{constructor(e=new X,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?YD.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;XD.subVectors(e,this.center);let t=XD.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(XD,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(ZD.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(XD.copy(e.center).add(ZD)),this.expandByPoint(XD.copy(e.center).sub(ZD))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},$D=0,eO=/*@__PURE__*/ new kE,tO=/*@__PURE__*/ new nD,nO=/*@__PURE__*/ new X,rO=/*@__PURE__*/ new DD,iO=/*@__PURE__*/ new DD,aO=/*@__PURE__*/ new X,oO=class e extends YT{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:$D++}),this.uuid=$T(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(zT(e)?qD:KD)(e,1):e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new Z().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return eO.makeRotationFromQuaternion(e),this.applyMatrix4(eO),this}rotateX(e){return eO.makeRotationX(e),this.applyMatrix4(eO),this}rotateY(e){return eO.makeRotationY(e),this.applyMatrix4(eO),this}rotateZ(e){return eO.makeRotationZ(e),this.applyMatrix4(eO),this}translate(e,t,n){return eO.makeTranslation(e,t,n),this.applyMatrix4(eO),this}scale(e,t,n){return eO.makeScale(e,t,n),this.applyMatrix4(eO),this}lookAt(e){return tO.lookAt(e),tO.updateMatrix(),this.applyMatrix4(tO.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(nO).negate(),this.translate(nO.x,nO.y,nO.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new JD(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&J(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new DD);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Y(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new X(-1/0,-1/0,-1/0),new X(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];rO.setFromBufferAttribute(n),this.morphTargetsRelative?(aO.addVectors(this.boundingBox.min,rO.min),this.boundingBox.expandByPoint(aO),aO.addVectors(this.boundingBox.max,rO.max),this.boundingBox.expandByPoint(aO)):(this.boundingBox.expandByPoint(rO.min),this.boundingBox.expandByPoint(rO.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Y(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new QD);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Y(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new X,1/0);return}if(e){let n=this.boundingSphere.center;if(rO.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];iO.setFromBufferAttribute(n),this.morphTargetsRelative?(aO.addVectors(rO.min,iO.min),rO.expandByPoint(aO),aO.addVectors(rO.max,iO.max),rO.expandByPoint(aO)):(rO.expandByPoint(iO.min),rO.expandByPoint(iO.max))}rO.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)aO.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(aO));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)aO.fromBufferAttribute(a,t),o&&(nO.fromBufferAttribute(e,t),aO.add(nO)),r=Math.max(r,n.distanceToSquared(aO))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&Y(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){Y(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv,a=this.getAttribute(`tangent`);(a===void 0||a.count!==n.count)&&(a=new GD(new Float32Array(4*n.count),4),this.setAttribute(`tangent`,a));let o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new X,s[e]=new X;let c=new X,l=new X,u=new X,d=new aE,f=new aE,p=new aE,m=new X,h=new X;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new X,y=new X,b=new X,x=new X;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0||n.count!==t.count)n=new GD(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new X,i=new X,a=new X,o=new X,s=new X,c=new X,l=new X,u=new X;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)aO.fromBufferAttribute(e,t),aO.normalize(),e.setXYZ(t,aO.x,aO.y,aO.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new GD(a,r,i)}if(this.index===null)return J(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?`BufferGeometry`:this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:`dispose`})}},sO=/*@__PURE__*/ new X,cO=/*@__PURE__*/ new X,lO=/*@__PURE__*/ new Z,uO=class{constructor(e=new X(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=sO.subVectors(n,t).cross(cO.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(sO),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||lO.getNormalMatrix(e),r=this.coplanarPoint(sO).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}},dO=0,fO=class extends YT{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:dO++}),this.uuid=$T(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new uD(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=FT,this.stencilZFail=FT,this.stencilZPass=FT,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){J(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){J(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new uD().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(e=>new uO().fromJSON(e))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new aE().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new aE().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},pO=/*@__PURE__*/ new X,mO=/*@__PURE__*/ new X,hO=/*@__PURE__*/ new X,gO=/*@__PURE__*/ new X,_O=class{constructor(e=new X,t=new X(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,pO)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=pO.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(pO.copy(this.origin).addScaledVector(this.direction,t),pO.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){mO.copy(e).add(t).multiplyScalar(.5),hO.copy(t).sub(e).normalize(),gO.copy(this.origin).sub(mO);let i=e.distanceTo(t)*.5,a=-this.direction.dot(hO),o=gO.dot(this.direction),s=-gO.dot(hO),c=gO.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(mO).addScaledVector(hO,d),f}intersectSphere(e,t){if(e.radius<0)return null;pO.subVectors(e.center,this.origin);let n=pO.dot(this.direction),r=pO.dot(pO)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,pO)!==null}intersectTriangle(e,t,n,r,i){let a=this.origin,o=this.direction,s=o.x,c=o.y,l=o.z,u=e.x-a.x,d=e.y-a.y,f=e.z-a.z,p=t.x-a.x,m=t.y-a.y,h=t.z-a.z,g=n.x-a.x,_=n.y-a.y,v=n.z-a.z,y=Math.abs(s),b=Math.abs(c),x=Math.abs(l),S,C,w,T,E,D,O,ee,k,te,ne,A;if(y>=b&&y>=x?(w=s,D=u,k=p,A=g,s>=0?(S=c,C=l,T=d,E=f,O=m,ee=h,te=_,ne=v):(S=l,C=c,T=f,E=d,O=h,ee=m,te=v,ne=_)):b>=x?(w=c,D=d,k=m,A=_,c>=0?(S=l,C=s,T=f,E=u,O=h,ee=p,te=v,ne=g):(S=s,C=l,T=u,E=f,O=p,ee=h,te=g,ne=v)):(w=l,D=f,k=h,A=v,l>=0?(S=s,C=c,T=u,E=d,O=p,ee=m,te=g,ne=_):(S=c,C=s,T=d,E=u,O=m,ee=p,te=_,ne=g)),w===0)return null;let re=S/w,ie=C/w,ae=1/w,oe=T-re*D,j=E-ie*D,se=O-re*k,ce=ee-ie*k,le=te-re*A,ue=ne-ie*A,de=le*ce-ue*se,fe=oe*ue-j*le,pe=se*j-ce*oe;if(r){if(de<0||fe<0||pe<0)return null}else if((de<0||fe<0||pe<0)&&(de>0||fe>0||pe>0))return null;let me=de+fe+pe;if(me===0)return null;let he=ae*(de*D+fe*k+pe*A);return(me>0?he<0:he>0)?null:this.at(he/me,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},vO=class extends fO{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new uD(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new zE,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},yO=/*@__PURE__*/ new kE,bO=/*@__PURE__*/ new _O,xO=/*@__PURE__*/ new QD,SO=/*@__PURE__*/ new X,CO=/*@__PURE__*/ new X,wO=/*@__PURE__*/ new X,TO=/*@__PURE__*/ new X,EO=/*@__PURE__*/ new X,DO=/*@__PURE__*/ new X,OO=/*@__PURE__*/ new X,kO=/*@__PURE__*/ new X,AO=class extends nD{constructor(e=new oO,t=new vO){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){DO.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(EO.fromBufferAttribute(s,e),a?DO.addScaledVector(EO,r):DO.addScaledVector(EO.sub(t),r))}t.add(DO)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),xO.copy(n.boundingSphere),xO.applyMatrix4(i),bO.copy(e.ray).recast(e.near),!(xO.containsPoint(bO.origin)===!1&&(bO.intersectSphere(xO,SO)===null||bO.origin.distanceToSquared(SO)>(e.far-e.near)**2))&&(yO.copy(i).invert(),bO.copy(e.ray).applyMatrix4(yO),(n.boundingBox===null||bO.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,bO)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=MO(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=MO(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}}else if(s!==void 0){if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=MO(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=MO(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}}};function jO(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;kO.copy(s),kO.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(kO);return l<n.near||l>n.far?null:{distance:l,point:kO.clone(),object:e}}function MO(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,CO),e.getVertexPosition(c,wO),e.getVertexPosition(l,TO);let u=jO(e,t,n,r,CO,wO,TO,OO);if(u){let e=new X;ED.getBarycoord(OO,CO,wO,TO,e),i&&(u.uv=ED.getInterpolatedAttribute(i,s,c,l,e,new aE)),a&&(u.uv1=ED.getInterpolatedAttribute(a,s,c,l,e,new aE)),o&&(u.normal=ED.getInterpolatedAttribute(o,s,c,l,e,new X),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new X,materialIndex:0};ED.getNormal(CO,wO,TO,t.normal),u.face=t,u.barycoord=e}return u}var NO=class extends CE{constructor(e=null,t=1,n=1,r,i,a,o,s,c=fw,l=fw,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},PO=/*@__PURE__*/ new QD,FO=/*@__PURE__*/ new aE(.5,.5),IO=/*@__PURE__*/ new X,LO=class{constructor(e=new uO,t=new uO,n=new uO,r=new uO,i=new uO,a=new uO){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=RT,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),PO.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),PO.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(PO)}intersectsSprite(e){return PO.center.set(0,0,0),PO.radius=.7071067811865476+FO.distanceTo(e.center),PO.applyMatrix4(e.matrixWorld),this.intersectsSphere(PO)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(IO.x=r.normal.x>0?e.max.x:e.min.x,IO.y=r.normal.y>0?e.max.y:e.min.y,IO.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(IO)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},RO=class extends CE{constructor(e,t,n,r,i=hw,a=hw,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;let l=this;function u(){l.needsUpdate=!0,l._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u)}`requestVideoFrameCallback`in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u))}clone(){return new this.constructor(this.image).copy(this)}update(){let e=this.image;!(`requestVideoFrameCallback`in e)&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}},zO=class extends RO{constructor(e,t,n,r,i,a,o,s){super({},e,t,n,r,i,a,o,s),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}},BO=class extends CE{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},VO=class extends CE{constructor(e,t,n=Cw,r,i,a,o=fw,s=fw,c,l=Pw,u=1){if(l!==1026&&l!==1027)throw Error(`THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new yE(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},HO=class extends VO{constructor(e,t=Cw,n=301,r,i,a=fw,o=fw,s,c=Pw){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},UO=class extends CE{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},WO=class e extends oO{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new JD(c,3)),this.setAttribute(`normal`,new JD(l,3)),this.setAttribute(`uv`,new JD(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new X;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}},GO=class e extends oO{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new JD(p,3)),this.setAttribute(`normal`,new JD(m,3)),this.setAttribute(`uv`,new JD(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}};function KO(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(JO(i))i.isRenderTargetTexture?(J(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone();else if(Array.isArray(i)){if(JO(i[0])){let e=[];for(let t=0,n=i.length;t<n;t++)e[t]=i[t].clone();t[n][r]=e}else t[n][r]=i.slice()}else t[n][r]=i}}return t}function qO(e){let t={};for(let n=0;n<e.length;n++){let r=KO(e[n]);for(let e in r)t[e]=r[e]}return t}function JO(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function YO(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function XO(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:pE.workingColorSpace}var ZO={clone:KO,merge:qO},QO=`void main() {
|
|
3
|
+
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e=>e,n=e=>e,r=90,i=180,a=360,o=t(r),s=t(i),c=t(a),l=e=>n(e*Math.PI/i),u=e=>t(e*i/Math.PI);function d(e){let n=e%c;return n>s&&(n-=c),n<=-s&&(n+=c),t(n)}var f={EdgeRadius:0,CenterX:1,CenterY:2,Yaw:3,Pitch:4,Roll:5},p={EdgeRadius:0,CenterX:1,CenterY:2,Yaw:3,Pitch:4,Roll:5,TranslationX:6,TranslationY:7,TranslationZ:8,C1:9,C2:10,C3:11,C4:12,CanvasWidth:13,CanvasHeight:14,LensType:15},m={Xi:0,FocalX:1,FocalY:2,CenterX:3,CenterY:4,Yaw:5,Pitch:6,Roll:7,TranslationX:8,TranslationY:9,TranslationZ:10},h={K1:11,K2:12,K3:13,P1:14,P2:15,CanvasWidth:16,CanvasHeight:17,LensType:18},g={K1:11,K2:12,K3:13,K4:14,K5:15,P1:16,P2:17,P3:18,P4:19,S1:20,S2:21,S3:22,S4:23,CanvasWidth:24,CanvasHeight:25,LensType:26},_={CanvasWidth:0,CanvasHeight:1,VersionWord:2};function v(e,n,r){return{yaw:t(e),pitch:t(n),roll:t(r)}}function y(e,t){let n=e>>>16;return n===t?void 0:`declares version ${n}`}function b(e,t,n){let[r]=e;return r?{width:r(t),height:r(n)}:x}var x={width:0,height:0};function S(e){let[t,r,i]=e,a=Math.hypot(t,r);return{theta:n(Math.atan2(a,i)),radialUnit:a===0?[0,0]:[t/a,r/a]}}function C(e,t,n){return{x:e.x+t*n[0],y:e.y+t*n[1]}}var w=l(t(100)),T=l(t(96)),E=class{parameters;kind=`equidistant`;halfFieldOfView=w;principalPoint;constructor(e){this.parameters=e,this.principalPoint=e.principalPoint}get projection(){return{kind:`radial-polynomial`,principalPoint:this.principalPoint,coefficients:[this.pixelsPerRadian,0,0,0]}}project(e){let{theta:t,radialUnit:n}=S(e);return t>this.halfFieldOfView?void 0:C(this.principalPoint,this.pixelsPerRadian*t,n)}get pixelsPerRadian(){return this.parameters.edgeRadius/this.parameters.radiusAngle}},D={Legacy:1,Polynomial:2,Mei:3,ExtendedMei:6},O={version:D.Legacy,lensTokens:6,trailingTokens:3,radialScale:1,parseLens(e,t){return{lensIndex:t,model:new E({edgeRadius:e(f.EdgeRadius),radiusAngle:T,principalPoint:{x:e(f.CenterX),y:e(f.CenterY)}}),orientation:v(e(f.Yaw),e(f.Pitch),e(f.Roll)),translation:[0,0,0]}},canvasOf(e){let t=1+(e[0]??0)*6;return{width:e[t+_.CanvasWidth]??0,height:e[t+_.CanvasHeight]??0}}},k=/* @__PURE__ */ `binary-out-of-bounds.binary-unsafe-integer.codec-unsupported.cors.decode.embed-destroyed.index-out-of-range.invalid-argument.invalid-byte-range.invalid-calibration.invalid-protobuf.invalid-trailer.invariant-violation.missing-second-file.no-calibration.no-info-record.no-key-frame.playback-blocked.range-unsupported.render-unavailable.source-changed.source-truncated.source-unreadable.unsupported-calibration.unsupported-container.unsupported-gyro-record.unsupported-info-format.unsupported-layout.webcodecs-unavailable`.split(`.`),A=[`browser`,`recording`,`source`,`usage`,`internal`],ee={"binary-out-of-bounds":`recording`,"binary-unsafe-integer":`recording`,"codec-unsupported":`browser`,cors:`source`,decode:`browser`,"embed-destroyed":`usage`,"index-out-of-range":`internal`,"invalid-argument":`usage`,"invalid-byte-range":`recording`,"invalid-calibration":`recording`,"invalid-protobuf":`recording`,"invalid-trailer":`recording`,"invariant-violation":`internal`,"missing-second-file":`recording`,"no-calibration":`recording`,"no-info-record":`recording`,"no-key-frame":`recording`,"playback-blocked":`browser`,"range-unsupported":`source`,"render-unavailable":`browser`,"source-changed":`source`,"source-truncated":`source`,"source-unreadable":`source`,"unsupported-calibration":`recording`,"unsupported-container":`recording`,"unsupported-gyro-record":`recording`,"unsupported-info-format":`recording`,"unsupported-layout":`recording`,"webcodecs-unavailable":`browser`};function te(e){return typeof e==`string`&&k.includes(e)}var j=class extends Error{code;category;constructor(e,t,n){super(t,n),this.code=e,this.name=`GyroViewError`,this.category=ee[e]}};function ne(e,t,n){return e instanceof j?e:new j(t,n,{cause:e})}function re(e){return e instanceof Error&&e.name===`AbortError`}function M(e,t){return e instanceof j&&e.code===t}function ie(e){return e instanceof Error?e.message:String(e)}function N(e,t){if(!e)throw new j(`invariant-violation`,t)}function ae(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>=t)throw new j(`index-out-of-range`,`${n} index ${e} is outside 0..${t-1}`)}var oe={radial:5,tangential:2,thinPrism:2};function se(e){ce(`radial`,e.radial.length),ce(`tangential`,e.tangential.length),ce(`thinPrism`,e.thinPrism.length)}function ce(e,t){let n=oe[e];N(t<=n,`a Mei distortion has ${t} ${e} terms, more than the ${n} a string carries`)}function le(e,t){let[n,r]=t,i=n*n+r*r,a=1+i*ue(i,e.radial,e=>e),o=ue(i,e.tangential,e=>e.p1),s=ue(i,e.tangential,e=>e.p2),c=i*ue(i,e.thinPrism,e=>e.x),l=i*ue(i,e.thinPrism,e=>e.y);return[a*n+2*o*n*r+s*(i+2*n*n)+c,a*r+o*(i+2*r*r)+2*s*n*r+l]}function ue(e,t,n){return t.reduceRight((t,r)=>t*e+n(r),0)}var de=class{parameters;kind=`mei`;halfFieldOfView=w;principalPoint;constructor(e){this.parameters=e,se(e.distortion),this.principalPoint=e.principalPoint}get projection(){return{kind:`mei`,...this.parameters}}project(e){let[t,n,r]=e,i=r+this.parameters.xi;if(i<=0||Math.atan2(Math.hypot(t,n),r)>this.halfFieldOfView)return;let[a,o]=le(this.parameters.distortion,[t/i,n/i]);return{x:this.parameters.focal[0]*a+this.principalPoint.x,y:this.parameters.focal[1]*o+this.principalPoint.y}}},fe=({radial:e,tangential:t})=>{let[n,r]=t;return{radial:e,tangential:[{p1:n,p2:r}],thinPrism:[]}};function pe(e){return{version:e.version,lensTokens:e.lensTokens,trailingTokens:1,radialScale:e.radialScale,versionWordProblem:t=>y(t,e.version),parseLens:(t,n)=>me(t,n,e),canvasOf:(t,n)=>b(n,e.canvasTokens.width,e.canvasTokens.height)}}function me(e,t,n){return{lensIndex:t,model:new de({xi:e(m.Xi),focal:[e(m.FocalX),e(m.FocalY)],principalPoint:{x:e(m.CenterX),y:e(m.CenterY)},distortion:n.distortionOf(e)}),orientation:v(e(m.Yaw),e(m.Pitch),e(m.Roll)),translation:[e(m.TranslationX),e(m.TranslationY),e(m.TranslationZ)]}}var he=pe({version:D.Mei,lensTokens:19,canvasTokens:{width:h.CanvasWidth,height:h.CanvasHeight},distortionOf:e=>({radial:[e(h.K1),e(h.K2),e(h.K3)],tangential:[{p1:e(h.P1),p2:e(h.P2)}],thinPrism:[]}),radialScale:1}),ge=1.008;function _e(e){return pe({version:D.ExtendedMei,lensTokens:27,canvasTokens:{width:g.CanvasWidth,height:g.CanvasHeight},distortionOf:t=>e(ye(t)),radialScale:ge})}var ve=_e(fe);function ye(e){return{radial:[e(g.K1),e(g.K2),e(g.K3),e(g.K4),e(g.K5)],tangential:[e(g.P1),e(g.P2),e(g.P3),e(g.P4)],thinPrism:[e(g.S1),e(g.S2),e(g.S3),e(g.S4)]}}var be=class{parameters;kind=`polynomial`;halfFieldOfView=w;principalPoint;scale;constructor(e){this.parameters=e,this.principalPoint=e.principalPoint,this.scale=e.edgeRadius/this.polynomial(this.halfFieldOfView)}get projection(){let[e,t,n,r]=this.parameters.coefficients;return{kind:`radial-polynomial`,principalPoint:this.principalPoint,coefficients:[e*this.scale,t*this.scale,n*this.scale,r*this.scale]}}project(e){let{theta:t,radialUnit:n}=S(e);return t>this.halfFieldOfView?void 0:C(this.principalPoint,this.scale*this.polynomial(t),n)}polynomial(e){let[t,n,r,i]=this.parameters.coefficients;return e*(t+e*(n+e*(r+e*i)))}},xe={version:D.Polynomial,lensTokens:16,trailingTokens:1,radialScale:1,versionWordProblem:e=>y(e,D.Polynomial),parseLens(e,t){return{lensIndex:t,model:new be({edgeRadius:e(p.EdgeRadius),principalPoint:{x:e(p.CenterX),y:e(p.CenterY)},coefficients:[e(p.C1),e(p.C2),e(p.C3),e(p.C4)]}),orientation:v(e(p.Yaw),e(p.Pitch),e(p.Roll)),translation:[e(p.TranslationX),e(p.TranslationY),e(p.TranslationZ)]}},canvasOf(e,t){return b(t,p.CanvasWidth,p.CanvasHeight)}},Se=`_`,Ce=[O,xe,he,ve];function P(e,t=Ce){let n=e.split(Se).map(e=>De(e)),r=n[0]??0,i=Te(t,n);Ee(i,n.at(-1)??0);let a=Array.from({length:r},(e,t)=>F(n,1+t*i.lensTokens));return{version:i.version,canvas:i.canvasOf(n,a),lenses:a.map((e,t)=>i.parseLens(e,t)),radialScale:i.radialScale}}function we(e,t,n){return 1+e*t+n}function Te(e,t){let n=t[0]??0,r=e.find(e=>t.length===we(n,e.lensTokens,e.trailingTokens));if(r)return r;throw new j(`invalid-calibration`,`calibration string has ${t.length} tokens for ${n} lenses, matching no known layout`)}function Ee(e,t){let n=e.versionWordProblem?.(t);if(n!==void 0)throw new j(`invalid-calibration`,`calibration string has the v${e.version} layout but ${n}`)}function F(e,t){return n=>e[t+n]??NaN}function De(e){let t=Number(e);if(e.trim()===``||!Number.isFinite(t))throw new j(`invalid-calibration`,`calibration token "${e}" is not a finite number`);return t}var I={SerialNumber:1,Model:2,Firmware:3,Offset:5,Dimension:19,FrameRate:20,CaptureMode:22,FirstFrameTimestamp:24,RollingShutterTimeMs:25,FileGroupInfo:26,WindowCropInfo:27,GyroTimestampMs:28,HasGyroTimestamp:29,TotalFrames:40,IsFlowstateOnline:42,GyroType:51,OffsetV2:53,OffsetV3:54,IsRawGyro:62,PtsType:64,GyroConfig:65,FileLayout:79,TrackOrder:80,OffsetV6:111},L={Width:1,Height:2},Oe={AccelerometerRangeG:1,GyroscopeRangeDps:2},ke={SensorWidth:1,SensorHeight:2,CropWidth:3,CropHeight:4,CropOffsetX:5,CropOffsetY:6},Ae={TrackTimestamps:1,ExposureRecord:2},je={SplitFiles:1,MultiTrack:2},Me={Stream10First:1,Stream00First:2},Ne={offset:{field:I.Offset,name:`offset`},offsetV2:{field:I.OffsetV2,name:`offset_v2`},offsetV3:{field:I.OffsetV3,name:`offset_v3`},offsetV6:{field:I.OffsetV6,name:`offset_v6`}},Pe=/* @__PURE__ */ new Set([`invalid-calibration`,`unsupported-calibration`]),Fe=[`offset`,`offsetV6`,`offsetV3`,`offsetV2`];function Ie(e){let t=[];for(let n of Le(e)){if(`calibration`in n)return{calibration:n.calibration,warnings:t};t.push(n.warning)}return{calibration:void 0,warnings:t}}function*Le(e){for(let t of Fe){let n=e[t];n!==void 0&&(yield Re(Ne[t],n))}}function Re({name:e},t){try{return{calibration:P(t)}}catch(t){if(t instanceof j&&Pe.has(t.code))return{warning:`${e} skipped: ${t.message}`};throw t}}var ze={Index:0,Info:1,Thumbnail:2,Gyro:3,Exposure:4,ThumbnailExtended:5,FrameTimestamps:6,Gps:7},Be={Protobuf:1,Json:2},Ve=1,He=2,Ue=4,We=8,Ge=4,Ke=8,qe=8,Je=!0,Ye=!1,Xe=BigInt(-(2**53-1)),Ze=BigInt(2**53-1),Qe=class{bytes;view;constructor(e){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}get length(){return this.bytes.byteLength}uint8At(e){return this.ensureAvailable(e,Ve),this.view.getUint8(e)}uint16LeAt(e){return this.ensureAvailable(e,He),this.view.getUint16(e,Je)}uint32LeAt(e){return this.ensureAvailable(e,Ue),this.view.getUint32(e,Je)}uint32BeAt(e){return this.ensureAvailable(e,Ue),this.view.getUint32(e,Ye)}int32BeAt(e){return this.ensureAvailable(e,Ge),this.view.getInt32(e,Ye)}uint64LeAt(e){return this.ensureAvailable(e,We),this.toSafeNumber(this.view.getBigUint64(e,Je),e)}uint64BeAt(e){return this.ensureAvailable(e,We),this.toSafeNumber(this.view.getBigUint64(e,Ye),e)}int64BeAt(e){return this.ensureAvailable(e,Ke),this.toSafeNumber(this.view.getBigInt64(e,Ye),e)}float64LeAt(e){return this.ensureAvailable(e,qe),this.view.getFloat64(e,Je)}bytesAt(e,t){return this.ensureAvailable(e,t),this.bytes.subarray(e,e+t)}asciiAt(e,t){return Array.from(this.bytesAt(e,t),e=>String.fromCodePoint(e)).join(``)}toSafeNumber(e,t){if(!(e>=Xe&&e<=Ze))throw new j(`binary-unsafe-integer`,`64-bit integer at offset ${t} (${e.toString()}) exceeds the safe integer range`);return Number(e)}ensureAvailable(e,t){if(e<0||t<0||e+t>this.bytes.byteLength)throw new j(`binary-out-of-bounds`,`read of ${t} byte(s) at offset ${e} exceeds ${this.bytes.byteLength} available`)}};function $e(e){let t;return()=>(t??={value:e()}).value}var et=$e(()=>new globalThis.TextDecoder(`utf8`));function tt(e){return et().decode(e)}var nt={Varint:0,Fixed64:1,LengthDelimited:2,Fixed32:5},rt=BigInt(7),it=BigInt(127),at=BigInt(2**53-1),ot=class e{decoded;constructor(e){this.decoded=e}static decode(t){let n=new st(t),r=[];for(;!n.atEnd;)r.push(n.readField());return new e(r)}varint(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`varint`)throw this.wrongType(e,`varint`,t.kind);if(t.value>at)throw new j(`binary-unsafe-integer`,`field ${e} holds ${t.value.toString()}, beyond the safe integer range`);return Number(t.value)}}boolean(e){let t=this.varint(e);return t===void 0?void 0:t!==0}double(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`fixed64`)throw this.wrongType(e,`fixed64`,t.kind);return new Qe(t.bytes).float64LeAt(0)}}bytes(e){let t=this.valueOf(e);if(t!==void 0){if(t.kind!==`bytes`)throw this.wrongType(e,`bytes`,t.kind);return t.bytes}}string(e){let t=this.bytes(e);return t===void 0?void 0:tt(t)}message(t){let n=this.bytes(t);return n===void 0?void 0:e.decode(n)}valueOf(e){return this.decoded.findLast(t=>t.number===e)?.value}wrongType(e,t,n){return new j(`invalid-protobuf`,`field ${e} is encoded as ${n}, expected ${t}`)}},st=class{bytes;position=0;reader;constructor(e){this.bytes=e,this.reader=new Qe(e)}get atEnd(){return this.position>=this.bytes.byteLength}readField(){let e=this.readVarint(),t=Number(e>>BigInt(3)),n=Number(e&BigInt(7));return{number:t,value:this.readValue(n,t)}}readValue(e,t){switch(e){case nt.Varint:return{kind:`varint`,value:this.readVarint()};case nt.Fixed64:return{kind:`fixed64`,bytes:this.readBytes(8)};case nt.Fixed32:return{kind:`fixed32`,bytes:this.readBytes(4)};case nt.LengthDelimited:return{kind:`bytes`,bytes:this.readBytes(this.readLength())};default:throw new j(`invalid-protobuf`,`field ${t} uses unsupported wire type ${e}`)}}readVarint(){let e=0n,t=0n;for(let n=0;n<10;n+=1){let n=this.readByte();if(e|=(BigInt(n)&it)<<t,!(n&128))return e;t+=rt}throw new j(`invalid-protobuf`,`varint longer than 10 bytes at byte ${this.position}`)}readLength(){let e=this.readVarint();if(e>BigInt(this.bytes.byteLength))throw new j(`invalid-protobuf`,`length ${e.toString()} exceeds the message at byte ${this.position}`);return Number(e)}readByte(){this.ensureRemaining(1);let e=this.reader.uint8At(this.position);return this.position+=1,e}readBytes(e){this.ensureRemaining(e);let t=this.reader.bytesAt(this.position,e);return this.position+=e,t}ensureRemaining(e){if(this.position+e>this.bytes.byteLength)throw new j(`invalid-protobuf`,`message truncated at byte ${this.position}`)}};function ct(e,t){let n=Object.entries(e).map(([e,n])=>[e,t(n,e)]);return Object.fromEntries(n)}var lt=1e6,ut=1e3,dt=1e3,ft=e=>e,pt=e=>e,R=e=>e,mt=e=>R(e/lt),ht=e=>ft(e*dt),gt=e=>R(e/ut),_t=e=>ft(e*lt);function vt(e,t){if(t!==Be.Protobuf)throw new j(`unsupported-info-format`,`info record uses format ${t}; only protobuf (${Be.Protobuf}) is supported`);let n=ot.decode(e);return{serialNumber:n.string(I.SerialNumber),model:n.string(I.Model),firmware:n.string(I.Firmware),calibration:Tt(n),dimension:Et(n.message(I.Dimension)),frameRate:n.varint(I.FrameRate),captureMode:n.string(I.CaptureMode),firstFrameTimestamp:n.varint(I.FirstFrameTimestamp),readoutTime:yt(n.double(I.RollingShutterTimeMs)),windowCrop:Dt(n.message(I.WindowCropInfo)),gyroOffset:bt(n),gyroType:n.varint(I.GyroType),isRawGyro:n.boolean(I.IsRawGyro),preferredFrameTimeSource:St(n.varint(I.PtsType)),sensorRanges:Ot(n.message(I.GyroConfig)),fileLayout:Ct(n.varint(I.FileLayout)),trackOrder:wt(n.varint(I.TrackOrder))}}function yt(e){return e===void 0?void 0:gt(pt(e))}function bt(e){return e.boolean(I.HasGyroTimestamp)===!0?xt(e.double(I.GyroTimestampMs)):void 0}function xt(e){return e===void 0?void 0:pt(e)}function St(e){return e===Ae.TrackTimestamps?`track-timestamps`:e===Ae.ExposureRecord?`exposure-record`:void 0}function Ct(e){return e===je.SplitFiles?`split-files`:e===je.MultiTrack?`multi-track`:void 0}function wt(e){return e===Me.Stream10First?`stream-10-first`:e===Me.Stream00First?`stream-00-first`:void 0}function Tt(e){return ct(Ne,t=>e.string(t.field))}function Et(e){let t=e?.varint(L.Width),n=e?.varint(L.Height);return t===void 0||n===void 0?void 0:{width:t,height:n}}function Dt(e){return e===void 0?void 0:{sensorWidth:e.varint(ke.SensorWidth),sensorHeight:e.varint(ke.SensorHeight),cropWidth:e.varint(ke.CropWidth),cropHeight:e.varint(ke.CropHeight),cropOffsetX:e.varint(ke.CropOffsetX),cropOffsetY:e.varint(ke.CropOffsetY)}}function Ot(e){return e===void 0?void 0:{accelerometerG:e.varint(Oe.AccelerometerRangeG),gyroscopeDps:e.varint(Oe.GyroscopeRangeDps)}}async function kt(e,t){let n=t.locationOf(ze.Info);if(!n)throw new j(`no-info-record`,`the trailer has no info record; the file is not a camera recording`);return vt(await e.read(n.payload),n.format)}var At=class e{captureTimeStore;shutterTimeStore;constructor(e,t){this.captureTimeStore=e,this.shutterTimeStore=t,N(e.length===t.length,`exposure record arrays disagree on the entry count`)}get length(){return this.captureTimeStore.length}get captureTimes(){return this.captureTimeStore}get shutterTimes(){return this.shutterTimeStore}entryAt(e){return ae(e,this.length,`exposure entry`),{captureTime:ft(this.captureTimeStore[e]??0),shutterTime:R(this.shutterTimeStore[e]??0)}}indexAtOrAfter(e){let t=0,n=this.captureTimeStore.length;for(;t<n;){let r=t+n>>>1;(this.captureTimeStore[r]??1/0)<e?t=r+1:n=r}return t}slice(t,n){return N(t>=0&&n>=0&&t+n<=this.length,`exposure slice out of range`),new e(this.captureTimeStore.slice(t,t+n),this.shutterTimeStore.slice(t,t+n))}},jt=60;function Mt(e,t){try{return Nt(e,t)}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function Nt(e,t){let n=Math.floor(e.byteLength/16),r=new Qe(e),i=new Float64Array(n),a=new Float64Array(n);for(let e=0;e<n;e+=1){let n=e*16;i[e]=t(r.uint64LeAt(n+0)),a[e]=r.float64LeAt(n+8)}return Pt(i)&&a.every(e=>Ft(e))?new At(i,a):void 0}function Pt(e){return e.every((t,n)=>n===0||t>=(e[n-1]??t))}function Ft(e){return e>=0&&e<=jt}var It=32768,Lt=32768,Rt=[Lt,Lt/2],zt=2e3,Bt=class{name=`float`;sampleSize=56;flipSteps={acceleration:[],angularVelocity:[]};captureTimeOf(e){return ht(pt(e))}timestampAt(e,t){return this.captureTimeOf(e.uint64LeAt(t+0))}accelerationAt(e,t){return this.vectorAt(e,t+8)}angularVelocityAt(e,t){return this.vectorAt(e,t+32)}vectorAt(e,t){return[e.float64LeAt(t),e.float64LeAt(t+8),e.float64LeAt(t+16)]}},Vt=class{name=`raw`;sampleSize=20;flipSteps;accelerationScale;angularVelocityScale;constructor(e={}){let n=Ht(e.accelerometerG,16),r=Ht(e.gyroscopeDps,zt);this.accelerationScale=n/Lt,this.angularVelocityScale=l(t(r))/Lt,this.flipSteps={acceleration:Rt.map(e=>e*this.accelerationScale),angularVelocity:Rt.map(e=>e*this.angularVelocityScale)}}captureTimeOf(e){return ft(e)}timestampAt(e,t){return this.captureTimeOf(e.uint64LeAt(t+0))}accelerationAt(e,t){return this.vectorAt(e,t+8,this.accelerationScale)}angularVelocityAt(e,t){return this.vectorAt(e,t+14,this.angularVelocityScale)}vectorAt(e,t,n){return[this.componentAt(e,t,n),this.componentAt(e,t+2,n),this.componentAt(e,t+4,n)]}componentAt(e,t,n){return(e.uint16LeAt(t)-It)*n}};function Ht(e,t){return e!==void 0&&e>0?e:t}var Ut=[0,0,0];function Wt(e){return Math.sqrt(Gt(e,e))}function Gt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function Kt(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function qt(e){return e.every(e=>Number.isFinite(e))}function Jt(e,t){return[e[0]+t[0],e[1]+t[1],e[2]+t[2]]}function Yt(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function Xt(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Zt(e,t,n){return Jt(e,Xt(Yt(t,e),n))}var Qt=class{captureTimeStore;accelerationStore;angularVelocityStore;constructor(e,t,n){this.captureTimeStore=e,this.accelerationStore=t,this.angularVelocityStore=n;let r=e.length*3;N(t.length===r&&n.length===r,`gyro track arrays disagree on the sample count`),N($t(e),`gyro sample times go back`)}get length(){return this.captureTimeStore.length}get isEmpty(){return this.captureTimeStore.length===0}get captureTimes(){return this.captureTimeStore}get meanSampleInterval(){return this.length<2?void 0:ft(((this.captureTimeStore[this.length-1]??0)-(this.captureTimeStore[0]??0))/(this.length-1))}sampleAt(e){return ae(e,this.length,`gyro sample`),{captureTime:ft(this.captureTimeStore[e]??0),acceleration:this.vectorAt(this.accelerationStore,e),angularVelocity:this.vectorAt(this.angularVelocityStore,e)}}angularVelocityAt(e){return ae(e,this.length,`gyro sample`),this.vectorAt(this.angularVelocityStore,e)}vectorAt(e,t){let n=t*3;return[e[n]??NaN,e[n+1]??NaN,e[n+2]??NaN]}};function $t(e){return e.every((t,n)=>n===0||t>=(e[n-1]??t))}var en=16,tn=class{length=0;recordedTimes;accelerations;angularVelocities;constructor(e){this.recordedTimes=new Float64Array(e),this.accelerations=new Float32Array(e*3),this.angularVelocities=new Float32Array(e*3)}push(e){let t=this.length*3;this.recordedTimes[this.length]=e.captureTime;for(let n=0;n<3;n+=1)this.accelerations[t+n]=e.acceleration[n]??NaN,this.angularVelocities[t+n]=e.angularVelocity[n]??NaN;this.length+=1}dropFlippedBits(e){let t=0;for(let n=0;n<this.length;n+=1)this.isFlippedAt(n,e)||(this.moveSample(n,t),t+=1);this.length=t}captureTimes(){return this.recordedTimes.subarray(0,this.length)}toTrack(e){let t=this.length*3;return new Qt(e,this.accelerations.subarray(0,t),this.angularVelocities.subarray(0,t))}isFlippedAt(e,t){return e>0&&e<this.length-1&&(nn(this.accelerations,e,t.acceleration)||nn(this.angularVelocities,e,t.angularVelocity))}moveSample(e,t){if(e!==t){this.recordedTimes[t]=this.recordedTimes[e]??0;for(let n of[this.accelerations,this.angularVelocities])n.copyWithin(t*3,e*3,(e+1)*3)}}};function nn(e,t,n){for(let r=0;r<3;r+=1)if(rn(e,t*3+r,n))return!0;return!1}function rn(e,t,n){let r=e[t-3]??0,i=e[t+3]??0,a=Math.abs((e[t]??0)-(r+i)/2),o=Math.abs(r-i);for(let e of n){let t=e/en;if(o<=t&&Math.abs(a-e)<=t)return!0}return!1}function an(e){let t=e.subarray(1).map((t,n)=>t-(e[n]??t)).toSorted();return t[Math.floor(t.length/2)]??0}var on=50,sn=1e4,cn=17;function ln(e){let t=dn(e),n={recorded:e,interval:t,tolerance:un(t)},r=Float64Array.from(e);hn(r,pn(fn(n)),n);let i=r.filter((t,n)=>t!==e[n]).length;for(let e=1;e<r.length;e+=1)r[e]=Math.max(r[e]??0,r[e-1]??0);return{times:r,mended:i}}function un(e){return Math.max(on*e,sn)}function dn(e){return an(e.subarray(0,1025))}function fn({recorded:e,tolerance:t}){let n=[],r=0;for(let i=1;i<=e.length;i+=1){let a=(e[i]??-1/0)-(e[i-1]??0);a>=0&&a<=t||(n.push({start:r,end:i}),r=i)}return n}function pn(e){let t=0;for(let n of e)t=Math.max(t,mn(n));return e.filter(e=>{let n=mn(e);return n>=cn||n===t})}function mn(e){return e.end-e.start}function hn(e,t,n){let[r]=t;if(r){for(let t=r.start-1;t>=0;--t)e[t]=_n(t,(e[t+1]??0)-n.interval,n);for(let[r,i]of t.entries())gn(e,{start:i.end,end:t[r+1]?.start??e.length},n)}}function gn(e,t,n){for(let r=t.start;r<t.end;r+=1)e[r]=_n(r,(e[r-1]??0)+n.interval,n)}function _n(e,t,n){let r=n.recorded[e]??t;return Math.abs(r-t)<=n.tolerance?r:t}var vn=100,yn=1e4,bn=32,xn=2,Sn=64,Cn=100,wn=56*bn;function Tn(e,t){let n=new Vt(e.ranges),r=new Bt;if(e.isRawGyro!==void 0)return e.isRawGyro?n:r;if(t===void 0)return;let i=[n,r].filter(e=>An(t,e)),[a]=i;if(a&&i.length===1)return a;throw new j(`unsupported-gyro-record`,`cannot tell the gyro sample layout from the first ${t.byteLength} bytes without the info record`)}function En(e,t){let n=Math.floor(e.byteLength/t.sampleSize),r=new Qe(e),i=new tn(n);for(let e=0;e<n;e+=1){let n=Dn(r,t,e*t.sampleSize);n&&i.push(n)}i.dropFlippedBits(t.flipSteps);let a=ln(i.captureTimes());return{track:i.toTrack(a.times),layout:t.name,strayBytes:e.byteLength%t.sampleSize,damagedSamples:n-i.length,mendedStamps:a.mended}}function Dn(e,t,n){try{let r=t.timestampAt(e,n);if(r===0&&On(e.bytesAt(n,t.sampleSize)))return;let i={captureTime:r,acceleration:t.accelerationAt(e,n),angularVelocity:t.angularVelocityAt(e,n)};return kn(i.acceleration,Sn)&&kn(i.angularVelocity,Cn)?i:void 0}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function On(e){return e.every(e=>e===0)}function kn(e,t){return e.every(e=>Math.abs(e)<=t)}function An(e,t){let n=jn(e,t);if(n.length<xn)return!1;let r=an(n);return r>=vn&&r<=yn}function jn(e,t){let n=new Qe(e),r=Math.floor(e.byteLength/t.sampleSize),i=[];for(let e=0;e<r;e+=1){let r=Mn(n,t,e*t.sampleSize);r!==void 0&&i.push(r)}return Float64Array.from(i)}function Mn(e,t,n){try{return t.timestampAt(e,n)}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}function Nn(e,t){return t?t.captureTimeOf(e):ft(e)}function Pn(e,t){let n=e.firstFrameTimestamp;return n===void 0?void 0:Nn(n,t)}var Fn=class e{offset;length;constructor(e,t){this.offset=e,this.length=t}static of(t,n){if(!Number.isSafeInteger(t)||t<0)throw new j(`invalid-byte-range`,`offset must be a non-negative integer, got ${t}`);if(!Number.isSafeInteger(n)||n<0)throw new j(`invalid-byte-range`,`length must be a non-negative integer, got ${n}`);return new e(t,n)}static lastOf(e,t){if(t>e)throw new j(`invalid-byte-range`,`cannot take ${t} bytes from a ${e}-byte source`);return this.of(e-t,t)}get end(){return this.offset+this.length}overlaps(e){return Math.max(this.offset,e.offset)<Math.min(this.end,e.end)}contains(e){return this.offset<=e.offset&&e.end<=this.end}ensureWithin(e,t){if(!(this.end<=e))throw new j(`invalid-byte-range`,`range ${this.offset}+${this.length} exceeds the ${e}-byte ${t}`)}},In=class{source;trailer;info;gyroLayoutPromise;constructor(e,t,n){this.source=e,this.trailer=t,this.info=n}get listsExposure(){return this.trailer.locationOf(ze.Exposure)!==void 0}async readGyro(){let e=this.trailer.locationOf(ze.Gyro);if(e===void 0)return;let[t,n]=await Promise.all([this.source.read(e.payload),this.gyroSampleLayout()]);return N(n!==void 0,`a gyro record always yields or refuses a layout`),En(t,n)}async readExposure(){let e=this.trailer.locationOf(ze.Exposure);if(e===void 0)return;let[t,n]=await Promise.all([this.source.read(e.payload),this.gyroSampleLayout()]);return Mt(t,e=>Nn(e,n))}async firstFrameCaptureTime(){return Pn(this.info,await this.gyroSampleLayout())}gyroSampleLayout(){return this.gyroLayoutPromise??=this.selectGyroLayout(),this.gyroLayoutPromise}async selectGyroLayout(){let e=this.gyroLayoutHints();if(e.isRawGyro!==void 0)return Tn(e,void 0);let t=this.trailer.locationOf(ze.Gyro);return Tn(e,t===void 0?void 0:await this.readHeadOf(t))}gyroLayoutHints(){return{isRawGyro:this.info.isRawGyro,ranges:this.info.sensorRanges}}readHeadOf(e){let t=Math.min(wn,e.payload.length);return this.source.read(Fn.of(e.payload.offset,t))}},Ln=class e{format;id;payloadSize;constructor(e,t,n){this.format=e,this.id=t,this.payloadSize=n}static parse(t){if(t.byteLength!==6)throw new j(`invalid-trailer`,`record header must be 6 bytes, got ${t.byteLength}`);let n=new Qe(t);return new e(n.uint8At(0),n.uint8At(1),n.uint32LeAt(2))}};function Rn(e,t){if(e.byteLength%10!=0)throw new j(`invalid-trailer`,`index size ${e.byteLength} is not a multiple of 10`);let n=new Qe(e),r=[];for(let i=0;i<e.byteLength;i+=10){let e=zn(n,i,t);e&&r.push(e)}return r}function zn(e,t,n){let r=e.uint32LeAt(t+2);return r===0?void 0:{id:e.uint8At(t+0),format:e.uint8At(t+1),payload:Fn.of(n+e.uint32LeAt(t+6),r)}}function Bn(e,t){return t.lastHeader.id===ze.Index?Vn(e,t):Un(e,t)}async function Vn(e,t){let n=t.fileSize-72-6-t.lastHeader.payloadSize;Kn(n,t.lastHeader,t.payloadStart);let r=Fn.of(n,t.lastHeader.payloadSize),i=Rn(await e.read(r),t.payloadStart);for(let e of i)Hn(e,r.offset);return i}function Hn(e,t){if(e.payload.end>t)throw new j(`invalid-trailer`,`record ${e.id} at ${e.payload.offset}+${e.payload.length} lies outside the trailer`)}async function Un(e,t){let n=[],r=new Gn(e,t.payloadStart),i=t.fileSize-72;for(;i>t.payloadStart;){let e=Ln.parse(await r.bytesEndingAt(i,6)),a=i-6-e.payloadSize;Kn(a,e,t.payloadStart),n.push({id:e.id,format:e.format,payload:Fn.of(a,e.payloadSize)}),i=a}return n.toReversed()}var Wn=65536,Gn=class{source;trailerStart;chunkStart=0;chunk=/* @__PURE__ */ new Uint8Array;constructor(e,t){this.source=e,this.trailerStart=t}async bytesEndingAt(e,t){let n=e-t;if(n<this.trailerStart)throw new j(`invalid-trailer`,`a record header at ${n} lies before the trailer`);return n>=this.chunkStart&&e<=this.chunkStart+this.chunk.byteLength||await this.readChunkEndingAt(e),this.chunk.subarray(n-this.chunkStart,e-this.chunkStart)}async readChunkEndingAt(e){this.chunkStart=Math.max(this.trailerStart,e-Wn),this.chunk=await this.source.read(Fn.of(this.chunkStart,e-this.chunkStart))}};function Kn(e,t,n){if(e<n)throw new j(`invalid-trailer`,`record ${t.id} (${t.payloadSize} bytes) runs past the trailer start; records are not contiguous`)}var qn=class{footer;payloadStart;byId;constructor(e,t,n){this.footer=e,this.payloadStart=t,this.byId=new Map(n.map(e=>[e.id,e]))}get records(){return[...this.byId.values()]}locationOf(e){return this.byId.get(e)}},Jn=class e{trailerSize;version;constructor(e,t){this.trailerSize=e,this.version=t}static parse(t){if(t.byteLength!==72)throw new j(`invalid-trailer`,`footer must be 72 bytes, got ${t.byteLength}`);let n=new Qe(t);if(n.asciiAt(40,32)!==`8db42d694ccc418790edff439fe026bf`)throw new j(`invalid-trailer`,`file does not end with the Insta360 magic`);return new e(n.uint32LeAt(32),n.uint32LeAt(36))}},Yn=78;async function Xn(e,t){if(t<Yn)throw new j(`invalid-trailer`,`file of ${t} bytes is too small to hold a trailer`);let n=Zn(await e.read(Fn.lastOf(t,Yn)),t);return new qn(n.footer,n.payloadStart,await Bn(e,n))}function Zn(e,t){let n=new Qe(e),r=Jn.parse(n.bytesAt(6,72));if(r.trailerSize>t)throw new j(`invalid-trailer`,`trailer size ${r.trailerSize} exceeds file size ${t}`);return{fileSize:t,payloadStart:t-r.trailerSize,footer:r,lastHeader:Ln.parse(n.bytesAt(0,6))}}var Qn=class e{firstFrameCaptureTime;gyroOffset;firstFrameVideoTime;constructor(e,t=pt(0),n=R(0)){this.firstFrameCaptureTime=e,this.gyroOffset=t,this.firstFrameVideoTime=n}withFirstFrameAt(t){return new e(this.firstFrameCaptureTime,this.gyroOffset,t)}videoTimeOf(e){let t=ft(e-this.firstFrameCaptureTime);return R(this.firstFrameVideoTime+mt(t))}gyroVideoTimeOf(e){return R(this.videoTimeOf(e)-gt(this.gyroOffset))}captureTimeOf(e){let t=_t(R(e-this.firstFrameVideoTime));return ft(Math.round(this.firstFrameCaptureTime+t))}};async function $n(e){let t=await Xn(e,await e.size()),n=await kt(e,t),r=new In(e,t,n);return{info:n,calibration:Ie(n.calibration),listsExposureRecord:r.listsExposure,captureClock:async()=>{let e=await r.firstFrameCaptureTime();return e===void 0?void 0:new Qn(e,n.gyroOffset)},readGyroRecord:()=>r.readGyro(),readExposureRecord:()=>r.readExposure()}}var er={Insta360Trailer:`inst`},tr=/^[ -~]{4}$/u;function nr(e){return tr.test(e)}function rr(e){return e.some(e=>e.type===er.Insta360Trailer)?`inst-box`:`bare`}function ir(e,t){if(e.length<8)return;let n=e.asciiAt(4,4);if(!nr(n))return;let r=ar(e,t);return r!==void 0&&r.size>=r.headerSize&&r.size<=t?{type:n,...r}:void 0}function ar(e,t){let n=e.uint32BeAt(0);return n===1&&e.length>=16?or(e):{size:n===0?t:n,headerSize:8}}function or(e){try{return{size:e.uint64BeAt(8),headerSize:16}}catch(e){if(M(e,`binary-unsafe-integer`))return;throw e}}async function sr(e,t){let n=[],r=0;for(;r+8<=t;){let i=await cr(e,r,t);if(!i)break;n.push(i),r=i.range.end}return n}async function cr(e,t,n){let r=n-t,i=Math.min(16,r),a=ir(new Qe(await e.read(Fn.of(t,i))),r);return a&&{type:a.type,range:Fn.of(t,a.size)}}async function lr(e){let t=await e.size(),[n,r]=await Promise.all([sr(e,t),Xn(e,t)]);return{fileSize:t,boxes:n,trailerWrapper:rr(n),trailerVersion:r.footer.version,trailerPayloadStart:r.payloadStart,records:r.records.toSorted((e,t)=>e.id-t.id)}}var ur=1e3;async function dr(e){let[t,n]=await Promise.all([lr(e),$n(e)]),r=await gr(n),i=await _r(n,r);return{...fr(t),info:n.info,calibration:pr(n),calibrationWarnings:n.calibration.warnings,gyro:r,exposure:i}}function fr(e){return{fileSize:e.fileSize,boxes:e.boxes.map(e=>({type:e.type,offset:e.range.offset,size:e.range.length})),trailerWrapper:e.trailerWrapper,trailerVersion:e.trailerVersion,payloadStart:e.trailerPayloadStart,records:e.records.map(e=>({id:e.id,format:e.format,offset:e.payload.offset,size:e.payload.length}))}}function pr(e){let{calibration:t}=e.calibration;return t===void 0?void 0:{version:t.version,canvas:[t.canvas.width,t.canvas.height],lenses:t.lenses.map(e=>({lensIndex:e.lensIndex,model:e.model.kind,principalPoint:[e.model.principalPoint.x,e.model.principalPoint.y],orientationDegrees:[e.orientation.yaw,e.orientation.pitch,e.orientation.roll],translationMetres:e.translation}))}}function mr(e){let{track:t,layout:n,strayBytes:r,damagedSamples:i,mendedStamps:a}=e,o=Math.min(ur,t.length),s=0;for(let e=0;e<o;e+=1)s+=Wt(t.sampleAt(e).acceleration);let c=t.isEmpty?0:t.sampleAt(t.length-1).captureTime-t.sampleAt(0).captureTime;return{layout:n,samples:t.length,strayBytes:r,damagedSamples:i,mendedStamps:a,spanSeconds:mt(ft(c)),meanIntervalUs:t.meanSampleInterval,meanAccelerationMagnitudeG:o>0?s/o:void 0}}function hr(e,t){let n=0;for(let t=0;t<e.length;t+=1)n+=e.entryAt(t).shutterTime;let r=e.length>0;return{entries:e.length,firstCaptureTimeUs:r?e.entryAt(0).captureTime:void 0,lastCaptureTimeUs:r?e.entryAt(e.length-1).captureTime:void 0,meanShutterTimeSeconds:r?n/e.length:void 0,firstEncodedFrameEntry:t}}async function gr(e){try{let t=await e.readGyroRecord();return t===void 0?void 0:mr(t)}catch(e){if(!M(e,`unsupported-gyro-record`))throw e;return{unreadable:ie(e)}}}async function _r(e,t){if(!e.listsExposureRecord)return;if(t!==void 0&&`unreadable`in t)return{unread:`gyro layout unknown`};let n=await e.readExposureRecord();return n?hr(n,await vr(n,e)):{damaged:!0}}async function vr(e,t){let n=await t.captureClock();return n===void 0?void 0:e.indexAtOrAfter(n.firstFrameCaptureTime)}function yr(e,t,n){return Math.min(Math.max(e,t),n)}var br=.01,xr=class e{clock;captureTimes;shutterTimes;frameDuration;constructor(e){N(e.shutterTimes===void 0||e.shutterTimes.length===e.captureTimes.length,`frame time arrays disagree on the frame count`),this.clock=e.clock,this.captureTimes=e.captureTimes,this.shutterTimes=e.shutterTimes,this.frameDuration=e.frameDuration}static withoutShutterTimes(t){return new e({...t,shutterTimes:void 0})}get frameCount(){return this.captureTimes.length}frameAt(e){ae(e,this.frameCount,`frame`);let t=ft(this.captureTimes[e]??0),n=this.shutterTimes?.[e],r=n===void 0?void 0:R(n),i=this.clock.videoTimeOf(t);return{index:e,captureTime:t,videoTime:i,shutterTime:r,midExposureVideoTime:R(i+(r??0)/2)}}midExposureAt(e){let t=this.frameIndexAt(e);return t===void 0?void 0:this.frameAt(t).midExposureVideoTime}frameIndexAt(e){return this.frameCount===0?void 0:yr(this.frameDuration===void 0?this.lastCapturedAt(e):this.onFrameGrid(e,this.frameDuration),0,this.frameCount-1)}onFrameGrid(e,t){let n=(e-this.clock.firstFrameVideoTime)/t;return Math.floor(n+br)}lastCapturedAt(e){let t=this.clock.captureTimeOf(e),n=0,r=this.frameCount-1;for(;n<r;){let e=Math.ceil((n+r)/2);(this.captureTimes[e]??1/0)<=t?n=e:r=e-1}return n}};function Sr(e){let{exposureRecord:t,clock:n,frameCount:r}=e;if(!t)return;let i=t.indexAtOrAfter(n.firstFrameCaptureTime);if(t.length-i<r)return;let a=t.slice(i,r);return new xr({clock:n,captureTimes:Float64Array.from(a.captureTimes),shutterTimes:Float64Array.from(a.shutterTimes),frameDuration:e.frameDuration})}function Cr(e){let{trackTimestamps:t,clock:n,frameCount:r}=e;if(!t||t.length<r)return;let i=Float64Array.from(t.slice(0,r),e=>n.captureTimeOf(e));return xr.withoutShutterTimes({clock:n,captureTimes:i,frameDuration:e.frameDuration})}function wr(e){let{frameRate:t,clock:n,frameCount:r}=e;if(t===void 0||t<=0)return;let i=Float64Array.from({length:r},(e,r)=>n.captureTimeOf(R(n.firstFrameVideoTime+r/t)));return xr.withoutShutterTimes({clock:n,captureTimes:i,frameDuration:e.frameDuration})}var Tr={"exposure-record":Sr,"track-timestamps":Cr,nominal:wr},Er=[`exposure-record`,`track-timestamps`,`nominal`],Dr=[`track-timestamps`,`exposure-record`,`nominal`];function Or(e,t){let n=[];for(let r of Ar(t)){let t=Tr[r](e);if(t)return{frameTimes:t,source:r,warnings:n};n.push(`${r} unavailable`)}}function kr(e,t){let n=[];for(let r of Ar(t)){if(r===`track-timestamps`)return{needsTrackTimestamps:!0,resolveWith:n=>Or({...e,trackTimestamps:n},t)};let i=Tr[r]({...e,trackTimestamps:void 0});if(i)return{needsTrackTimestamps:!1,resolved:{frameTimes:i,source:r,warnings:n}};n.push(`${r} unavailable`)}return{needsTrackTimestamps:!1,resolved:void 0}}function Ar(e){return e===`track-timestamps`?Dr:Er}async function jr(e,t,n){let{info:r}=e,[i,a]=await Promise.all([t.frameCount(),e.readExposureRecord()]),o=kr({...n,frameCount:i,frameRate:r.frameRate,exposureRecord:a},r.preferredFrameTimeSource);return o.needsTrackTimestamps?o.resolveWith(await t.sampleTimestamps()):o.resolved}var Mr=[1,0,0,0,1,0,0,0,1];function Nr(e){let t=Math.cos(e),n=Math.sin(e);return[1,0,0,0,t,-n,0,n,t]}function Pr(e){let t=Math.cos(e),n=Math.sin(e);return[t,0,n,0,1,0,-n,0,t]}function Fr(e){let t=Math.cos(e),n=Math.sin(e);return[t,-n,0,n,t,0,0,0,1]}function Ir(e,t){let[n,r,i,a,o,s,c,l,u]=e,[d,f,p,m,h,g,_,v,y]=t;return[n*d+r*m+i*_,n*f+r*h+i*v,n*p+r*g+i*y,a*d+o*m+s*_,a*f+o*h+s*v,a*p+o*g+s*y,c*d+l*m+u*_,c*f+l*h+u*v,c*p+l*g+u*y]}function Lr(e,t){let[n,r,i,a,o,s,c,l,u]=e,[d,f,p]=t;return[n*d+r*f+i*p,a*d+o*f+s*p,c*d+l*f+u*p]}function Rr(e){let[t,n,r,i,a,o,s,c,l]=e;return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}var zr=/* @__PURE__ */ new Map([[`x`,[1,0,0]],[`y`,[0,1,0]],[`z`,[0,0,1]],[`-x`,[-1,0,0]],[`-y`,[0,-1,0]],[`-z`,[0,0,-1]]]);function Br(e){let t=zr.get(e);return N(t!==void 0,`unknown IMU axis ${e}`),t}function Vr(e){let[t,n,r]=e.map(e=>Br(e));return[...t,...n,...r]}function Hr(e){return Rr(Vr(e))===1}function Ur(e,t){return{...Gr(e,t),isVerified:!0}}function Wr(e,t){return{...Gr(e,t),isVerified:!1}}function Gr(e,t){return N(Hr(t),`IMU axes ${t.join(`, `)} are not a rotation`),{name:e,toBody:Vr(t)}}function Kr(e,t){return Lr(e.toBody,t)}var qr=[`x`,`z`,`-y`],Jr=Ur(`X5`,qr),Yr=Ur(`X6`,qr),Xr=Ur(`X4 Air`,qr),Zr=Wr(`aligned (unverified)`,[`x`,`y`,`z`]),Qr=/* @__PURE__ */ new Map([[`Insta360 X4 Air`,Xr],[`Insta360 X5`,Jr],[`Insta360 X6`,Yr]]);function $r(e){return Qr.get(e.model?.trim()??``)??Zr}var ei=.02,ti=_t(R(1));function ni(e,t,n){let r=mt(e.meanSampleInterval??ti),i=Math.max(1,Math.min(e.length,Math.round(n/r))),a=ri(e,t),o=0;for(let e=0;e<i;e+=1)o+=a[e]??0;let s={start:0,sum:o};for(let t=1;t+i<=e.length;t+=1)o+=(a[t+i-1]??0)-(a[t-1]??0),o<s.sum&&(s={start:t,sum:o});return{start:s.start,end:s.start+i}}function ri(e,t){let n=new Float64Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=Wt(Kr(t,e.angularVelocityAt(r)));return n}function ii({gyro:e,frame:t},n,r){let i=Ut;for(let a=n.start;a<n.end;a+=1){let n=r(e.sampleAt(a));i=Jt(i,Kr(t,n))}return Xt(i,1/Math.max(n.end-n.start,1))}function ai(e,t,n){let r=ii({gyro:e,frame:t},n,e=>e.angularVelocity);return Wt(r)<=ei?r:Ut}var oi=[0,0,0,1],si=1e-12,ci=.9995;function li(e,t){let n=Wt(e);if(n===0)return oi;let r=t/2,i=Math.sin(r)/n;return[e[0]*i,e[1]*i,e[2]*i,Math.cos(r)]}function ui(e){let t=Wt(e);return t<si?oi:li(e,n(t))}function di(e,t){let[n,r,i,a]=e,[o,s,c,l]=t;return[a*o+n*l+r*c-i*s,a*s-n*c+r*l+i*o,a*c+n*s-r*o+i*l,a*l-n*o-r*s-i*c]}function fi(e){let[t,n,r,i]=e;return[-t,-n,-r,i]}function pi(e){let[t,n,r,i]=e,a=Math.sqrt(t*t+n*n+r*r+i*i);return a===0?oi:[t/a,n/a,r/a,i/a]}function mi(e,t){let[n,r,i,a]=e,[o,s,c]=t,l=2*(r*c-i*s),u=2*(i*o-n*c),d=2*(n*s-r*o);return[o+a*l+(r*d-i*u),s+a*u+(i*l-n*d),c+a*d+(n*u-r*l)]}function hi(e,t,n){let[r,i,a,o]=e,[s,c,l,u]=t,d=r*s+i*c+a*l+o*u;if(d<0&&(d=-d,[s,c,l,u]=[-s,-c,-l,-u]),d>ci)return pi([r+(s-r)*n,i+(c-i)*n,a+(l-a)*n,o+(u-o)*n]);let f=Math.acos(d),p=Math.sin(f),m=Math.sin((1-n)*f)/p,h=Math.sin(n*f)/p;return[r*m+s*h,i*m+c*h,a*m+l*h,o*m+u*h]}function gi(e){let[t,n,r,i]=e;return[1-2*(n*n+r*r),2*(t*n-r*i),2*(t*r+n*i),2*(t*n+r*i),1-2*(t*t+r*r),2*(n*r-t*i),2*(t*r-n*i),2*(n*r+t*i),1-2*(t*t+n*n)]}var _i=[0,1,0],vi=.9,yi=1.1;function bi(e){let t=Wt(e);return t>=vi&&t<=yi?Xt(e,-1/t):void 0}function xi(e,t){let n=bi(t);return n?Kt(n,mi(fi(e),_i)):[0,0,0]}function Si(e,t){if(e.isEmpty)return{start:0,end:0};let n=e.sampleAt(0).captureTime,r=_t(t),i=1;for(;i<e.length&&e.sampleAt(i).captureTime-n<=r;)i+=1;return{start:0,end:i}}function Ci(e,t,n){if(e.isEmpty)return oi;let r=Si(e,n),i=bi(ii({gyro:e,frame:t},r,e=>e.acceleration));return i?wi(i,_i):oi}function wi(e,t){let r=Kt(e,t),i=Gt(e,t),a=Wt(r);return a>0?li(r,n(Math.atan2(a,i))):i>0?oi:li(Ti(e),n(Math.PI))}function Ti(e){return Math.abs(e[0])<Math.abs(e[2])?[0,-e[2],e[1]]:[-e[1],e[0],0]}var Ei=.2,Di=.5,Oi=.5,ki=4,Ai=.05,ji=class e{videoTimes;quaternions;constructor(e,t){this.videoTimes=e,this.quaternions=t,N(t.length===e.length*ki,`orientation track arrays disagree on the sample count`)}static integrate(t){let{gyro:n,clock:r,frame:i}=t,a=new Float64Array(n.length),o=new Float32Array(n.length*ki);if(n.isEmpty)return new e(a,o);let s={frame:i,bias:ai(n,i,ni(n,i,R(Di))),gravityGain:t.options?.gravityGain??Ei};a.set(Mi(n,r));let c={orientation:Ci(n,i,R(Oi)),time:R(a[0]??0),rate:Ut};for(let e=0;e<n.length;e+=1){let t=R(a[e]??c.time);c=Pi(c,{sample:Ni(n,e),time:t},s),o.set(c.orientation,e*ki)}return new e(a,o)}get length(){return this.videoTimes.length}orientationAt(e){if(this.length===0)return oi;let t=this.firstIndexAfter(e);if(t===0)return this.quaternionAt(0);if(t>=this.length)return this.quaternionAt(this.length-1);let n=t-1,r=(this.videoTimes[t]??0)-(this.videoTimes[n]??0),i=r>0?(e-(this.videoTimes[n]??0))/r:0;return hi(this.quaternionAt(n),this.quaternionAt(t),i)}quaternionAt(e){let t=e*ki,[n=0,r=0,i=0,a=1]=this.quaternions.subarray(t,t+ki);return[n,r,i,a]}firstIndexAfter(e){let t=0,n=this.length;for(;t<n;){let r=Math.floor((t+n)/2);(this.videoTimes[r]??1/0)<=e?t=r+1:n=r}return t}};function Mi(e,t){return e.captureTimes.map(e=>t.gyroVideoTimeOf(ft(e)))}function Ni(e,t){let n=e.sampleAt(t);return N(qt(n.acceleration)&&qt(n.angularVelocity),`gyro sample ${t} is not finite`),n}function Pi(e,{sample:t,time:n},r){let{frame:i,bias:a,gravityGain:o}=r,s=yr(n-e.time,0,Ai),c=xi(e.orientation,Kr(i,t.acceleration));return{orientation:Ii(e.orientation,Fi(e.rate,c,o),s),time:n,rate:Yt(Kr(i,t.angularVelocity),a)}}function Fi(e,t,n){return Jt(e,Xt(t,n))}function Ii(e,t,n){return pi(di(e,ui(Xt(t,n))))}var Li=`the recording has no gyro record; stabilization is unavailable`;async function Ri(e,t){let n=await e.readGyroRecord();if(!n)return{setup:void 0,warnings:[Li]};let r=$r(e.info),i=ji.integrate({gyro:n.track,clock:t,frame:r}),a=[...Bi(r,e),...zi(n)];return{setup:{orientations:i,imuFrame:r},warnings:a}}function zi(e){return[...e.damagedSamples>0?[`damaged gyro samples left out of stabilization: ${e.damagedSamples}`]:[],...e.mendedStamps>0?[`gyro stamps off their neighbours mended: ${e.mendedStamps}`]:[]]}function Bi(e,t){return e.isVerified?[]:[`the IMU frame of ${t.info.model??`this camera`} has not been verified on a recording; stabilization may misbehave`]}var Vi=`frame timing and stabilization are unavailable`,Hi=`the recording has no capture clock; ${Vi}`,Ui=`the recording has no frame source to time; ${Vi}`,Wi=`no frame timing source is usable; frames are timed by their track timestamps`;async function Gi(e,t){try{return await Ki(e,t)}catch(e){if(!M(e,`unsupported-gyro-record`))throw e;return Ji([`${ie(e)}; ${Vi}`])}}async function Ki(e,t){let n=await e.captureClock();if(!n)return Ji([Hi]);if(!t)return Ji([Ui]);let r=await qi(n,t),[i,a]=await Promise.all([jr(e,t,r),Ri(e,r.clock)]);return{frameTimes:i?.frameTimes,frameTimeSource:i?.source,motion:a.setup,warnings:[...i?.warnings??[Wi],...a.warnings]}}async function qi(e,t){let n=await t.firstKeyframe(),r=n!==void 0&&n.duration>0;return{clock:e.withFirstFrameAt(n?.timestamp??R(0)),frameDuration:r?n.duration:void 0}}function Ji(e){return{frameTimes:void 0,frameTimeSource:void 0,motion:void 0,warnings:e}}var Yi=/^(?<prefix>[A-Za-z]+(?:_[A-Za-z]+)*)_(?<stamp>\d{8}_\d{6})_(?<lens>\d)(?<proxy>\d)_(?<sequence>\d{3})\.(?<extension>[A-Za-z0-9]+)$/u,Xi=0,Zi=1,Qi=0,$i=1,ea=class e{parts;constructor(e){this.parts=e}static parse(t){let n=Yi.exec(t)?.groups;return n?new e(ta(n)):void 0}get isBackLens(){return this.parts.lensDigit===Xi}get isScreenLens(){return this.parts.lensDigit===Zi}get isProxy(){return this.parts.proxyDigit===$i}otherLensName(){let t=this.isBackLens?Zi:Xi;return new e({...this.parts,lensDigit:t,proxyDigit:Qi}).toString()}toString(){let{prefix:e,captureStamp:t,lensDigit:n,proxyDigit:r,sequence:i,extension:a}=this.parts;return`${e}_${t}_${n}${r}_${i}.${a}`}};function ta(e){return{prefix:e.prefix??``,captureStamp:e.stamp??``,lensDigit:Number(e.lens),proxyDigit:Number(e.proxy),sequence:e.sequence??``,extension:e.extension??``}}var na=/[#?]/u;function ra(e){let t=e.search(na);return t===-1?{path:e,suffix:``}:{path:e.slice(0,t),suffix:e.slice(t)}}function ia(e){let{path:t}=ra(e),n=t.slice(t.lastIndexOf(`/`)+1);try{return decodeURIComponent(n)}catch{return n}}async function aa(e,t){let n=ea.parse(ia(e));if(!n)return;let r=oa(e,n.otherLensName());return await t.exists(r)?r:void 0}function oa(e,t){let{path:n,suffix:r}=ra(e);return`${n.slice(0,n.lastIndexOf(`/`)+1)}${encodeURIComponent(t)}${r}`}var sa={FileType:`ftyp`,MediaData:`mdat`,Movie:`moov`,MovieHeader:`mvhd`,MovieExtends:`mvex`,Track:`trak`,TrackHeader:`tkhd`,Edit:`edts`,EditList:`elst`,Media:`mdia`,MediaHeader:`mdhd`,Handler:`hdlr`,MediaInformation:`minf`,SampleTable:`stbl`,SampleDescription:`stsd`,TimeToSample:`stts`,CompositionOffset:`ctts`,SyncSample:`stss`,SampleToChunk:`stsc`,SampleSize:`stsz`,ChunkOffset:`stco`,ChunkLargeOffset:`co64`,AvcConfiguration:`avcC`,HevcConfiguration:`hvcC`},ca={Video:`vide`,Sound:`soun`},la=[`avc1`,`avc3`],ua=[`hvc1`,`hev1`],da={isKeyframe:()=>!0},fa=31,pa=1,ma=4,ha=5,ga=1,_a=63,va=16,ya=23,ba={typeOf:e=>e&fa,verdictOn:e=>e===ha?`keyframe`:e>=pa&&e<=ma?`not-a-keyframe`:`read-on`},xa={typeOf:e=>e>>ga&_a,verdictOn:e=>e<va?`not-a-keyframe`:e<=ya?`keyframe`:`read-on`},Sa=8,Ca=class{family;lengthSize;constructor(e,t){this.family=e,this.lengthSize=t}isKeyframe(e){let t=0;for(;t+this.lengthSize<e.length;){let n=t+this.lengthSize,r=n+wa(e,t,this.lengthSize);if(r>e.length)return!1;let i=this.family.verdictOn(this.family.typeOf(e[n]??0));if(i!==`read-on`)return i===`keyframe`;t=r}return!1}};function wa(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r*2**Sa+(e[t+i]??0);return r}var Ta=[[la,ba],[ua,xa]];function Ea(e){let{sampleEntryType:t,nalLengthSize:n}=e,[,r]=Ta.find(([e])=>e.includes(t))??[];return r&&n!==void 0?new Ca(r,n):da}function Da(e){let t=[],n=0;for(;e.byteLength-n>=8;){let r=e.byteLength-n,i=ir(new Qe(e.subarray(n,n+16)),r);if(!i)throw ja(`holds no box at byte ${n} of ${e.byteLength}`);let a=e.subarray(n+i.headerSize,n+i.size);t.push({type:i.type,body:a}),n+=i.size}return t}function Oa(e,t){let n=ka(e,t);if(!n)throw ja(`has no ${t} box where one belongs`);return n}function ka(e,t){return e.find(e=>e.type===t)}function Aa(e){if(e.body.byteLength<4)throw ja(`has a ${e.type} box too short for its version and flags`);return{version:e.body[0]??0,content:new Qe(e.body.subarray(4))}}function ja(e){return new j(`unsupported-container`,`the movie box ${e}`)}var Ma={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:96},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:108}},Na={0:8,1:16},Pa={0:{timescale:8,duration:{offset:12,kind:`uint32`},size:20},1:{timescale:16,duration:{offset:20,kind:`uint64`},size:32}},Fa={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleDelta:{offset:4,kind:`uint32`}}},Ia={entrySize:8,fields:{sampleCount:{offset:0,kind:`uint32`},sampleOffset:{offset:4,kind:`int32`}}},La={entrySize:4,fields:{sampleNumber:{offset:0,kind:`uint32`}}},Ra={0:{entrySize:12,fields:{segmentDuration:{offset:0,kind:`uint32`},mediaTime:{offset:4,kind:`int32`},mediaRate:{offset:8,kind:`uint32`}}},1:{entrySize:20,fields:{segmentDuration:{offset:0,kind:`uint64`},mediaTime:{offset:8,kind:`int64`},mediaRate:{offset:16,kind:`uint32`}}}},za={entrySize:12,fields:{firstChunk:{offset:0,kind:`uint32`},samplesPerChunk:{offset:4,kind:`uint32`},sampleDescriptionIndex:{offset:8,kind:`uint32`}}},Ba={entrySize:4,fields:{chunkOffset:{offset:0,kind:`uint32`}}},Va={entrySize:8,fields:{chunkOffset:{offset:0,kind:`uint64`}}},Ha={uint32:(e,t)=>e.uint32BeAt(t),uint64:(e,t)=>e.uint64BeAt(t),int32:(e,t)=>e.int32BeAt(t),int64:(e,t)=>e.int64BeAt(t)};function Ua(e,t,n=0){return Ha[t.kind](e,n+t.offset)}function Wa(e,t){let n=e.uint32BeAt(0);if(4+n*t.entrySize>e.length)throw ja(`has a table of ${n} entries that do not fit in its box`);let r=Object.keys(t.fields),i={};for(let a of r)i[a]=Array.from({length:n},(n,r)=>Ua(e,t.fields[a],4+r*t.entrySize));return i}var Ga=1;function Ka(e){let t=qa(Oa(e,sa.SampleSize)),n=Ja(e),r=Aa(Oa(e,sa.SampleToChunk)).content;return{offsets:Xa({sizes:t,chunkOffsets:n,perChunk:Ya(Wa(r,za),n.length)}),sizes:t}}function qa(e){let{content:t}=Aa(e),n=t.uint32BeAt(0),r=t.uint32BeAt(4);if(n!==0)return new Float64Array(r).fill(n);if(8+r*4>t.length)throw ja(`lists ${r} sample sizes that do not fit in its box`);return Float64Array.from({length:r},(e,n)=>t.uint32BeAt(8+n*4))}function Ja(e){let t=ka(e,sa.ChunkLargeOffset),n=t??ka(e,sa.ChunkOffset);if(!n)throw ja(`has a sample table without chunk offsets`);let r=t?Va:Ba;return Wa(Aa(n).content,r).chunkOffset}function Ya(e,t){let n=Array.from({length:t},()=>0);for(let[r,i]of e.firstChunk.entries()){let a=e.firstChunk[r+1]??t+Ga,o=e.samplesPerChunk[r]??0;n.fill(o,i-Ga,a-Ga)}return n}function Xa(e){let t=new Float64Array(e.sizes.length),n=0;for(let[r,i]of e.chunkOffsets.entries()){let a=i,o=Math.min(n+(e.perChunk[r]??0),t.length);for(;n<o;n+=1)t[n]=a,a+=e.sizes[n]??0}if(n<t.length)throw ja(`has chunks for ${n} of its ${t.length} samples`);return t}var Za=4,Qa=/* @__PURE__ */ new Map([[sa.AvcConfiguration,4],[sa.HevcConfiguration,21]]);function $a(e){let t=Aa(Oa(e,sa.MovieHeader));return t.content.uint32BeAt(no(t,Ma,sa.MovieHeader).timescale)}function eo(e){let t=Da(e.body),n=Da(Oa(t,sa.Media).body);return{track:t,media:n,sampleTable:Da(Oa(Da(Oa(n,sa.MediaInformation).body),sa.SampleTable).body)}}function to(e){let t=ao(e.media),n=oo(e.sampleTable);return{trackId:ro(e.track),handlerType:t,mediaTimescale:io(e.media),sampleEntryType:n.type,nalLengthSize:t===ca.Video?so(n):void 0}}function no(e,t,n){let r=e.version===0||e.version===1?t[e.version]:void 0;if(r===void 0)throw ja(`has a ${n} box of version ${e.version}`);return r}function ro(e){let t=Aa(Oa(e,sa.TrackHeader));return t.content.uint32BeAt(no(t,Na,sa.TrackHeader))}function io(e){let t=Aa(Oa(e,sa.MediaHeader));return t.content.uint32BeAt(no(t,Pa,sa.MediaHeader).timescale)}function ao(e){let{content:t}=Aa(Oa(e,sa.Handler));return t.asciiAt(4,Za)}function oo(e){let{content:t}=Aa(Oa(e,sa.SampleDescription)),n=t.length-4,[r]=Da(t.bytesAt(4,n));if(!r)throw ja(`has a track without a sample entry`);return r}function so(e){let t=Da(e.body.subarray(78)).find(e=>Qa.has(e.type)),n=t?.body[Qa.get(t.type)??0];return n===void 0?void 0:(n&3)+1}function co(e){return Array.from({length:e.length},(e,t)=>t).toSorted((t,n)=>(e[t]??0)-(e[n]??0))}function lo(e,t){let n=uo(Oa(e.sampleTable,sa.TimeToSample),t),r=fo(e.sampleTable,t.sampleCount),i=r?n.times.map((e,t)=>e+(r[t]??0)):n.times,a=mo(e.track,t),o=i.map(e=>(e-a)/t.media),s=(r?ho(i,n.deltas):n.deltas).map(e=>e/t.media);return{timestamps:o,durations:s,end:go(o,s,t.media)}}function uo(e,t){let n=Wa(Aa(e).content,Fa),r=po(n.sampleCount,n.sampleDelta);if(r.length!==t.sampleCount)throw ja(`times ${r.length} samples of a track that has ${t.sampleCount}`);let i=new Float64Array(r.length);for(let e=1;e<r.length;e+=1)i[e]=(i[e-1]??0)+(r[e-1]??0);return{times:i,deltas:r}}function fo(e,t){let n=ka(e,sa.CompositionOffset);if(!n)return;let r=Wa(Aa(n).content,Ia),i=new Float64Array(t);return i.set(po(r.sampleCount,r.sampleOffset).subarray(0,t)),i}function po(e,t){let n=e.reduce((e,t)=>e+t,0),r=new Float64Array(n),i=0;for(let[n,a]of e.entries())r.fill(t[n]??0,i,i+a),i+=a;return r}function mo(e,t){let n=ka(e,sa.Edit),r=n&&ka(Da(n.body),sa.EditList);if(!r)return 0;let i=Aa(r),a=Wa(i.content,no(i,Ra,sa.EditList)),o=0;for(let[e,n]of a.mediaTime.entries()){if(n===-1){o+=a.segmentDuration[e]??0;continue}return a.mediaRate[e]===65536?n-Math.round(o/t.movie*t.media):0}return 0}function ho(e,t){let n=co(e),r=Float64Array.from(t);for(let t=0;t<n.length-1;t+=1){let i=n[t]??0;r[i]=(e[n[t+1]??0]??0)-(e[i]??0)}return r}function go(e,t,n){let r=co(e).at(-1);if(r===void 0)return R(0);let i=(e[r]??0)+(t[r]??0);return R(Math.round(i*n)/n)}var _o=class{tracks;constructor(e){this.tracks=e}get videoTracks(){return this.tracks.filter(e=>e.kind===`video`)}get audioTracks(){return this.tracks.filter(e=>e.kind===`audio`)}get duration(){return R(Math.max(0,...this.tracks.map(e=>e.end)))}trackWithId(e){return this.tracks.find(t=>t.trackId===e)}};function vo(e,t,n){let r=0,i=e;for(;r<i;){let e=r+i>>>1;t(e)<=n?r=e+1:i=e}return r}var yo=class{parts;trackId;kind;end;keyframeRule;presentationOrder;constructor(e){this.parts=e;let{length:t}=e.offsets;N([e.sizes,e.timestamps,e.durations].every(e=>e.length===t),`the sample table of track ${e.trackId} disagrees on its sample count`),N(bo(e.syncSamples??[],t),`the sync samples of track ${e.trackId} are not samples of it in order`),this.trackId=e.trackId,this.kind=e.kind,this.end=e.end,this.keyframeRule=e.keyframeRule,this.presentationOrder=co(e.timestamps)}get sampleCount(){return this.parts.offsets.length}rangeOf(e){return this.ensureSample(e),Fn.of(this.parts.offsets[e]??0,this.parts.sizes[e]??0)}timestampOf(e){return this.ensureSample(e),R(this.parts.timestamps[e]??0)}durationOf(e){return this.ensureSample(e),R(this.parts.durations[e]??0)}isSync(e){return this.ensureSample(e),this.syncSampleAtOrBefore(e)===e}sampleShownAt(e){let t=vo(this.presentationOrder.length,e=>this.parts.timestamps[this.presentationOrder[e]??0]??1/0,e);return this.presentationOrder[t-1]}keyframeAt(e){let t=this.sampleShownAt(e);return t===void 0?void 0:this.syncSampleAtOrBefore(t)}syncSampleAtOrBefore(e){let{syncSamples:t}=this.parts;return t?t[vo(t.length,e=>t[e]??0,e)-1]:e>=0?e:void 0}syncSampleAtOrAfter(e){let{syncSamples:t}=this.parts,n=Math.max(0,e);return t?t[vo(t.length,e=>t[e]??0,n-1)]:n<this.sampleCount?n:void 0}timestampsInPresentationOrder(){return this.presentationOrder.map(e=>R(this.parts.timestamps[e]??0))}ensureSample(e){ae(e,this.sampleCount,`sample of track ${this.trackId}`)}};function bo(e,t){return e.every((n,r)=>Number.isSafeInteger(n)&&n>=0&&n<t&&n>(e[r-1]??-1))}var xo={[ca.Video]:`video`,[ca.Sound]:`audio`},So=1;function Co(e){let[t]=Da(e);if(t?.type!==sa.Movie)throw ja(`is not where the file says it is`);let n=Da(t.body);if(ka(n,sa.MovieExtends))throw ja(`is fragmented: its samples are described in movie fragments after it`);let r=$a(n);return new _o(n.filter(e=>e.type===sa.Track).flatMap(e=>wo(eo(e),r)))}function wo(e,t){let n=to(e),r=xo[n.handlerType];if(!r)return[];let i=Ka(e.sampleTable),a=lo(e,{media:n.mediaTimescale,movie:t,sampleCount:i.sizes.length});return[new yo({trackId:n.trackId,kind:r,...i,...a,syncSamples:To(e.sampleTable),keyframeRule:Ea(n)})]}function To(e){let t=ka(e,sa.SyncSample);if(!t)return;let{sampleNumber:n}=Wa(Aa(t).content,La);return n.map(e=>e-So)}function Eo(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}async function Do(e){let t=await sr(e,await e.size()),n=t.find(e=>e.type===sa.Movie);if(!n)throw new j(`unsupported-container`,`the file has no movie box to read its samples from`);let r=t.find(e=>e.type===sa.FileType),[i,a]=await Promise.all([Oo(e,r),Oo(e,n)]);return{table:Co(a),movieBytes:Eo([i,a])}}function Oo(e,t){return t?e.read(t.range):Promise.resolve(/* @__PURE__ */ new Uint8Array)}var ko={x:0,y:0,width:1,height:1},Ao={x:0,y:0,width:.5,height:1},jo={x:.5,y:0,width:.5,height:1},Mo=2,No=2,Po=.02,Fo=0,Io=1,Lo=2;function Ro(e,t){let n=e.flatMap((e,t)=>e.videoTracks.map(({description:n})=>({input:e,inputIndex:t,track:n})));if(e.length===1&&Uo(n))return zo(n,t);if(e.length===Mo&&Wo(e,n))return Bo(e,n);let[r]=n;if(r&&n.length===1&&Ko(r.track))return Vo(r);throw Jo(e,n)}function zo(e,t){let n=t.trackOrder===`stream-10-first`,r=n?e.toReversed():e,i=t.fileLayout===void 0?[]:[`info record file layout ${t.fileLayout}`],a=t.trackOrder===void 0?`no track order hint: lens 0 assumed to be track 0`:`info record track order ${t.trackOrder}: lens 0 is track ${+!!n}`;return{kind:`multi-track`,sources:r.map((e,t)=>Ho(e,t)),evidence:[`one input with two video tracks`,...i,a]}}function Bo(e,t){let n=t.toSorted((e,t)=>qo(e.input)-qo(t.input)),r=e.map(e=>e.name??`?`).join(`, `);return{kind:`split-files`,sources:n.map((e,t)=>Ho(e,t)),evidence:[`two inputs with one video track each (${r})`,`lens 0 taken from the _00_ file when named`]}}function Vo(e){let{inputIndex:t,track:n}=e;return{kind:`packed`,sources:[{lensIndex:0,inputIndex:t,trackIndex:n.trackIndex,region:Ao},{lensIndex:1,inputIndex:t,trackIndex:n.trackIndex,region:jo}],evidence:[`single ${n.codedWidth}x${n.codedHeight} track with a 2:1 aspect ratio`]}}function Ho(e,t){return{lensIndex:t,inputIndex:e.inputIndex,trackIndex:e.track.trackIndex,region:ko}}function Uo(e){let[t,n]=e;return e.length===Mo&&t!==void 0&&n!==void 0&&Go(t.track)&&t.track.codedWidth===n.track.codedWidth&&t.track.codedHeight===n.track.codedHeight}function Wo(e,t){return t.length===Mo&&e.every(e=>e.videoTracks.length===1)&&t.every(e=>Go(e.track))}function Go(e){return e.codedWidth===e.codedHeight}function Ko(e){return Math.abs(e.codedWidth/e.codedHeight-No)<=Po}function qo(e){let t=ea.parse(e.name??``);return t?.isBackLens?Fo:t?.isScreenLens?Lo:Io}function Jo(e,t){let[n]=t;if(e.length===1&&t.length===1&&n!==void 0&&Go(n.track))return Yo(n.input);let r=t.map(e=>`${e.track.codedWidth}x${e.track.codedHeight}`).join(`, `);return new j(`unsupported-layout`,`cannot map ${t.length} video track(s) [${r}] in ${e.length} file(s) onto two lenses`)}function Yo(e){let t=ea.parse(e.name??``);return new j(`missing-second-file`,`this recording stores one lens per file; provide ${t?`the matching ${t.otherLensName()}`:`the other lens's file`} as the second source`)}var Xo=[`off`,`lock`,`horizon`,`follow`],Zo=`lock`,Qo=class{nextRotation(){return Mr}},$o=class{nextRotation(e){return gi(fi(e))}},es=class{nextRotation(e){let t=li(_i,as(e));return Ir(gi(fi(e)),gi(t))}},ts={timeConstant:R(1.5),maxContinuousGap:R(1)},ns=class{options;smoothed;previousTime;constructor(e=ts){this.options=e}nextRotation(e,t){return this.smoothed=this.follow(e,t),this.previousTime=t,Ir(gi(fi(e)),gi(this.smoothed))}follow(e,t){let n=this.previousTime===void 0?1/0:t-this.previousTime;if(!this.smoothed||Math.abs(n)>this.options.maxContinuousGap)return e;if(n<=0)return this.smoothed;let r=1-Math.exp(-n/this.options.timeConstant);return hi(this.smoothed,e,r)}},rs={off:()=>new Qo,lock:()=>new $o,horizon:()=>new es,follow:()=>new ns};function is(e){return rs[e]()}function as(e){let[,t,,r]=e;return n(2*Math.atan2(t,r))}function os(e){return t(2*(Math.round(e/o)*o)-e)}function ss(e){let{yaw:n,pitch:r,roll:i}=e.orientation,a=Pr(l(n)),o=Ir(Nr(l(r)),a),c=Ir(Nr(l(t(s*e.lensIndex))),o);return Ir(Fr(l(os(i))),c)}var cs=1.5,ls=.01,us=[1,1,1],ds={maxGain:2,timeConstant:R(cs)};function fs(e,t){let[n]=e;return n?e.map((e,r)=>r===0?us:ps(n,e,t)):[]}function ps(e,t,n){return[ms(e[0],t[0],n),ms(e[1],t[1],n),ms(e[2],t[2],n)]}function ms(e,t,n){return e<ls||t<ls?1:yr(e/t,1/n,n)}var hs=class{options;current;lastTime;constructor(e=ds){this.options=e}update(e,t){let n=fs(e,this.options.maxGain),r=this.lastTime===void 0?1/0:Math.max(t-this.lastTime,0);this.lastTime=t;let i=this.current?1-Math.exp(-r/this.options.timeConstant):1,a=this.current;return this.current=n.map((e,t)=>Zt(a?.[t]??us,e,i)),this.current}},gs=30,_s=120,vs=90,ys=90,bs={yaw:t(0),pitch:t(0),fieldOfView:t(vs)};function xs(e){return N([e.yaw,e.pitch,e.fieldOfView].every(e=>Number.isFinite(e)),`view angles must be finite`),{...e,yaw:d(e.yaw),pitch:t(yr(e.pitch,-90,ys)),fieldOfView:t(yr(e.fieldOfView,gs,_s))}}function Ss(e,t){return e.yaw===t.yaw&&e.pitch===t.pitch&&e.fieldOfView===t.fieldOfView}function Cs(e){return Ir(Pr(l(e.yaw)),Nr(l(e.pitch)))}var ws=[`fast`,`balanced`,`high`],Ts=`balanced`,Es={fast:1,balanced:2,high:3};function Ds(e){return Es[e]}var Os=[`raw-lenses`,`equirectangular`,`normal`],ks=`raw-lenses`,As=.5,js={x:0,y:0,width:1,height:1},Ms={x:As,y:As};function Ns(e){return Math.max(e,1)}function Ps(e){return e.width/Ns(e.height)}function Fs(e,t){return{across:e.x/Ns(t.width),down:e.y/Ns(t.height)}}function Is(e,t){return{x:(t.x-e.x)/e.width,y:(t.y-e.y)/e.height}}function Ls(e,t){let n=Vs(e,t),r=Vs(1/e,t);return n.height>=r.height/e?Rs(n,e):zs(r,e)}function Rs(e,t){let n=e.width/t;return Array.from({length:t},(t,r)=>({...e,x:e.x+r*n,width:n}))}function zs(e,t){let n=e.height/t;return Array.from({length:t},(t,r)=>({...e,y:e.y+r*n,height:n}))}function Bs(e){N(e.length>0,`bounds need at least one rectangle`);let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),r=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t,y:n,width:r-t,height:i-n}}function Vs(e,t){if(e>=t){let n=t/e;return{x:0,y:(1-n)*As,width:1,height:n}}let n=e/t;return{x:(1-n)*As,y:0,width:n,height:1}}function Hs(e){return Math.tan(l(t(e/2)))}function Us(e,t){return t*e.width/e.height}function Ws(e,t,n){let r=Hs(e),i=[(t.x*2-1)*r,(t.y*2-1)*r/n,1];return Xt(i,1/Wt(i))}function Gs(e,t,n){return Lr(Cs(e),Ws(e.fieldOfView,t,n))}var Ks=1.1;function qs(e){return Ks**e}function Js(e,n){return t(e.fieldOfView/Math.max(n,1))}function Ys(e,n,r){let i=Js(e,r);return xs({...e,yaw:t(e.yaw-n.x*i),pitch:t(e.pitch+n.y*i)})}function Xs(e,n){return xs({...e,fieldOfView:t(e.fieldOfView/qs(n))})}function Zs(e,t,r){let i=Xs(e,t.steps);if(t.focus.x===Ms.x&&t.focus.y===Ms.y||i.fieldOfView===e.fieldOfView)return i;let a=Gs(e,t.focus,r),o=Ws(i.fieldOfView,t.focus,r),s=Qs(o,a[1],e.pitch);if(s===void 0)return i;let c=Lr(Nr(l(s)),o),d=u(n(Math.atan2(a[0],a[2])-Math.atan2(c[0],c[2])));return xs({...i,yaw:d,pitch:s})}function Qs(e,r,i){let[,a,o]=e,s=r/Math.hypot(a,o);if(Math.abs(s)>1)return;let c=u(n(Math.atan2(o,a))),l=u(n(Math.acos(s))),f=d(t(l-c)),p=d(t(-l-c));return Math.abs(f-i)<=Math.abs(p-i)?f:p}function $s(e,t){return e<=0||t<=0?0:Math.log(t/e)/Math.log(Ks)}function ec(e,t,n){return xs({...e,yaw:t,pitch:n})}var tc={scale:1,centre:{x:As,y:As}},nc=1e-9;function rc(e,t){return e.scale===t.scale&&e.centre.x===t.centre.x&&e.centre.y===t.centre.y}function ic(e,t){let n=e.width*t.scale,r=e.height*t.scale;return{x:Ms.x-t.centre.x*n,y:Ms.y-t.centre.y*r,width:n,height:r}}function ac(e,t){let n=yr(t.scale,1,8),r=n-1<nc?1:n;return{scale:r,centre:{x:lc(t.centre.x,e.width*r),y:lc(t.centre.y,e.height*r)}}}function oc(e,t,n){let r=ac(e,t),i=Is(ic(e,r),n.focus),a=r.scale*qs(n.steps);return ac(e,{scale:a,centre:{x:i.x+(Ms.x-n.focus.x)/(e.width*a),y:i.y+(Ms.y-n.focus.y)/(e.height*a)}})}function sc(e,t,n){let r=ac(e,t),i=cc(e,r,n);return ac(e,{scale:r.scale,centre:{x:r.centre.x-i.across,y:r.centre.y-i.down}})}function cc(e,t,n){return{across:n.across/(e.width*t.scale),down:n.down/(e.height*t.scale)}}function lc(e,t){if(t<=1)return As;let n=As/t;return yr(e,n,1-n)}var uc={view:bs,panorama:tc,lenses:tc};function dc(e,t){return Ss(e.view,t.view)&&rc(e.panorama,t.panorama)&&rc(e.lenses,t.lenses)}function fc(e,t){return{...e,view:t}}function pc(e,t){return{...e,lenses:t}}var mc=90;function hc({viewport:e,lensCount:t}){let n=Ls(t,Ps(e));return{tiles:n,bounds:Bs(n)}}function gc(e,t,n){let r=Fs(t,n.viewport);return pc(e,sc(hc(n).bounds,e.lenses,r))}function _c(e,t,n){let r=n.viewport.width/mc;return gc(e,{x:-(t.yaw*r),y:t.pitch*r},n)}function vc(e,t){let{tiles:n,bounds:r}=hc(t),i=ac(r,e.lenses),a=ic(r,i);return n.map(e=>({x:a.x+(e.x-r.x)*i.scale,y:a.y+(e.y-r.y)*i.scale,width:e.width*i.scale,height:e.height*i.scale}))}var yc={isStabilized:!1,canPan:({lenses:e})=>e.scale>1,pan:gc,turn:_c,zoom:(e,t,n)=>pc(e,oc(hc(n).bounds,e.lenses,t)),reset:e=>pc(e,tc),picture:(e,t)=>({kind:`lens-tiles`,tiles:vc(e,t)})},bc={isStabilized:!0,canPan:()=>!0,pan:(e,t,{viewport:n})=>fc(e,Ys(e.view,t,n.width)),turn:(e,n)=>{let{view:r}=e;return fc(e,ec(r,t(r.yaw+n.yaw),t(r.pitch+n.pitch)))},zoom:(e,t,{viewport:n})=>fc(e,Zs(e.view,t,Ps(n))),reset:e=>fc(e,bs),picture:({view:e})=>({kind:`rectilinear`,rotation:Cs(e),fieldOfView:e.fieldOfView,area:js})},xc=2;function Sc(e,t){let n=ac(e,t);return{...n,centre:{x:As,y:n.centre.y}}}function Cc(e,{viewport:t}){let n=Vs(xc,Ps(t));return{fitted:n,panorama:Sc(n,e.panorama)}}function wc(e,n,r){let{view:i}=e;return{...fc(e,ec(i,t(i.yaw+r),i.pitch)),panorama:n}}function Tc(e,n,r){let{fitted:i,panorama:a}=Cc(e,r),o=Fs(n,r.viewport);return wc(e,sc(i,a,{across:0,down:o.down}),t(-(cc(i,a,o).across*c)))}function Ec(e,t,n){let{fitted:r,panorama:i}=Cc(e,n);return wc(e,Sc(r,{...i,centre:{x:As,y:i.centre.y-t.pitch/s}}),t.yaw)}function Dc(e,n,r){let{fitted:i,panorama:a}=Cc(e,r),o=Sc(i,oc(i,a,n)),s=Is(ic(i,a),n.focus),l=Is(ic(i,o),n.focus);return wc(e,o,t((s.x-l.x)*c))}var Oc={normal:bc,equirectangular:{isStabilized:!0,canPan:()=>!0,pan:Tc,turn:Ec,zoom:Dc,reset:e=>({...fc(e,ec(e.view,t(0),e.view.pitch)),panorama:tc}),picture:(e,t)=>{let{fitted:n,panorama:r}=Cc(e,t);return{kind:`equirectangular`,rotation:Pr(l(e.view.yaw)),area:ic(n,r)}}},"raw-lenses":yc};function kc(e){return Oc[e]}var Ac=t(90);function jc(e,t){switch(e.kind){case`mei`:{let[n,r]=e.focal;return{...e,focal:[n*t,r*t]}}case`radial-polynomial`:{let[n,r,i,a]=e.coefficients;return{...e,coefficients:[n*t,r*t,i*t,a*t]}}}}var Mc=5,Nc={start:l(t(Ac-Mc)),end:l(t(Ac+Mc))};function Pc(e){let t=[];for(let n of e.sources)t.every(e=>!Lc(e,n))&&t.push({inputIndex:n.inputIndex,trackIndex:n.trackIndex});return t}function Fc(e){let{calibration:t,layout:n}=e;if(t.lenses.length!==n.sources.length)throw new j(`unsupported-layout`,`the calibration describes ${t.lenses.length} lenses but the layout has ${n.sources.length}`);let r=Pc(n);return N(e.displayConversions.length===r.length,`${e.displayConversions.length} display conversions for ${r.length} frame sources`),{lenses:n.sources.map(n=>{let i=Rc(t,n.lensIndex),a=r.findIndex(e=>Lc(e,n));return{lensIndex:n.lensIndex,frameSlot:a,region:n.region,window:zc(t,i),rotation:ss(i),projection:jc(i.model.projection,t.radialScale),halfFieldOfView:i.model.halfFieldOfView,displayConversion:Ic(e.displayConversions,a)}}),frameSlotCount:r.length,feather:Nc}}function Ic(e,t){let n=e[t];return N(n!==void 0,`no display conversion for frame slot ${t}`),n}function Lc(e,t){return e.inputIndex===t.inputIndex&&e.trackIndex===t.trackIndex}function Rc(e,t){let n=e.lenses.find(e=>e.lensIndex===t);if(!n)throw new j(`invalid-calibration`,`the calibration has no lens ${t}`);return n}function zc(e,t){let n=e.canvas.height;return{x:Math.floor(t.model.principalPoint.x/n)*n,y:0,width:n,height:n}}var Bc=class{parts;stabilizer=new Qo;constructor(e){this.parts=e}setStabilizer(e){this.stabilizer=e}present(e){let t=this.exposureTimeOf(e),n=this.parts.orientations.orientationAt(t);this.parts.sink.setStabilization(this.stabilizer.nextRotation(n,t)),this.parts.sink.present(e)}exposureTimeOf(e){let{timestamp:t}=e.pair;return this.parts.frameTimes?.midExposureAt(t)??t}};function Vc(e){let t=e instanceof Error?e:Error(`a failure went unheard`,{cause:e});Promise.reject(t)}var Hc=.5,Uc=class{meter;applyGains;reportFailure;matcher=new hs;lastMeasuredAt;inFlight;isStopped=!1;constructor(e,t,n=Vc){this.meter=e,this.applyGains=t,this.reportFailure=n}afterPresent(e){(this.lastMeasuredAt===void 0||Math.abs(e-this.lastMeasuredAt)>=Hc)&&!this.isStopped&&this.matchReporting(e)}matchNow(e){return this.inFlight??=this.measureAt(e),this.inFlight}stop(){this.isStopped=!0}async matchReporting(e){try{await this.matchNow(e)}catch(e){this.reportFailure(e)}}async measureAt(e){this.lastMeasuredAt=e;try{let t=await this.meter.measure();t&&!this.isStopped&&this.applyGains(this.matcher.update(t,e))}catch(e){throw this.isStopped=!0,e}finally{this.inFlight=void 0}}},Wc=[1,1,1],Gc=class{sink;renderer;active;lastMediaTime;constructor(e,t){this.sink=e,this.renderer=t}enable(){if(this.active)return;let{renderer:e}=this,t=e.createSeamMeter(),n=new Uc(t,t=>{e.setLensGains(t)});this.active={meter:t,matching:n}}disable(){this.stop();let e=Array.from({length:this.renderer.lensCount},()=>Wc);this.renderer.setLensGains(e)}async matchNow(){this.lastMediaTime!==void 0&&await this.active?.matching.matchNow(this.lastMediaTime)}present(e){this.sink.present(e),this.lastMediaTime=e.mediaTime,this.active?.matching.afterPresent(e.mediaTime)}dispose(){this.stop()}stop(){this.active?.matching.stop(),this.active?.meter.dispose(),this.active=void 0}},Kc=7,qc=.5,Jc=5,Yc=360;Ac-Kc,Math.round(14/qc),Math.round(Jc/qc);var Xc=Math.round(Yc/Jc);Array.from({length:Xc},()=>t(0));var Zc=[`bt709`,`bt470bg`,`smpte170m`,`bt2020`,`smpte432`],Qc=[`bt709`,`smpte170m`,`iec61966-2-1`,`linear`,`pq`,`hlg`],$c=[`rgb`,`bt709`,`bt470bg`,`smpte170m`,`bt2020-ncl`];function el(e,t){return e.find(e=>e===t)??`unspecified`}var tl={a:.17883277,b:.28466892,c:.55991073,segmentJoin:.5,squareSegmentDivisor:3,logSegmentDivisor:12},nl=[1.660491,-.5876411,-.0728499,-.1245505,1.1328999,-.0083494,-.0181508,-.1005789,1.1187297],rl=[.2126,.7152,.0722],il={exposure:1.4,kneeStart:.2,ceiling:1.5,exponent:2.2},al=/* @__PURE__ */ new Set([`bt709`,`bt470bg`,`smpte170m`,`unspecified`]),ol={bt709:Mr,bt2020:nl,unspecified:nl,bt470bg:void 0,smpte170m:void 0,smpte432:void 0};function sl({matrix:e}){return{kind:`as-recorded`,matrix:e}}function cl(e){let t=sl(e);return al.has(e.primaries)?{conversion:t}:{conversion:t,problem:`${e.primaries} primaries are shown as BT.709`}}function ll(e){let t=ol[e.primaries],n={kind:`hlg-to-sdr-bt709`,matrix:e.matrix,gamut:t??Mr,tone:il};return t===void 0?{conversion:n,problem:`HLG of ${e.primaries} primaries is shown without their gamut`}:{conversion:n}}function ul(e){return t=>({conversion:sl(t),problem:`the ${e} transfer cannot be shown yet: drawn as recorded`})}var dl={bt709:cl,smpte170m:cl,"iec61966-2-1":cl,unspecified:cl,hlg:ll,pq:ul(`pq`),linear:ul(`linear`)};function fl(e){let t=e.map(e=>dl[e.transfer](e)),n=t.flatMap(e=>e.problem===void 0?[]:[e.problem]);return{conversions:t.map(e=>e.conversion),warnings:[...new Set(n)]}}var pl={bt709:{red:.2126,blue:.0722},"bt2020-ncl":{red:.2627,blue:.0593},bt470bg:{red:.299,blue:.114},smpte170m:{red:.299,blue:.114},rgb:void 0,unspecified:void 0};function ml(e,t){let n=pl[e],r=pl[t];return n===void 0||r===void 0||e===t?Mr:Ir(hl(n),gl(r))}function hl({red:e,blue:t}){let n=1-e-t,r=2*(1-e),i=2*(1-t);return[1,0,r,1,-t*i/n,-e*r/n,1,i,0]}function gl({red:e,blue:t}){let n=1-e-t,r=2*(1-t),i=2*(1-e);return[e,n,t,-e/r,-n/r,(1-t)/r,(1-e)/i,-n/i,-t/i]}function _l(e){return Object.keys(e)}var vl=class{emitter;queue=[];depth=0;isDelivering=!1;isSuperseding=!1;constructor(e){this.emitter=e}change(e){this.depth===0&&this.isDelivering&&(this.isSuperseding=!0),this.depth+=1;try{return e()}finally{--this.depth,this.depth===0&&(this.isSuperseding=!1,this.deliver())}}emit(e,t){this.post(()=>{this.emitter.emit(e,t)})}post(e){this.isSuperseding&&=(this.queue.length=0,!1),this.queue.push(e),this.depth===0&&this.deliver()}deliver(){if(!this.isDelivering){this.isDelivering=!0;try{for(let e=this.queue.shift();e;e=this.queue.shift())e()}finally{this.isDelivering=!1}}}},yl={done:!0,value:void 0},bl=class{isEnded=!1;end(){this.isEnded=!0}hasEnded(){return this.isEnded}},xl=class{source;constructor(e){this.source=e}stream(e){return{[Symbol.asyncIterator]:()=>new Sl(this.source,e)}}},Sl=class{source;range;ending=new bl;constructor(e,t){this.source=e,this.range=t}async next(){if(await Promise.resolve(),this.ending.hasEnded())return yl;let e=await this.source.read(this.range);return this.ending.hasEnded()?yl:(this.ending.end(),e.byteLength===0?yl:{done:!1,value:e})}return(){return this.ending.end(),Promise.resolve(yl)}},Cl=class{parts;constructor(e){this.parts=e}get duration(){return this.parts.track.end}samplesFrom(e){let{download:t,track:n}=this.parts;return{[Symbol.asyncIterator]:()=>new wl(n,t.openCursor(n,n.sampleShownAt(e)??0,e))}}},wl=class{track;cursor;ending=new bl;constructor(e,t){this.track=e,this.cursor=t}async next(){let e=await this.cursor.nextSample();return!e||this.ending.hasEnded()?yl:{done:!1,value:{timestamp:this.track.timestampOf(e.sample),duration:this.track.durationOf(e.sample),data:Uint8Array.from(e.bytes)}}}return(){return this.ending.end(),this.cursor.close(),Promise.resolve(yl)}},Tl=class{parts;rejected=/* @__PURE__ */ new Set;constructor(e){this.parts=e}get description(){return this.parts.codec.description}decoderConfiguration(){return Promise.resolve(this.parts.codec.configuration)}keyframeAt(e){return Promise.resolve(this.timeOf(this.keyframeSampleAt(e)))}firstKeyframe(){return Promise.resolve(this.timeOf(this.firstKeyframeSample()))}packetsFrom(e){return{[Symbol.asyncIterator]:()=>new El({track:this.parts.track,open:()=>this.cursorFrom(e),reject:e=>{this.rejected.add(e)},packetOf:e=>this.packetOf(e)})}}sampleTimestamps(){return Promise.resolve(this.parts.track.timestampsInPresentationOrder())}frameCount(){return Promise.resolve(this.parts.track.sampleCount)}cursorFrom(e){let t=this.keyframeSampleAt(e)??this.firstKeyframeSample();return t===void 0?void 0:this.parts.download.openCursor(this.parts.track,t,e)}keyframeSampleAt(e){let{track:t}=this.parts,n=t.keyframeAt(e);for(;n!==void 0&&this.rejected.has(n);)n=t.syncSampleAtOrBefore(n-1);return n}firstKeyframeSample(){let{track:e}=this.parts,t=e.syncSampleAtOrAfter(0);for(;t!==void 0&&this.rejected.has(t);)t=e.syncSampleAtOrAfter(t+1);return t}timeOf(e){let{track:t}=this.parts;return e===void 0?void 0:{timestamp:t.timestampOf(e),duration:t.durationOf(e)}}packetOf(e){let{track:t}=this.parts;return{timestamp:t.timestampOf(e.sample),duration:t.durationOf(e.sample),isKeyFrame:t.isSync(e.sample)&&!this.rejected.has(e.sample),data:e.bytes}}},El=class{parts;cursor;isVerified=!1;ending=new bl;constructor(e){this.parts=e,this.cursor=e.open()}async next(){if(this.ending.hasEnded())return yl;let{cursor:e}=this;if(!e)throw new j(`no-key-frame`,`track ${this.parts.track.trackId} has no key frame`);let t=await e.nextSample();return!t||this.ending.hasEnded()?yl:!this.isVerified&&!this.parts.track.keyframeRule.isKeyframe(t.bytes)?this.startEarlier(e,t):(this.isVerified=!0,{done:!1,value:this.parts.packetOf(t)})}return(){return this.ending.end(),this.cursor?.close(),Promise.resolve(yl)}startEarlier(e,t){return this.parts.reject(t.sample),e.close(),this.cursor=this.parts.open(),this.next()}},Dl=class e{ranges;static empty=new e([]);constructor(e){this.ranges=e}static of(t){let n=t.filter(e=>e.length>0).toSorted((e,t)=>e.offset-t.offset);return new e(Ol(n,0))}get isEmpty(){return this.ranges.length===0}get totalLength(){return this.ranges.reduce((e,t)=>e+t.length,0)}union(t){return e.of([...this.ranges,...t.ranges])}subtract(t){return new e(this.ranges.flatMap(e=>kl(e,t.ranges)))}covers(e){return e.length===0||this.ranges.some(t=>t.contains(e))}overlaps(e){return this.ranges.some(t=>t.overlaps(e))}bridgingGapsBelow(t){return new e(Ol(this.ranges,t))}};function Ol(e,t){let n=[];for(let r of e){let e=n.at(-1),i=e!==void 0&&r.offset-e.end<Math.max(t,1);e&&i?n[n.length-1]=Al(e.offset,r.end,e.end):n.push(r)}return n}function kl(e,t){let n=[],r=e.offset;for(let i of t)i.end<=r||i.offset>=e.end||(i.offset>r&&n.push(Fn.of(r,i.offset-r)),r=Math.max(r,i.end));return r<e.end&&n.push(Fn.of(r,e.end-r)),n}function Al(e,t,n){return Fn.of(e,Math.max(t,n)-e)}var jl=class{range;bytes;filled=0;isComplete=!1;constructor(e,t){this.range=e,this.bytes=t}get filledRange(){return Fn.of(this.range.offset,this.filled)}},Ml=class{blocks=[];get held(){return Dl.of(this.blocks.map(e=>e.filledRange))}get allocatedBytes(){return this.blocks.reduce((e,t)=>e+t.bytes.byteLength,0)}allocate(e){let t=new jl(e,new Uint8Array(e.length));return this.blocks.push(t),t}write(e,t){let n=this.fillingOf(e);n.bytes.set(t,n.filled),n.filled+=t.byteLength}complete(e){this.fillingOf(e).isComplete=!0}trim(e){let t=this.fillingOf(e);t.isComplete=!0,t.bytes=t.bytes.slice(0,t.filled),this.blocks=this.blocks.filter(e=>e.bytes.byteLength>0)}bytesOf(e){let t=this.blocks.find(t=>t.filledRange.contains(e));return t?Nl(t,e):this.held.covers(e)?this.copyOf(e):void 0}release(e){this.blocks=this.blocks.filter(t=>!t.isComplete||!e.covers(t.filledRange))}fillingOf(e){let t=this.blocks.find(t=>t===e);return N(t!==void 0,`the block is not one this store holds`),t}copyOf(e){let t=new Uint8Array(e.length);for(let n of this.blocks){let r=Math.max(n.range.offset,e.offset),i=Math.min(n.filledRange.end,e.end);r<i&&t.set(n.bytes.subarray(r-n.range.offset,i-n.range.offset),r-e.offset)}return t}};function Nl(e,t){let n=t.offset-e.range.offset;return e.bytes.subarray(n,n+t.length)}var Pl=class{track;host;target;next;waiter;isClosed=!1;constructor(e,t,n){this.track=e,this.host=n,this.next=t.sample,this.target=t.target}get position(){return this.next}get isWaiting(){return this.waiter!==void 0}nextSample(){if(this.isClosed||this.next>=this.track.sampleCount)return Promise.resolve(void 0);N(this.waiter===void 0,`a cursor reads one sample at a time`);let e=this.track.rangeOf(this.next),t=this.host.bytesOf(e);if(t)return Promise.resolve(this.take(t));let n=this.host.failureOf(e);return n===void 0?this.waitForBytes(e):Promise.reject(n)}serve(){let{waiter:e}=this,t=e&&this.host.bytesOf(this.track.rangeOf(this.next));e&&t&&(this.waiter=void 0,e.resolve(this.take(t)))}fail(e,t){let{waiter:n}=this;n!==void 0&&e.overlaps(this.track.rangeOf(this.next))&&(this.waiter=void 0,n.reject(t))}close(){this.isClosed||(this.isClosed=!0,this.waiter?.resolve(void 0),this.waiter=void 0,this.host.closed(this))}waitForBytes(e){return new Promise((t,n)=>{this.waiter={resolve:t,reject:n},this.host.waiting(e)})}take(e){let t=this.next;return this.next+=1,this.host.movedOn(e.byteLength),{sample:t,bytes:e}}},Fl=class{parts;nextId=1;running=/* @__PURE__ */ new Map;constructor(e){this.parts=e}get states(){return[...this.running.values()].map(e=>({id:e.id,remaining:Il(e)}))}isBringing(e){for(let t of this.running.values())if(t.block.range.contains(e))return!0;return!1}start(e){let t={id:this.nextId,block:this.parts.store.allocate(e),chunks:this.parts.stream.stream(e)[Symbol.asyncIterator](),delivered:0};this.nextId+=1,this.running.set(t.id,t),this.pump(t)}cancel(e){let t=this.running.get(e);t&&(this.running.delete(e),t.chunks.return?.(),this.parts.store.trim(t.block))}cancelAll(){for(let e of this.running.keys())this.cancel(e)}async pump(e){try{for(let t=await e.chunks.next();t.done!==!0;t=await e.chunks.next()){if(!this.isRunning(e))return;this.parts.store.write(e.block,t.value),e.delivered+=t.value.byteLength,this.parts.listener.onChunk()}this.finish(e)}catch(t){this.fail(e,t)}}finish(e){this.isRunning(e)&&(this.running.delete(e.id),this.parts.store.complete(e.block),this.parts.listener.onEnd())}fail(e,t){this.isRunning(e)&&(this.running.delete(e.id),this.parts.store.trim(e.block),this.parts.listener.onFailure(Il(e),t))}isRunning(e){return this.running.get(e.id)===e}};function Il(e){let{range:t}=e.block;return Fn.of(t.offset+e.delivered,t.length-e.delivered)}function Ll(e,t){let{track:n}=e,r=[];for(let i=e.sample;i<n.sampleCount&&!(n.timestampOf(i)>t);i+=1)r.push(n.rangeOf(i));return r}function Rl(e,t){let n=[],r=t;for(let t of e.ranges){if(r<=0)break;n.push(Fn.of(t.offset,Math.min(t.length,r))),r-=t.length}return Dl.of(n)}function zl(e){let{policy:t}=e,n=R(e.time+t.resumeSeconds),r=e.cursors.filter(e=>e.track.kind===`video`),i=Dl.of(r.flatMap(e=>Ll(e,n))),a=Math.min(t.requestSize,t.refillBytes);return Rl(i,t.aheadBytes-a)}function Bl(e){return zl(e).subtract(e.held).isEmpty}function Vl(e){let t=e.cursors.filter(e=>Yl(e)),n=t.length>0?Wl(t):e.anchor,r=n??Hl(e);if(!r)return Ul(e);let i=e.isReadingAhead?e.policy.aheadSeconds:0,a=R(r.time+i),o=Gl({state:e,windowStart:r,windowEnd:a}).bridgingGapsBelow(e.policy.bridgedGap),s=e.transfers.filter(e=>e.remaining.length===0||o.overlaps(e.remaining)),c=Dl.of(s.map(e=>e.remaining)),l=o.subtract(e.held).subtract(c).subtract(e.unreadable),u=e.policy.requestsInFlight-s.length;return{start:Zl({state:e,windowStart:r,windowEnd:a,missing:l,threshold:Xl(e,r)})?$l(l,e.policy,u):[],cancel:e.transfers.filter(e=>!s.includes(e)).map(e=>e.id),release:e.held.subtract(o.union(eu(r,e.policy))),anchor:n}}function Hl(e){return e.isReadingAhead&&e.cursors.length>0?Wl(e.cursors):void 0}function Ul(e){return{start:[],cancel:e.transfers.map(e=>e.id),release:Dl.empty,anchor:void 0}}function Wl(e){return{time:R(Math.min(...e.map(e=>ru(e)))),offset:Math.min(...e.map(e=>au(e))),keyframeOffset:Math.min(...e.map(e=>iu(e)))}}function Gl(e){let{state:t,windowEnd:n}=e,r=t.cursors.filter(t=>Kl(t,e)),i=r.flatMap(e=>Ll(e,Jl(n,e.target))),a=r.filter(e=>ql(e,n)),o=Dl.of(a.map(e=>e.track.rangeOf(e.sample)));return Rl(Dl.of(i),t.policy.aheadBytes).union(o)}function Kl(e,t){return ru(e)>=t.windowStart.time-t.state.policy.keepBehindSeconds}function ql(e,t){let n=e.isWaiting&&ru(e)<=t;return!nu(e)&&(Yl(e)||n)}function Jl(e,t){return t!==void 0&&t>e?t:e}function Yl(e){return e.track.kind===`video`}function Xl(e,t){let n={cursors:e.cursors,time:t.time,policy:e.policy};return e.isReadingAhead?zl(n):Dl.empty}function Zl(e){let{state:t,missing:n,threshold:r}=e;return n.ranges.some(e=>r.overlaps(e))?!0:t.cursors.some(t=>Ql(t,e)&&n.overlaps(t.track.rangeOf(t.sample)))||n.totalLength>=t.policy.refillBytes}function Ql(e,t){if(!e.isWaiting||nu(e))return!1;let{windowStart:n,state:r}=t,i=n.time+(r.isReadingAhead?r.policy.resumeSeconds:0);return Yl(e)||ru(e)<=i}function $l(e,t,n){let r=[];for(let i of e.ranges)for(let e=i.offset;e<i.end&&r.length<n;e+=t.requestSize)r.push(Fn.of(e,Math.min(t.requestSize,i.end-e)));return r}function eu(e,t){let n=tu(e,t);return Dl.of([Fn.of(n,e.offset-n)])}function tu(e,t){return Math.max(0,Math.min(e.keyframeOffset,e.offset-t.keepBehindBytes))}function nu(e){return e.sample>=e.track.sampleCount}function ru(e){return nu(e)?e.track.end:e.track.timestampOf(e.sample)}function iu(e){let{track:t}=e,n=Math.min(e.sample,t.sampleCount-1),r=t.syncSampleAtOrBefore(n);return r===void 0?au(e):t.rangeOf(r).offset}function au(e){let{track:t}=e;return nu(e)?t.sampleCount>0?t.rangeOf(t.sampleCount-1).end:0:t.rangeOf(e.sample).offset}var ou=Fn.of(0,2**53-1),su=class{parts;store=new Ml;progressListeners=/* @__PURE__ */ new Set;transfers;cursors=/* @__PURE__ */ new Set;host;failures=[];anchor;isReadingAhead=!1;isPlanDue=!1;takenSincePlan=0;isDisposed=!1;constructor(e){this.parts=e,this.transfers=new Fl({stream:e.stream,store:this.store,listener:{onChunk:()=>{this.serveCursors();for(let e of this.progressListeners)e()},onEnd:()=>{this.schedulePlan()},onFailure:(e,t)=>{this.fail(e,t)}}}),this.host=this.cursorHost()}openCursor(e,t,n){N(this.parts.table.tracks.includes(e),`the track is not one of this file`);let r=new Pl(e,{sample:t,target:n},this.host);return this.isDisposed?(r.close(),r):(this.failures=[],this.cursors.add(r),this.schedulePlan(),r)}startReadingAhead(){this.isReadingAhead=!0,this.schedulePlan()}isReadyToResumeAt(e){return Bl({cursors:this.positions(),held:this.store.held,time:e,policy:this.parts.policy})}onProgress(e){let t=()=>{e()};return this.progressListeners.add(t),()=>{this.progressListeners.delete(t)}}dispose(){this.isDisposed=!0,this.transfers.cancelAll();for(let e of this.cursors)e.close()}cursorHost(){return{bytesOf:e=>this.store.bytesOf(e),failureOf:e=>this.failures.find(t=>t.range.overlaps(e))?.error,movedOn:e=>{this.takenSincePlan+=e,this.takenSincePlan>=this.parts.policy.replanBytes&&this.schedulePlan()},waiting:e=>{this.transfers.isBringing(e)||this.schedulePlan()},closed:e=>{this.cursors.delete(e),this.schedulePlan()}}}schedulePlan(){this.isPlanDue||this.isDisposed||(this.isPlanDue=!0,this.planAfterThisTurn())}async planAfterThisTurn(){if(await Promise.resolve(),this.isPlanDue=!1,!this.isDisposed)try{this.plan()}catch(e){this.failEveryRead(e)}}failEveryRead(e){let t=ne(e,`invariant-violation`,`the download could not plan`);this.failures.push({range:ou,error:t});for(let e of this.cursors)e.fail(ou,t)}plan(){this.takenSincePlan=0;let e=Vl({cursors:this.positions(),held:this.store.held,transfers:this.transfers.states,unreadable:Dl.of(this.failures.map(e=>e.range)),isReadingAhead:this.isReadingAhead,anchor:this.anchor,policy:this.parts.policy});this.anchor=e.anchor,this.carryOut(e)}positions(){return[...this.cursors].map(e=>({track:e.track,sample:e.position,isWaiting:e.isWaiting,target:e.target}))}carryOut(e){for(let t of e.cancel)this.transfers.cancel(t);this.store.release(e.release);for(let t of e.start)this.transfers.start(t)}serveCursors(){for(let e of this.cursors)e.serve()}fail(e,t){let n=ne(t,`source-unreadable`,`a range of the recording could not be read`);this.failures.push({range:e,error:n});for(let t of this.cursors)t.fail(e,n);this.schedulePlan()}};function cu(e){let t=new su(e);return{download:t,videoTracks:e.codecs.video.map(n=>new Tl({download:t,track:lu(e.table,n.trackId,`video`),codec:n})),audioTracks:e.codecs.audio.map(n=>({samples:new Cl({download:t,track:lu(e.table,n.trackId,`audio`)}),configuration:n.configuration})),duration:e.table.duration,dispose:()=>{t.dispose()}}}function lu(e,t,n){let r=e.trackWithId(t);if(r?.kind!==n)throw new j(`unsupported-container`,`the movie box has no ${n} track ${t} to read`);return r}var uu=1048576,du=10,fu=128,pu=2,mu=32,hu=8,gu=2,_u=1,vu=.25,yu=16,bu=4;function xu(e,t){let n=e.size/e.duration,r=Math.min(Math.round(du*n),fu*uu/t),i=Math.round(r*vu);return{aheadSeconds:R(du),aheadBytes:r,keepBehindBytes:Math.min(Math.round(pu*n),mu*uu/t),keepBehindSeconds:R(pu),requestSize:hu*uu,requestsInFlight:gu,bridgedGap:_u*uu,refillBytes:i,replanBytes:Math.round(i/yu),resumeSeconds:R(bu)}}var Su=class{files;constructor(e){this.files=e}isReadyToResumeAt(e){return this.files.every(t=>t.isReadyToResumeAt(e))}onProgress(e){let t=this.files.map(t=>t.onProgress(e));return()=>{for(let e of t)e()}}};function Cu(e){for(let t of e.frames)t.close()}var wu=class{capacity;onPush;pairs=[];roomWaiters=[];isClosed=!1;constructor(e,t=Tu){this.capacity=e,this.onPush=t,N(Number.isSafeInteger(e)&&e>0,`queue capacity must be positive`)}get length(){return this.pairs.length}get isFull(){return this.pairs.length>=this.capacity}get isClosedForGood(){return this.isClosed}waitForRoom(){return!this.isFull||this.isClosed?Promise.resolve():new Promise(e=>{this.roomWaiters.push(e)})}push(e){if(this.isClosed){Cu(e);return}this.pairs.push(e),this.onPush()}takePairAt(e){let t;for(;this.pairs.length>0&&(this.pairs[0]?.timestamp??1/0)<=e;)t&&Cu(t),t=this.pairs.shift();return t&&this.wakeWaiters(),t}peekTimestamp(){return this.pairs[0]?.timestamp}newestTimestamp(){return this.pairs.at(-1)?.timestamp}close(){this.isClosed=!0;for(let e of this.pairs)Cu(e);this.pairs.length=0,this.wakeWaiters()}wakeWaiters(){if(this.isFull&&!this.isClosed)return;let e=this.roomWaiters;this.roomWaiters=[];for(let t of e)t()}};function Tu(){}var Eu=class{tolerance;onPair;queues;unpairedCount=0;constructor(e,t,n){this.tolerance=t,this.onPair=n,this.queues=Array.from({length:e},()=>[])}get unpaired(){return this.unpairedCount}push(e,t){ae(e,this.queues.length,`frame source`),this.queues[e]?.push(t),this.drain()}discardAll(){for(let e of this.queues){for(let t of e)t.close();e.length=0}}drain(){for(;this.queues.every(e=>e.length>0);){let e=this.queues.map(e=>e[0]).filter(e=>e!==void 0),t=Math.min(...e.map(e=>e.timestamp));e.every(e=>Math.abs(e.timestamp-t)<=this.tolerance)?this.emit(e,R(t)):this.dropHeadAt(t)}}emit(e,t){for(let e of this.queues)e.shift();this.onPair({timestamp:t,frames:e})}dropHeadAt(e){this.queues.find(t=>t[0]?.timestamp===e)?.shift()?.close(),this.unpairedCount+=1}},Du=class{from;deliver;held;droppedCount=0;constructor(e,t){this.from=e,this.deliver=t}get dropped(){return this.droppedCount}push(e){if(e.timestamp>=this.from){this.release(),this.deliver(e);return}this.hold(e)}release(){if(!this.held)return;let e=this.held;this.held=void 0,this.deliver(e)}discard(){this.held&&Cu(this.held),this.held=void 0}hold(e){this.held&&(Cu(this.held),this.droppedCount+=1),this.held=e}},Ou=class{promise;isSettledNow=!1;resolvePromise;rejectPromise;constructor(){this.promise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})}get isSettled(){return this.isSettledNow}resolve(e){this.isSettledNow||(this.isSettledNow=!0,this.resolvePromise?.(e))}reject(e){this.isSettledNow||(this.isSettledNow=!0,this.rejectPromise?.(e))}async follow(e){try{this.resolve(await e)}catch(e){this.reject(e)}}},ku=Symbol(`stopped`),Au=class{isStopped=!1;wakeWaiter;get wasStopped(){return this.isStopped}stop(){this.isStopped=!0,this.wakeWaiter?.()}async race(e){if(this.isStopped)return ku;N(this.wakeWaiter===void 0,`a run stop races one wait at a time`);let t=new Promise(e=>{this.wakeWaiter=()=>{e(ku)}});try{return await Promise.race([e(),t])}finally{this.wakeWaiter=void 0}}},ju=class{frameSources;decoderPort;options;stop=new Au;hasRun=!1;iterators=[];constructor(e,t,n){if(this.frameSources=e,this.decoderPort=t,this.options=n,e.length===0)throw new j(`invariant-violation`,`a decode pipeline needs at least one frame source`)}async run(e,t){N(!this.hasRun,`a decode pipeline runs once; create a new one for each run`),this.hasRun=!0;let n=await this.openRun(e,t);try{let e=await this.feed(n);if(await Nu(n,e),n.failure.isSettled)throw await n.failure.promise;return Lu(n,e)}finally{Fu(n)}}abort(){this.stop.stop(),Iu(this.iterators)}async openRun(e,t){let{stop:n}=this,r=new Ou,i={packets:0,pairs:0},a=new Du(e,e=>{i.pairs+=1,t.push(e)}),o=new Eu(this.frameSources.length,this.options.pairTolerance,e=>{a.push(e)}),s=n.wasStopped?[]:this.packetIteratorsFrom(e);this.iterators=s;let c=e=>{r.resolve(e),n.stop()};try{return{output:t,stop:n,failure:r,tally:i,gate:a,pairer:o,iterators:s,decoders:n.wasStopped?[]:await this.createDecoders(o,c)}}catch(e){throw Iu(s),e}}async createDecoders(e,t){let n=await Promise.allSettled(this.frameSources.map(async(n,r)=>this.decoderPort.create(await n.decoderConfiguration(),{onFrame:t=>{e.push(r,t)},onError:t}))),r=n.flatMap(e=>e.status===`fulfilled`?[e.value]:[]),i=n.find(e=>e.status===`rejected`);if(i){for(let e of r)e.close();throw Ru(i.reason)}return r}async feed(e){for(;!Mu(e);){if(await e.stop.race(()=>e.output.waitForRoom()),Mu(e))return!1;let t=await e.stop.race(()=>zu(e.iterators));if(t===ku)return!1;if(!t)return!0;await this.decodeRound(e,t)}return!1}async decodeRound(e,t){for(let[n,r]of e.decoders.entries()){let i=t[n];if(i){if(await e.stop.race(()=>r.waitForPendingBelow(this.options.maxPendingPackets)),Mu(e))return;r.decode(i),e.tally.packets+=1}}}packetIteratorsFrom(e){return this.frameSources.map(t=>t.packetsFrom(e)[Symbol.asyncIterator]())}};function Mu(e){return e.stop.wasStopped||e.output.isClosedForGood}async function Nu(e,t){await e.stop.race(()=>Pu(e.decoders,e.failure))!==ku&&t&&e.gate.release()}async function Pu(e,t){try{await Promise.all(e.map(e=>e.flush()))}catch(e){if(!t.isSettled)throw e}}function Fu(e){for(let t of e.decoders)t.close();e.pairer.discardAll(),e.gate.discard(),Iu(e.iterators)}function Iu(e){for(let t of e)t.return?.()}function Lu(e,t){return{packetsDecoded:e.tally.packets,pairsDelivered:e.tally.pairs,unpairedFrames:e.pairer.unpaired,pairsDroppedBeforeStart:e.gate.dropped,hasReachedEnd:t}}function Ru(e){return e instanceof Error?e:new j(`decode`,`a decoder could not be created`,{cause:e})}async function zu(e){let t=await Promise.all(e.map(e=>e.next())),n=[];for(let e of t){if(e.done===!0)return;n.push(e.value)}return n}var Bu={verdict:`decodes`,detail:void 0},Vu={verdict:`no-key-frame`,detail:`the track has no key frame`},Hu={verdict:`decode-failed`,detail:`the decoder accepted the first key frame but produced no picture`},Uu={verdict:`timed-out`,detail:`the decoder produced no picture before the deadline`},Wu={verdict:`key-frame-late`,detail:`the first key frame did not arrive before the deadline`};async function Gu(e,t,n){let r=e.map(e=>new Ju(e,t));try{let e=await Promise.all(r.map(e=>Ku(e,n)));return{canDecode:e.every(e=>e.verdict===`decodes`),sources:e}}finally{for(let e of r)e.close()}}async function Ku(e,t){try{let n=await Promise.race([e.run(),qu(t,e)]);return{track:e.track.description,...n}}finally{e.close()}}async function qu(e,t){return await e.promise,t.outcomeAtDeadline}var Ju=class{track;decoderPort;decoder;firstOutcome;isClosed=!1;isReadingKeyFrame=!1;constructor(e,t){this.track=e,this.decoderPort=t}get outcomeAtDeadline(){return this.isReadingKeyFrame?Wu:Uu}async run(){let e=await this.track.decoderConfiguration();if(!await this.decoderPort.isSupported(e))return Yu(e);if(this.isClosed)return Uu;let t=await this.track.firstKeyframe();if(!t)return Vu;this.isReadingKeyFrame=!0;let n=await Zu(this.track,t.timestamp);return this.isReadingKeyFrame=!1,n?await this.decodeFirst(e,n):Vu}close(){this.isClosed=!0,this.decoder?.close(),this.decoder=void 0,this.firstOutcome?.resolve(Uu)}async decodeFirst(e,t){if(this.isClosed)return Uu;let n=new Ou;this.firstOutcome=n;let r=await this.openDecoder(e,n);return r===void 0?n.promise:(this.decoder=r,this.decodeInto(r,t,n),n.promise)}async openDecoder(e,t){try{let n=await this.decoderPort.create(e,{onFrame:e=>{e.close(),t.resolve(Bu)},onError:e=>{t.resolve(Xu(e))}});if(!this.isClosed)return n;n.close(),t.resolve(Uu)}catch(e){t.resolve(Xu(e))}}async decodeInto(e,t,n){try{e.decode(t),await e.flush(),n.resolve(Hu)}catch(e){n.resolve(Xu(e))}}};function Yu(e){return{verdict:`unsupported-configuration`,detail:`${e.codec} at ${e.codedWidth}x${e.codedHeight} is not supported here`}}function Xu(e){let t=ie(e);return{verdict:M(e,`codec-unsupported`)?`unsupported-configuration`:`decode-failed`,detail:t}}async function Zu(e,t){let n=e.packetsFrom(t)[Symbol.asyncIterator]();try{let e=await n.next();return e.done===!0?void 0:e.value}finally{n.return?.()}}var Qu=class{now;hasEnded=!1;failure=void 0;isRunningNow=!1;positionAtAnchor=R(0);anchorMs=0;constructor(e){this.now=e}get isRunning(){return this.isRunningNow}get currentTime(){if(!this.isRunningNow)return this.positionAtAnchor;let e=gt(pt(this.now()-this.anchorMs));return R(this.positionAtAnchor+e)}start(){return this.isRunningNow||=(this.anchorMs=this.now(),!0),Promise.resolve()}pause(){this.isRunningNow&&=(this.positionAtAnchor=this.currentTime,!1)}seek(e){this.positionAtAnchor=e,this.anchorMs=this.now()}dispose(){this.pause()}},$u={ready:[`playing`,`buffering`,`paused`,`seeking`,`error`,`disposed`],playing:[`buffering`,`paused`,`seeking`,`ended`,`error`,`disposed`],buffering:[`playing`,`paused`,`seeking`,`error`,`disposed`],paused:[`playing`,`buffering`,`seeking`,`error`,`disposed`],seeking:[`buffering`,`paused`,`error`,`disposed`],ended:[`seeking`,`error`,`disposed`],error:[`disposed`],disposed:[]},ed=/* @__PURE__ */ new Set([`playing`,`buffering`]);function td(e){return e!==void 0&&ed.has(e)}var nd=class{current=`ready`;get state(){return this.current}canTransitionTo(e){return $u[this.current].includes(e)}transitionTo(e){if(!this.canTransitionTo(e))throw new j(`invariant-violation`,`player cannot go from ${this.current} to ${e}`);this.current=e}isOneOf(...e){return e.includes(this.current)}},rd=class{reportListenerError;listeners=/* @__PURE__ */ new Map;constructor(e=Vc){this.reportListenerError=e}on(e,t){let n=this.listeners.get(e)??/* @__PURE__ */ new Set;return n.add(t),this.listeners.set(e,n),()=>{n.delete(t)}}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r=[...n];for(let e of r)if(n.has(e))try{e(t)}catch(e){this.reportListenerError(e)}}removeAll(){for(let e of this.listeners.values())e.clear();this.listeners.clear()}},id=1,ad=.25,od=class{position;previousPlayingTick;placedAt(e){this.position=e}stoppedAt(e){(this.position===void 0||e>=this.position)&&(this.position=e)}playingFrom(e){this.previousPlayingTick=e}wasMovedFromOutside({now:e,state:t}){let n=this.position;return this.position=e,n!==void 0&&(t===`playing`?n-e:Math.abs(e-n))>ad}wereTicksMissed({now:e,state:t}){let n=t===`playing`,r=this.previousPlayingTick;this.previousPlayingTick=n?e:void 0;let i=r===void 0?0:e-r;return n&&i>id}};function sd(e){return!e.isRunning&&!e.hasEnded}function cd(e,t){return e.hasEnded||e.currentTime>=t}var ld=class{generation=0;scrubs=0;isFromFlowing=!1;get resumesPlaying(){return this.isFromFlowing}begin(e){this.isFromFlowing=td(e),this.generation+=1}claimScrub(){return this.scrubs+=1,{seek:this.generation,scrub:this.scrubs}}isScrubCurrent(e){return e.seek===this.generation&&e.scrub===this.scrubs}},ud=.25,dd=class{lifecycle;announced;constructor(e){this.lifecycle=e}announce(e){this.announced=e,this.lifecycle.announce(`timeupdate`,e)}followPlayback(e){let{announced:t}=this;(t===void 0||Math.abs(e-t)>=ud)&&this.announce(e)}},fd=class{lifecycle;cause=`priming`;startAttempt;constructor(e){this.lifecycle=e}get waitingStart(){return this.startAttempt?.promise}enter(e){this.cause=e,this.lifecycle.moveTo(`buffering`)}enterForStart(){let e=new Ou;return this.startAttempt=e,this.enter(`priming`),e.promise}isOverAt(e,t){return!e||!this.lifecycle.is(`buffering`)?!1:this.cause===`priming`?e.isPrimedAt(t):e.isReadyToResumeAt(t)}takeStart(){let e=this.startAttempt;return this.startAttempt=void 0,e}settleStart(){this.takeStart()?.resolve()}},pd=class{machine=new nd;outbox;constructor(e){this.outbox=new vl(e)}get current(){return this.machine.state}is(e){return this.machine.state===e}isOneOf(...e){return this.machine.isOneOf(...e)}canMoveTo(e){return this.machine.canTransitionTo(e)}moveTo(e){this.machine.transitionTo(e),this.announce(`statechange`,e)}announce(e,t){this.outbox.emit(e,t)}change(e){return this.outbox.change(e)}},md=2,hd=.25,gd=class e{parts;listener;queue;pipeline;primingPairs;stopFollowingBuffer;isAborted=!1;hasReachedEnd=!1;hasHandedOutPair=!1;constructor(e,t){this.parts=e,this.listener=t,this.primingPairs=Math.min(md,e.queueCapacity),this.queue=new wu(e.queueCapacity,()=>{this.isAborted||t.onProgress()}),this.stopFollowingBuffer=e.buffer?.onProgress(()=>{t.onProgress()})??(()=>void 0),this.pipeline=new ju(e.frameSources,e.decoderPort,e.pipeline)}static start(t,n,r){let i=new e(t,r);return i.follow(i.pipeline.run(n,i.queue)),i}get isDrained(){return this.hasReachedEnd&&this.queue.length===0}isPrimedAt(e){let t=(this.queue.newestTimestamp()??-1/0)>=e;return this.hasReachedEnd||t&&this.queue.length>=this.primingPairs}isReadyToResumeAt(e){return this.isPrimedAt(e)&&(this.hasReachedEnd||(this.parts.buffer?.isReadyToResumeAt(e)??!0))}isStarvedAt(e,t){let n=this.queue.length===0&&!this.hasReachedEnd,r=e-(t??-1/0);return n&&r>hd}takePairAt(e){let t=this.queue.peekTimestamp(),n=!this.hasHandedOutPair&&t!==void 0,r=this.queue.takePairAt(n?R(Math.max(e,t)):e);return r&&(this.hasHandedOutPair=!0),r}abort(){this.isAborted=!0,this.stopFollowingBuffer(),this.pipeline.abort(),this.queue.close()}async follow(e){try{let{hasReachedEnd:t}=await e;if(this.isAborted)return;this.hasReachedEnd=t,this.listener.onProgress()}catch(e){this.isAborted||this.listener.onFailure(e)}}};async function _d(e,t){try{return(await e.keyframeAt(t))?.timestamp??t}catch{return t}}var vd=class{parts;events=new rd;lifecycle=new pd(this.events);run;presented;timeUpdates=new dd(this.lifecycle);buffering=new fd(this.lifecycle);clockWatch=new od;seeks=new ld;constructor(e){this.parts=e}get state(){return this.lifecycle.current}get currentTime(){return this.parts.clock.currentTime}async play(){if(this.lifecycle.current!==`playing`){if(this.lifecycle.current===`buffering`){await this.buffering.waitingStart;return}await this.lifecycle.change(()=>this.beginStart())}}pause(){this.lifecycle.change(()=>{let e=this.parts.clock.isRunning;this.parts.clock.pause(),e&&this.clockWatch.stoppedAt(this.parts.clock.currentTime),this.lifecycle.canMoveTo(`paused`)&&(this.lifecycle.moveTo(`paused`),this.buffering.settleStart(),this.timeUpdates.announce(this.parts.clock.currentTime))})}stop(){this.lifecycle.change(()=>{this.pause(),this.seek(R(0))})}seek(e){this.lifecycle.isOneOf(`disposed`,`error`)||this.lifecycle.change(()=>{let t=R(yr(e,0,this.parts.duration));this.seeks.begin(this.lifecycle.current),this.moveClockTo(t),this.startRun(t),this.lifecycle.moveTo(`seeking`),this.seeks.resumesPlaying?this.buffering.enter(`priming`):this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(t)})}async scrub(e){let[t]=this.parts.frameSources;if(!t||this.lifecycle.isOneOf(`disposed`,`error`))return;let n=R(yr(e,0,this.parts.duration)),r=this.seeks.claimScrub(),i=await _d(t,n);this.seeks.isScrubCurrent(r)&&!this.lifecycle.isOneOf(`disposed`,`error`)&&this.seek(i)}preload(){this.run||this.lifecycle.current!==`ready`||this.lifecycle.change(()=>{this.startRun(this.parts.clock.currentTime)})}tick(){this.lifecycle.isOneOf(`disposed`,`error`)||this.lifecycle.change(()=>{let{failure:e}=this.parts.clock;if(e){this.fail(e);return}let t=this.parts.clock.currentTime;if(this.clockWatch.wasMovedFromOutside({now:t,state:this.lifecycle.current})){this.followMoveFromOutside(t);return}if(this.haveTicksStopped(t)){this.restartAt(t);return}this.presentDue(t),this.lifecycle.is(`playing`)?this.followClock(t):this.isStartedFromOutside()&&this.followStartFromOutside()})}redraw(){if(!this.presented||this.lifecycle.isOneOf(`playing`,`error`))return;let{presented:e}=this;this.lifecycle.change(()=>this.draw(e))}dispose(){this.lifecycle.current!==`disposed`&&(this.lifecycle.change(()=>{this.abortRun(),this.presented&&Cu(this.presented.pair),this.presented=void 0,this.parts.clock.pause(),this.lifecycle.moveTo(`disposed`),this.buffering.settleStart()}),this.events.removeAll())}beginStart(){if(this.isAtTheEnd()&&this.seek(R(0)),this.lifecycle.canMoveTo(`buffering`))return this.run||this.startRun(this.parts.clock.currentTime),this.isPrimed()?(this.enterPlaying(),this.startClockOnceHeard()):this.startOncePrimed()}startOncePrimed(){return this.parts.clock.pause(),this.buffering.enterForStart()}async startClockOnceHeard(){await Promise.resolve(),this.lifecycle.is(`playing`)&&await this.startClock()}enterPlaying(){this.clockWatch.playingFrom(this.parts.clock.currentTime),this.lifecycle.moveTo(`playing`)}presentDue(e){let t=this.run?.takePairAt(e);t&&this.present(t,e)}followClock(e){if(this.isPlayedOut(e)){this.end();return}if(sd(this.parts.clock)){this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(e);return}if(this.run?.isStarvedAt(e,this.presented?.pair.timestamp)===!0){this.parts.clock.pause(),this.buffering.enter(`starvation`);return}this.timeUpdates.followPlayback(e)}isStartedFromOutside(){return this.parts.clock.isRunning&&this.lifecycle.isOneOf(`ready`,`paused`,`ended`)}async followStartFromOutside(){try{await this.play()}catch{}}moveClockTo(e){this.parts.clock.pause(),this.parts.clock.seek(e),this.clockWatch.placedAt(this.parts.clock.currentTime)}followMoveFromOutside(e){let t=this.parts.clock.isRunning;!t&&this.lifecycle.is(`playing`)&&this.pause(),this.seek(e),t&&this.lifecycle.is(`paused`)&&this.followStartFromOutside()}haveTicksStopped(e){return this.clockWatch.wereTicksMissed({now:e,state:this.lifecycle.current})&&!this.parts.clock.hasEnded}restartAt(e){let{clock:t,duration:n}=this.parts;if(e>=n){this.moveClockTo(n),this.end();return}let r=t.isRunning;if(t.pause(),this.startRun(e),r){this.buffering.enter(`priming`);return}this.lifecycle.moveTo(`paused`),this.timeUpdates.announce(e)}isAtTheEnd(){return this.lifecycle.current===`ended`||cd(this.parts.clock,this.parts.duration)}isPrimed(){return this.run?.isPrimedAt(this.parts.clock.currentTime)===!0}resumeIfPrimed(){this.buffering.isOverAt(this.run,this.parts.clock.currentTime)&&this.resume()}async resume(){let e=this.buffering.takeStart();this.enterPlaying();try{await this.startClockOnceHeard(),e?.resolve()}catch(t){e?.reject(t)}}async startClock(){try{await this.parts.clock.start()}catch(e){throw this.lifecycle.is(`playing`)&&this.lifecycle.moveTo(`paused`),e}}isPlayedOut(e){let t=this.run?.isDrained===!0&&e>=this.parts.duration;return this.parts.clock.hasEnded||t}present(e,t){this.presented&&Cu(this.presented.pair),this.presented={pair:e,mediaTime:t},this.draw(this.presented)&&this.lifecycle.announce(`present`,t)}draw(e){try{return this.parts.sink.present(e),!0}catch(e){return this.fail(ne(e,`render-unavailable`,`the picture could not be drawn`)),!1}}startRun(e){this.abortRun(),this.run=gd.start(this.parts,e,{onProgress:()=>{this.resumeIfPrimed()},onFailure:e=>{this.fail(e)}})}abortRun(){this.run?.abort(),this.run=void 0}end(){this.lifecycle.canMoveTo(`ended`)&&(this.parts.clock.pause(),this.lifecycle.moveTo(`ended`),this.timeUpdates.announce(this.parts.clock.currentTime),this.lifecycle.announce(`ended`,void 0))}fail(e){this.lifecycle.canMoveTo(`error`)&&this.lifecycle.change(()=>{this.parts.clock.pause(),this.abortRun(),this.lifecycle.moveTo(`error`),this.buffering.settleStart(),this.lifecycle.announce(`error`,ne(e,`decode`,`playback failed`))})}};function yd(e,t){if(e===null)return;let n=e.trim().toLowerCase();return t.find(e=>e===n)}function bd(e){return yd(e,Xo)}function xd(e){return yd(e,Os)}function Sd(e){return yd(e,ws)}function Cd(e,t){for(let n of t)Object.defineProperty(e,Ad(n),{configurable:!0,enumerable:!0,get(){return this.getAttribute(n)},set(e){Od(this,n,e)}})}function wd(e,t){for(let n of t)Object.defineProperty(e,Ad(n),{configurable:!0,enumerable:!0,get(){return this.hasAttribute(n)},set(e){this.toggleAttribute(n,!!e)}})}function Td(e,t){for(let n of t)Object.defineProperty(e,Ad(n.name),{configurable:!0,enumerable:!0,get(){return Dd(n,this.getAttribute(n.name))},set(e){Od(this,n.name,e)}})}function Ed(e,t){for(let n of t)Object.defineProperty(e,n.property,{configurable:!0,enumerable:!0,get(){let e=this.getAttribute(n.name);return e===null?null:Dd(n,e)},set(e){Od(this,n.name,e)}})}function Dd(e,t){let n=t?.trim().toLowerCase();return e.keywords.find(e=>e===n)??e.fallback}function Od(e,t,n){if(n==null){e.removeAttribute(t);return}e.setAttribute(t,n)}var kd=/-(?<letter>[a-z])/gu;function Ad(e){return e.replaceAll(kd,(e,t)=>t.toUpperCase())}function jd(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new j(`invalid-argument`,`${t} must be a finite number`)}function Md(e){return jd(e.yaw,`yaw`),jd(e.pitch,`pitch`),jd(e.fieldOfView,`fieldOfView`),{yaw:t(e.yaw),pitch:t(e.pitch),fieldOfView:t(e.fieldOfView)}}var Nd=/* @__PURE__ */ new Map([[` `,`toggle-play`],[`k`,`toggle-play`],[`j`,`seek-back`],[`l`,`seek-forward`],[`s`,`stop`],[`m`,`toggle-mute`],[`f`,`toggle-fullscreen`],[`0`,`reset-view`],[`+`,`zoom-in`],[`=`,`zoom-in`],[`-`,`zoom-out`],[`ArrowLeft`,`look-left`],[`ArrowRight`,`look-right`],[`ArrowUp`,`look-up`],[`ArrowDown`,`look-down`]]),Pd=/* @__PURE__ */ new Map([[`ArrowLeft`,`seek-back`],[`ArrowRight`,`seek-forward`]]);function Fd(e){if(!e.hasSystemModifier)return e.key.length===1?Nd.get(e.key.toLowerCase()):e.isShiftPressed?Pd.get(e.key):Nd.get(e.key)}var Id=5;function Ld(e){return({player:t})=>{t.seek(t.currentTime+e)}}function Rd(e,t){return({player:n})=>{n.turn(e,t)}}var zd={"toggle-play":e=>{e.togglePlay()},stop:({player:e})=>{e.stop()},"seek-back":Ld(-5),"seek-forward":Ld(5),"toggle-mute":({player:e})=>{e.setMuted(!e.isMuted)},"toggle-fullscreen":e=>{e.toggleFullscreen()},"reset-view":({player:e})=>{e.resetView()},"zoom-in":({player:e})=>{e.zoom(1)},"zoom-out":({player:e})=>{e.zoom(-1)},"look-left":Rd(-5,0),"look-right":Rd(Id,0),"look-up":Rd(0,Id),"look-down":Rd(0,-5)};function Bd(e,t){let n=new AbortController;return e.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&t.isFullscreen()){t.exitFullscreen();return}let n=Fd({key:e.key,isShiftPressed:e.shiftKey,hasSystemModifier:e.ctrlKey||e.altKey||e.metaKey});n&&!Ud(e)&&(e.preventDefault(),zd[n](t))},{signal:n.signal}),()=>{n.abort()}}var Vd=/* @__PURE__ */ new Set([`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`]),Hd=` `;function Ud(e){let[t]=e.composedPath();return t instanceof HTMLInputElement?Vd.has(e.key):t instanceof HTMLButtonElement&&e.key===Hd}var Wd=100,Gd=`data-draggable`,Kd=0,qd=4,Jd=class{surface;player;onTap;pointers=/* @__PURE__ */ new Map;listening=new AbortController;dragDistance=0;constructor(e,t,n){this.surface=e,this.player=t,this.onTap=n;let{signal:r}=this.listening;e.addEventListener(`pointerenter`,this.reflectDraggable,{signal:r}),e.addEventListener(`pointerdown`,this.onPointerDown,{signal:r}),e.addEventListener(`pointermove`,this.onPointerMove,{signal:r}),e.addEventListener(`pointerup`,this.onPointerUp,{signal:r}),e.addEventListener(`pointercancel`,this.onPointerCancel,{signal:r}),e.addEventListener(`lostpointercapture`,this.onPointerCancel,{signal:r}),e.addEventListener(`wheel`,this.onWheel,{passive:!1,signal:r})}detach(){this.listening.abort(),this.pointers.clear(),this.surface.removeAttribute(Gd)}onPointerDown=e=>{(e.pointerType!==`mouse`||e.button===Kd)&&(this.pointers.size===0&&(this.dragDistance=0),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.surface.setPointerCapture(e.pointerId))};onPointerMove=e=>{this.reflectDraggable();let t=this.pointers.get(e.pointerId);if(!t)return;let n={x:e.clientX,y:e.clientY};this.pointers.size===1?this.pan(t,n):this.pinch(e.pointerId,n),this.pointers.set(e.pointerId,n)};onPointerUp=e=>{!this.pointers.delete(e.pointerId)||this.pointers.size>0||this.dragDistance<qd&&this.onTap(e.pointerType)};onPointerCancel=e=>{this.pointers.delete(e.pointerId),this.dragDistance=1/0};onWheel=e=>{e.preventDefault();let t={x:e.clientX,y:e.clientY};this.player.zoom(-e.deltaY/Wd,this.focusAt(t)),this.reflectDraggable()};reflectDraggable=()=>{this.surface.toggleAttribute(Gd,this.player.canPan)};pan(e,t){let n={x:t.x-e.x,y:t.y-e.y};this.dragDistance+=Math.hypot(n.x,n.y),this.player.pan(n)}pinch(e,t){let n=[...this.pointers].find(([t])=>t!==e)?.[1],r=this.pointers.get(e);if(!n||!r)return;this.dragDistance=1/0;let i=$s(Yd(r,n),Yd(t,n)),a={x:(t.x+n.x)/2,y:(t.y+n.y)/2};this.player.zoom(i,this.focusAt(a))}focusAt(e){let t=this.surface.getBoundingClientRect();return{x:(e.x-t.left)/Math.max(t.width,1),y:(e.y-t.top)/Math.max(t.height,1)}}};function Yd(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Xd(e,t,n={}){let r=new Jd(e,t,n.onTap??(()=>{Qd(t)}));return()=>{r.detach()}}function Zd(e,t,n={}){let r=()=>e.matches(`:fullscreen`);return Bd(e,{player:t,togglePlay:()=>{Qd(t)},toggleFullscreen:n.toggleFullscreen??(()=>{r()?document.exitFullscreen():e.requestFullscreen()}),isFullscreen:r,exitFullscreen:()=>{document.exitFullscreen()}})}function Qd(e){if(!e.isPaused){e.pause();return}e.play().catch(t=>{e.events.emit(`warning`,{code:`playback-failed`,message:`playback could not start: ${ie(t)}`})})}var $d=class{blob;constructor(e){this.blob=e}size(){return Promise.resolve(this.blob.size)}async read(e){if(e.ensureWithin(this.blob.size,`blob`),e.length===0)return/* @__PURE__ */ new Uint8Array;let t=await this.bytesOf(this.blob.slice(e.offset,e.end));if(t.byteLength!==e.length)throw new j(`source-truncated`,`the blob yielded ${t.byteLength} bytes for a ${e.length}-byte range at ${e.offset}; the file may have changed on disk`);return t}async bytesOf(e){try{return new Uint8Array(await e.arrayBuffer())}catch(e){throw new j(`source-unreadable`,`the blob could not be read`,{cause:e})}}},ef=/^bytes (\d+)-(\d+)\/(\d+|\*)$/u,tf=`*`;function nf(e){let t=ef.exec(e.headers.get(`content-range`)??``);if(!t)return;let[,n,r,i]=t;return{first:Number(n),last:Number(r),total:i===tf?void 0:Number(i)}}var rf=/* @__PURE__ */ new WeakSet;function af(e){return rf.add(e),e}function of(e){return e instanceof j&&rf.has(e)}function sf(e){return M(e,`source-unreadable`)&&e instanceof Error?af(new j(`source-unreadable`,e.message,{cause:e.cause})):e}function cf(e,t,n){return af(new j(`source-unreadable`,`${e} broke off the ${t.length}-byte range at ${t.offset}`,{cause:n}))}function lf(e,t,n){return new j(`source-truncated`,`${e} returned ${t} bytes for a ${n.length}-byte range at ${n.offset}`)}var uf=1e4,df=class{resource;stallTimeoutMs;constructor(e,t={}){this.resource=e,this.stallTimeoutMs=t.stallTimeoutMs??uf}stream(e){return{[Symbol.asyncIterator]:()=>new ff({resource:this.resource,range:e,stallTimeoutMs:this.stallTimeoutMs})}}},ff=class{parts;attempt;received=0;ending=new bl;constructor(e){this.parts=e}async next(){try{let e=await this.parts.resource.askingAgain(()=>this.readChunk());if(e)return{done:!1,value:e}}catch(e){if(!this.ending.hasEnded())throw this.end(),e}return this.end(),yl}return(){return this.end(),Promise.resolve(yl)}async readChunk(){let{resource:e,range:t}=this.parts;if(await e.ensureFits(t),this.ending.hasEnded()||t.length===0)return;this.attempt??=this.attemptAtTheRest();let{attempt:n}=this;try{let e=await this.withinStallTimeout(this.readFrom(n));return this.taken(e)}catch(e){throw this.drop(n),e}}attemptAtTheRest(){let{range:e}=this.parts,t=Fn.of(e.offset+this.received,e.length-this.received),n=new AbortController;return{request:n,body:this.bodyOf(t,n.signal)}}async bodyOf(e,t){let n=await this.parts.resource.rangeAnswer(e,t);return this.ensureAnswers(n,e),n.body?.getReader()??new ReadableStream().getReader()}ensureAnswers(e,t){let n=nf(e);if(!n)return;let r=`${t.offset}-${t.end-1}`,i=`${n.first}-${n.last}`;if(i!==r)throw new j(`source-unreadable`,`${this.parts.resource.url} answered bytes ${i} to a request for bytes ${r}`)}async readFrom(e){let t=await e.body;try{return await t.read()}catch(e){throw re(e)?e:cf(this.parts.resource.url,this.parts.range,e)}}async withinStallTimeout(e){let t,n=new Promise((e,n)=>{t=setTimeout(()=>{n(this.stalled())},this.parts.stallTimeoutMs)});try{return await Promise.race([e,n])}finally{clearTimeout(t)}}stalled(){let{resource:e,range:t,stallTimeoutMs:n}=this.parts;return af(new j(`source-unreadable`,`${e.url} sent nothing of the ${t.length}-byte range at ${t.offset} for ${n} ms`))}taken(e){if(e.done){this.ensureWhole();return}return this.count(e.value),e.value}count(e){let{resource:t,range:n}=this.parts;if(this.received+=e.byteLength,!(this.received<=n.length))throw new j(`source-unreadable`,`${t.url} sent more than the ${n.length}-byte range at ${n.offset}`)}ensureWhole(){let{resource:e,range:t}=this.parts;if(this.received!==t.length)throw lf(e.url,this.received,t)}drop(e){e.request.abort(),this.attempt===e&&(this.attempt=void 0)}end(){this.ending.end(),this.attempt&&this.drop(this.attempt)}},pf=class{resource;constructor(e){this.resource=e}size(){return this.resource.size()}async read(e){return await this.resource.ensureFits(e),e.length===0?/* @__PURE__ */ new Uint8Array:this.resource.askingAgain(()=>this.readOnce(e))}async readOnce(e){let t=await this.resource.rangeAnswer(e),n=await this.bodyOf(t,e);if(n.byteLength!==e.length)throw lf(this.resource.url,n.byteLength,e);return n}async bodyOf(e,t){try{return new Uint8Array(await e.arrayBuffer())}catch(e){throw re(e)?e:cf(this.resource.url,t,e)}}},mf=`bytes=0-0`,hf=`Access-Control-Expose-Headers: Content-Range, Content-Length, Accept-Ranges, ETag`,gf=`Access-Control-Allow-Origin, ${hf}`,_f=`Access-Control-Allow-Origin naming this page's origin, not *; Access-Control-Allow-Credentials: true; ${hf}`,vf=`no-store`;async function yf(e,t,n){try{return await bf(e,t,n)}catch(t){throw re(t)?t:await Cf(e,n,t)}}function bf(e,t,n){return(n.fetch??fetch)(e,{cache:vf,...n.requestInit,method:t.method,headers:{...Of(n.requestInit),...t.headers}})}function xf(e,t){let n=e.requestInit?.signal??void 0,r=n?Sf(n,t):t;return{...e,requestInit:{...e.requestInit,signal:r}}}function Sf(e,t){let n=new AbortController;for(let r of[e,t])r.aborted&&n.abort(r.reason),r.addEventListener(`abort`,()=>{n.abort(r.reason)},{once:!0,signal:n.signal});return n.signal}async function Cf(e,t,n){return await Tf(e,t)?new j(`cors`,`${e} answered, but its server does not allow this page's origin to read it; add CORS headers (${wf(t)})`,{cause:n}):new j(`source-unreadable`,`${e} could not be fetched; check the URL and the network`,{cause:n})}function wf(e){return e.requestInit?.credentials===`include`?_f:gf}async function Tf(e,t){let n=t.fetch??fetch,r=t.requestInit?.signal??null;try{return Ef(await n(e,{method:`HEAD`,mode:`no-cors`,signal:r})),!0}catch(e){if(re(e))throw e;return!1}}function Ef(e){Df(e)}async function Df(e){try{await e.body?.cancel()}catch{}}function Of(e){return Object.fromEntries(new Headers(e?.headers).entries())}var kf=200,Af=/^W\//u;function jf(e){let t=e.headers.get(`etag`),n=e.headers.get(`last-modified`),r=Ff(e);return{...t!==null&&{etag:t},...n!==null&&{lastModified:n},...r!==void 0&&{size:r}}}function Mf(e,t){return e.etag!==void 0&&t.etag!==void 0?Nf(e.etag)===Nf(t.etag):Pf(e.lastModified,t.lastModified)&&Pf(e.size,t.size)}function Nf(e){return e.replace(Af,``)}function Pf(e,t){return e===void 0||t===void 0||e===t}function Ff(e){let t=e.status===kf?Number(e.headers.get(`content-length`)??NaN):nf(e)?.total;return t!==void 0&&Number.isSafeInteger(t)&&t>0?t:void 0}var If=200,Lf=206,Rf=500,zf=[250,1e3],Bf=class{url;options;retryDelaysMs;sizePromise;hasReadRange=!1;version;constructor(e,t={},n){this.url=e,this.options=n?xf(t,n):t,this.retryDelaysMs=t.retryDelaysMs??zf}size(){return this.sizePromise??=this.rememberSize(),this.sizePromise}async ensureFits(e){e.ensureWithin(await this.size(),`resource ${this.url}`)}async askingAgain(e){for(let t of this.retryDelaysMs){try{return await e()}catch(e){if(!of(e))throw e}await Vf(t,this.options.requestInit?.signal)}return e()}async rangeAnswer(e,t){let n=t?xf(this.options,t):this.options,r=await this.requestRange(e,n);if(r.status!==Lf)throw Ef(r),this.refusalOf(r.status);return this.hasReadRange=!0,this.ensureUnchanged(r),r}ensureUnchanged(e){let t=jf(e);if(this.version??=t,!Mf(this.version,t))throw Ef(e),new j(`source-changed`,`${this.url} was replaced while it played; load it again`)}async requestRange(e,t){let n={Range:`bytes=${e.offset}-${e.end-1}`};try{return this.hasReadRange?await bf(this.url,{method:`GET`,headers:n},t):await yf(this.url,{method:`GET`,headers:n},t)}catch(e){throw this.hasReadRange?this.passingOnceAnswered(e):sf(e)}}passingOnceAnswered(e){let t=`${this.url} could not be reached for a byte range`;return re(e)?e:af(new j(`source-unreadable`,t,{cause:e}))}refusalOf(e){if(e===If)return new j(`range-unsupported`,`${this.url} ignores Range requests (answered 200 to a byte range)`);let t=`${this.url} answered ${e} to a byte range`;return e>=Rf?af(new j(`source-unreadable`,t)):new j(`source-unreadable`,t)}async rememberSize(){try{return await this.fetchSize()}catch(e){throw this.sizePromise=void 0,e}}async fetchSize(){let e=await this.request(`HEAD`);if(Ef(e),!e.ok)return this.sizeFromContentRange();this.ensureUnchanged(e);let t=Number(e.headers.get(`content-length`));return Number.isSafeInteger(t)&&t>0?t:this.sizeFromContentRange()}async sizeFromContentRange(){let e=await this.request(`GET`,{Range:mf});if(Ef(e),e.status!==Lf)throw new j(`source-unreadable`,`${this.url} answered ${e.status} to a byte range; cannot determine the file size`);return this.hasReadRange=!0,this.ensureUnchanged(e),this.totalOf(e)}totalOf(e){if(!e.headers.has(`content-range`)&&e.type===`cors`)throw this.hiddenContentRange();let t=nf(e)?.total;if(t===void 0)throw new j(`source-unreadable`,`${this.url} reports neither Content-Length nor Content-Range; cannot determine the file size`);return t}hiddenContentRange(){return new j(`cors`,`${this.url} answered a byte range but hides its Content-Range from this origin; add ${hf}`)}request(e,t){return yf(this.url,{method:e,...t&&{headers:t}},this.options)}};function Vf(e,t){return new Promise((n,r)=>{t?.throwIfAborted();let i=new AbortController,a=setTimeout(()=>{i.abort(),n()},e);t?.addEventListener(`abort`,()=>{clearTimeout(a),r(Hf(t))},{once:!0,signal:i.signal})})}function Hf(e){let t=e?.reason;return t instanceof Error?t:new DOMException(`the read was aborted`,`AbortError`)}var Uf=/* @__PURE__ */ new Set([405,403]),Wf=class{options;constructor(e={}){this.options=e}async exists(e){try{let t=await bf(e,{method:`HEAD`},this.options);if(Ef(t),!Uf.has(t.status))return t.ok;let n=await bf(e,{method:`GET`,headers:{Range:mf}},this.options);return Ef(n),n.ok}catch{return!1}}};function z(e){if(!e)throw Error(`Assertion failed.`)}var Gf=Math.PI/180,Kf=180/Math.PI,qf=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},Jf=[1,0,0,0,1,0,0,0,1],Yf=(e,t,n)=>{let[r,i,,a,o]=e,s=Math.abs(r)*t+Math.abs(a)*n,c=Math.abs(i)*t+Math.abs(o)*n;return tp(tp($f(-t/2,-n/2),e),$f(s/2,c/2))},Xf=e=>{let[t,n]=e;return qf(Rp(Math.atan2(n,Zf(e)?-t:t)*Kf,90))},Zf=e=>{let[t,n,,r,i]=e;return t*i-n*r<0},Qf=e=>{let t=e*Gf,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},$f=(e,t)=>[1,0,0,0,1,0,e,t,1],ep=(e,t)=>[e,0,0,0,t,0,0,0,1],tp=(e,t)=>{let n=Array(9);for(let r=0;r<3;r++)for(let i=0;i<3;i++)n[3*r+i]=e[3*r]*t[i]+e[3*r+1]*t[3+i]+e[3*r+2]*t[6+i];return n},np=e=>e&&e[e.length-1],rp=e=>e>=0&&e<2**32,ip=e=>e>=-(2**31)&&e<2**31,B=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},ap=e=>{let t=B(e);return t&1?t+1>>1:-(t>>1)},op=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),sp=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),cp=globalThis.TextEncoder===void 0?class{constructor(){this.encoding=`utf-8`}encode(e=``){let t=new Uint8Array(3*e.length),n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i<128)t[n++]=i;else if(i<2048)t[n++]=192|i>>6,t[n++]=128|i&63;else if(i<55296||i>57343)t[n++]=224|i>>12,t[n++]=128|i>>6&63,t[n++]=128|i&63;else{let a=r+1<e.length?e.charCodeAt(r+1):0;i<56320&&a>=56320&&a<=57343?(i=65536+(i-55296<<10)+(a-56320),r++,t[n++]=240|i>>18,t[n++]=128|i>>12&63,t[n++]=128|i>>6&63,t[n++]=128|i&63):(t[n++]=239,t[n++]=191,t[n++]=189)}}return t.slice(0,n)}}:globalThis.TextEncoder,lp=globalThis.TextDecoder===void 0?class{constructor(e=`utf-8`){let t=e.trim().toLowerCase();if(t===`utf-8`||t===`utf8`||t===`unicode-1-1-utf-8`)this.encoding=`utf-8`;else if(t===`utf-16le`||t===`utf-16`)this.encoding=`utf-16le`;else if(t===`utf-16be`)this.encoding=`utf-16be`;else throw RangeError(`The encoding label provided ('${e}') is invalid.`)}decode(e){let t=e?op(e):/* @__PURE__ */ new Uint8Array,n=[];if(this.encoding===`utf-8`){let e=t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?3:0;for(;e<t.length;){let r=t[e];if(r<128){n.push(r),e++;continue}let i,a;if(r>=194&&r<224)i=1,a=r&31;else if(r>=224&&r<240)i=2,a=r&15;else if(r>=240&&r<245)i=3,a=r&7;else{n.push(65533),e++;continue}let o=r===224?160:r===240?144:128,s=r===237?159:r===244?143:191,c=1;for(;c<=i;c++){let n=e+c<t.length?t[e+c]:0;if(n<o||n>s)break;a=a<<6|n&63,o=128,s=191}e+=c,c<=i?n.push(65533):a>=65536?(a-=65536,n.push(55296|a>>10,56320|a&1023)):n.push(a)}}else{let e=this.encoding===`utf-16le`,r=e?255:254,i=e?254:255,a=t.length>=2&&t[0]===r&&t[1]===i?2:0;for(;a+1<t.length;){let r=e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1];if(a+=2,r>=55296&&r<=56319){let i=a+1<t.length?e?t[a]|t[a+1]<<8:t[a]<<8|t[a+1]:-1;i>=56320&&i<=57343?(n.push(r,i),a+=2):n.push(65533)}else r>=56320&&r<=57343?n.push(65533):n.push(r)}a<t.length&&n.push(65533)}let r=``;for(let e=0;e<n.length;e+=8192)r+=String.fromCharCode(...n.slice(e,e+8192));return r}}:globalThis.TextDecoder,up=/* #__PURE__ */ new lp,dp=/* #__PURE__ */ new cp,fp=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),pp={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},mp=/* #__PURE__ */ fp(pp),hp={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},gp=/* #__PURE__ */ fp(hp),_p={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},vp=/* #__PURE__ */ fp(_p),yp=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,bp=e=>!e||e.primaries==null&&e.transfer==null&&e.matrix==null&&e.fullRange==null,xp={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Sp=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),Cp=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},wp=/^[0-9a-fA-F]+$/,Tp=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),Ep=e=>{z(e.length%2==0);let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.slice(n,n+2),16);return t},Dp=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),Op=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},kp=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},Ap=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},jp=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},Mp=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},Np=e=>{throw Error(`Unexpected value: ${e}`)},Pp=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},Fp=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},Ip=(e,t,n)=>Math.max(t,Math.min(n,e)),Lp=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},Rp=(e,t)=>Math.round(e/t)*t,zp=(e,t)=>Math.round(e*t)/t,Bp=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Vp=/^[a-z]{3}$/,Hp=e=>Vp.test(e),Up=1e6*(1+2**-52),Wp=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{num:n*a,den:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{num:n*a,den:o}},Gp=null,Kp=()=>Gp===null?Gp=!(typeof navigator>`u`||!navigator.vendor?.includes(`Google Inc`)&&!/Chrome/.test(navigator.userAgent)):Gp,qp=(/* #__PURE__ */ (async()=>{})()).constructor,Jp=e=>e instanceof qp||e instanceof Promise||typeof e?.then==`function`,Yp=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},Xp=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Zp=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},Qp=e=>typeof e==`number`&&!Number.isNaN(e),$p=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},em=(e,t)=>{let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);a<r&&(r=a,n=i)}return n},tm=e=>{z(Number.isInteger(e.num)),z(Number.isInteger(e.den)),z(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},nm=e=>Array.isArray(e)?e:[e],rm=class{constructor(){this._listeners=/* @__PURE__ */ new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,/* @__PURE__ */ new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},im=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),am;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(am||={});var om=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==am.Silent&&t!==am.Errors&&t!==am.Warnings&&t!==am.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new rm}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=am.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=am.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=am.Info&&console.info(...t)}};om._level=am.Info,om._emitterInstance=null;var sm=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},cm=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},lm=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(Array.isArray(t)&&t.every(e=>typeof e==`string`))&&!(t instanceof Uint8Array)&&!(t instanceof sm)&&!(t instanceof cm)&&!im(t))throw TypeError(`Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},um={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},dm=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.primary!==void 0&&typeof e.primary!=`boolean`)throw TypeError(`disposition.primary must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},fm=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}copyBits(e,t){let n=0;for(;n<e-7;n+=8)this.writeBits(8,t.readBits(8));let r=e-n;r>0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},pm=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],mm=[-1,1,2,3,4,5,6,8],hm=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new fm(e),n=gm(t),{frequencyIndex:r,sampleRate:i}=_m(t),a=t.readBits(4),o=null;a>=1&&a<=7&&(o=mm[a]);let s=n,c=!1,l=i;if(n===5||n===29)c=n===29,l=_m(t).sampleRate,s=gm(t),s===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let e=t.pos;if(t.readBits(11)!==695){t.pos=e+1;continue}gm(t)===5&&t.readBits(1)&&(l=_m(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return o!==null&&o>1&&(c=!1),{objectType:n,coreObjectType:s,frequencyIndex:r,channelConfiguration:a,outputSampleRate:l,outputNumberOfChannels:c&&o===1?2:o}},gm=e=>{let t=e.readBits(5);return t===31?32+e.readBits(6):t},_m=e=>{let t=e.readBits(4);return t===15?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<pm.length?pm[t]:null}},vm=e=>{let t=e.objectType===5||e.objectType===29,n=e.objectType===29,r=t?e.outputSampleRate/2:e.outputSampleRate,i=n?1:e.outputNumberOfChannels,a=mm.indexOf(i);if(a===-1)throw TypeError(`Unsupported number of channels: ${e.outputNumberOfChannels}`);let o=16;e.objectType>=32&&(o+=6),xm(r)===15&&(o+=24),t&&(o+=9,xm(e.outputSampleRate)===15&&(o+=24));let s=Math.ceil(o/8),c=new Uint8Array(s),l=new fm(c);return ym(l,e.objectType),bm(l,r),l.writeBits(4,a),t&&(bm(l,e.outputSampleRate),ym(l,2)),l.writeBits(3,0),c},ym=(e,t)=>{t<32?e.writeBits(5,t):(e.writeBits(5,31),e.writeBits(6,t-32))},bm=(e,t)=>{let n=xm(t);e.writeBits(4,n),n===15&&e.writeBits(24,t)},xm=e=>{let t=pm.indexOf(e);return t===-1?15:t},Sm=[48e3,44100,32e3],Cm=[24e3,22050,16e3],wm;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(wm||={});var Tm;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(Tm||={});var Em=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},Dm=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;t===1?e=r.getUint8(n):t===2?e=r.getUint16(n,!1):t===3?e=Pp(r,n,!1):(z(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},Om=(e,t)=>t.description?Dm(e,(op(t.description)[4]&3)+1):Em(e),km=e=>e&31,Am=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)};new Uint8Array([0,0,0,1]);var jm=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:Fp(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},Mm=e=>{try{let t=[],n=[],r=[];for(let i of Em(e)){let a=e.subarray(i.offset,i.offset+i.length),o=km(a[0]);o===wm.SPS?t.push(a):o===wm.PPS?n.push(a):o===wm.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=Im(i);z(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return om._error(`Error building AVC Decoder Configuration Record:`,e),null}},Nm=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if((e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144)&&e.chromaFormat!==null){z(e.bitDepthLumaMinus8!==null),z(e.bitDepthChromaMinus8!==null),z(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},Pm=e=>{try{let t=sp(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return om._error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},Fm={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Im=e=>{try{let t=Am(e),n=new fm(t);if(n.skipBits(1),n.skipBits(2),n.readBits(5)!==7)return null;let r=n.readAlignedByte(),i=n.readAlignedByte(),a=n.readAlignedByte();B(n);let o=1,s=0,c=0,l=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(o=B(n),o===3&&(l=n.readBits(1)),s=B(n),c=B(n),n.skipBits(1),n.readBits(1))){for(let e=0;e<(o===3?12:8);e++)if(n.readBits(1)){let t=e<6?16:64,r=8,i=8;for(let e=0;e<t;e++){if(i!==0){let e=ap(n);i=(r+e+256)%256}r=i===0?r:i}}}B(n);let u=B(n);if(u===0)B(n);else if(u===1){n.skipBits(1),ap(n),ap(n);let e=B(n);for(let t=0;t<e;t++)ap(n)}B(n),n.skipBits(1);let d=B(n),f=B(n),p=16*(d+1),m=16*(f+1),h=p,g=m,_=n.readBits(1);if(_||n.skipBits(1),n.skipBits(1),n.readBits(1)){let e=B(n),t=B(n),r=B(n),i=B(n),a,s;if((l===0?o:0)===0)a=1,s=2-_;else{let e=o===3?1:2,t=o===1?2:1;a=e,s=t*(2-_)}h-=a*(e+t),g-=s*(r+i)}let v=2,y=2,b=2,x=0,S={num:1,den:1},C=null,w=null,T=null,E=null,D=n.pos;if(n.readBits(1)){if(n.readBits(1)){let e=n.readBits(8);if(e===255)S={num:n.readBits(16),den:n.readBits(16)};else{let t=Fm[e];t&&(S=t)}}n.readBits(1)&&n.skipBits(1),n.readBits(1)&&(n.skipBits(3),x=n.readBits(1),n.readBits(1)&&(v=n.readBits(8),y=n.readBits(8),b=n.readBits(8))),n.readBits(1)&&(B(n),B(n)),n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.skipBits(1));let e=n.readBits(1);e&&Lm(n);let t=n.readBits(1);t&&Lm(n),(e||t)&&n.skipBits(1),n.skipBits(1),T=n.pos,E=n.readBits(1),E&&(n.skipBits(1),B(n),B(n),B(n),B(n),C=B(n),w=B(n))}if(C===null){z(w===null);let e=i&16;if((r===44||r===86||r===100||r===110||r===122||r===244)&&e)C=0,w=0;else{let e=d+1,t=f+1,n=(2-_)*t,r=Rh.find(e=>e.level>=a)??np(Rh),i=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);C=i,w=i}}return z(w!==null),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:_,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:c,codedWidth:p,codedHeight:m,displayWidth:h,displayHeight:g,pixelAspectRatio:S,colourPrimaries:v,matrixCoefficients:b,transferCharacteristics:y,fullRangeFlag:x,numReorderFrames:C,maxDecFrameBuffering:w,vuiParametersFlagBitOffset:D,bitstreamRestrictionFlagBitOffset:T,bitstreamRestrictionFlag:E}}catch(e){return om._error(`Error parsing AVC SPS:`,e),null}},Lm=e=>{let t=B(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)B(e),B(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Rm=(e,t)=>t.description?Dm(e,(op(t.description)[21]&3)+1):Em(e),zm=e=>e>>1&63,Bm=e=>{try{let t=new fm(Am(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=Hm(t,n);B(t);let u=B(t),d=0;u===3&&(d=t.readBits(1));let f=B(t),p=B(t),m=f,h=p;if(t.readBits(1)){let e=B(t),n=B(t),r=B(t),i=B(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=B(t),_=B(t);B(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)B(t),y=B(t),B(t);if(B(t),B(t),B(t),B(t),B(t),B(t),t.readBits(1)&&t.readBits(1)&&Um(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),B(t),B(t),t.skipBits(1)),Wm(t,B(t)),t.readBits(1)){let e=B(t);for(let n=0;n<e;n++)B(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,w=0,T={num:1,den:1};if(t.readBits(1)){let e=Km(t,n);T=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,w=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:T,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:w}}catch(e){return om._error(`Error parsing HEVC SPS:`,e),null}},Vm=e=>{try{let t=[],n=[],r=[],i=[];for(let a of Em(e)){let o=e.subarray(a.offset,a.offset+a.length),s=zm(o[0]);s===Tm.VPS_NUT?t.push(o):s===Tm.SPS_NUT?n.push(o):s===Tm.PPS_NUT?r.push(o):(s===Tm.PREFIX_SEI_NUT||s===Tm.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Bm(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new fm(Am(e));t.skipBits(16),B(t),B(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),B(t),B(t),ap(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&B(t),ap(t),ap(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:Tm.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Tm.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Tm.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:zm(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return om._error(`Error building HEVC Decoder Configuration Record:`,e),null}},Hm=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=/* @__PURE__ */ new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},Um=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))B(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&ap(e);for(let t=0;t<n;t++)ap(e)}},Wm=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Gm(e,r,t,n)},Gm=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(B(e)+1):t-1,e.readBits(1),B(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=B(e),n=B(e);for(let n=0;n<t;n++)B(e),e.readBits(1);for(let t=0;t<n;t++)B(e),e.readBits(1);i=t+n}return i},Km=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=Fm[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(B(e),B(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(B(e),B(e),B(e),B(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&B(e),e.readBits(1)&&qm(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=B(e),B(e),B(e),B(e),B(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},qm=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?B(e):o=e.readBits(1)===1;let s=1;o||(s=B(e)+1),r&&Jm(e,s,a),i&&Jm(e,s,a)}},Jm=(e,t,n)=>{for(let r=0;r<t;r++)B(e),B(e),n&&(B(e),B(e)),e.readBits(1)},Ym=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},Xm=e=>{try{let t=sp(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=i>>6&3,o=i>>5&1,s=i&31,c=t.getUint32(n,!1);n+=4;let l=e.subarray(n,n+6);n+=6;let u=t.getUint8(n++),d=(t.getUint8(n++)&15)<<8|t.getUint8(n++),f=t.getUint8(n++)&3,p=t.getUint8(n++)&3,m=t.getUint8(n++)&7,h=t.getUint8(n++)&7,g=t.getUint16(n,!1);n+=2;let _=t.getUint8(n++),v=_>>6&3,y=_>>3&7,b=_>>2&1,x=_&3,S=t.getUint8(n++),C=[];for(let r=0;r<S;r++){let r=t.getUint8(n++),i=r>>7&1,a=r&63,o=t.getUint16(n,!1);n+=2;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}C.push({arrayCompleteness:i,nalUnitType:a,nalUnits:s})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:p,bitDepthLumaMinus8:m,bitDepthChromaMinus8:h,avgFrameRate:g,constantFrameRate:v,numTemporalLayers:y,temporalIdNested:b,lengthSizeMinusOne:x,arrays:C}}catch(e){return om._error(`Error deserializing HEVC Decoder Configuration Record:`,e),null}},Zm;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(Zm||={});var Qm={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},$m=e=>{let t=new fm(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7){if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1}else o=3,s=1;let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=np(zh).level;for(let e of zh)if(u<=e.maxPictureSize){d=e.level;break}let f=Qm[a],p=f?.colourPrimaries??2,m=f?.transferCharacteristics??2,h=f?.matrixCoefficients??2;return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:p,transferCharacteristics:m,matrixCoefficients:h}},eh=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,th=function*(e){let t=new fm(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e+=(r&127)*2**(n*7),!(r&128))break;if(n===7&&r&128)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),i=t.readBits(1),a=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let o;if(a){let e=n();if(e===null)return;o=e}else o=Math.floor(t.getBitsLeft()/8);z(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(o*8)}},nh=e=>{for(let{type:t,data:n}of th(e)){if(t!==1)continue;let e=new fm(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{let t=e.readBits(1),n=0;if(t){if(e.skipBits(32),e.skipBits(32),e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}n=e.readBits(1),n&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}let r=e.readBits(1),i=e.readBits(5);for(let t=0;t<=i;t++){e.skipBits(12);let i=e.readBits(5);if(t===0&&(a=i),i>7){let n=e.readBits(1);t===0&&(o=n)}if(n&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}r&&e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=2,_=2,v=2;e.readBits(1)&&(g=e.readBits(8),_=e.readBits(8),v=e.readBits(8));let y=0,b=1,x=1,S=0;return h?y=e.readBits(1):g===1&&_===13&&v===0?(y=1,b=0,x=0):(y=e.readBits(1),r===0?(b=1,x=1):r===1?(b=0,x=0):m===12?(b=e.readBits(1),x=b?e.readBits(1):0):(b=1,x=0),b&&x&&(S=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:b,chromaSubsamplingY:x,chromaSamplePosition:S,videoFullRangeFlag:y,colourPrimaries:g,transferCharacteristics:_,matrixCoefficients:v}}return null},rh=e=>e.colourPrimaries!==2||e.transferCharacteristics!==2||e.matrixCoefficients!==2,ih=e=>{if(e.length<36)return null;let t=sp(e);return t.getUint32(4)!==1768124518||t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},ah=e=>{let t=sp(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},oh=(e,t,n)=>{switch(e){case`avc`:for(let e of Om(n,t)){let t=n[e.offset],r=km(t);if(r>=wm.NON_IDR_SLICE&&r<=wm.SLICE_DPC)return`delta`;if(r===wm.IDR)return`key`;if(r===wm.SEI&&!Kp()){let t=Am(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(n===void 0||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(e===void 0||(n+=e,e<255))break}if(e===6){let e=new fm(t);e.pos=8*r;let n=B(e),i=e.readBits(1);if(n===0&&i===1)return`key`}r+=n}while(r<t.length-1)}}return`delta`;case`hevc`:for(let e of Rm(n,t)){let t=zm(n[e.offset]);if(t<Tm.BLA_W_LP)return`delta`;if(t<=Tm.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new fm(n);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:r}of th(n))if(t===1){let t=new fm(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new fm(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}case`prores`:return`key`;default:Np(e),z(!1)}},sh;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(sh||={});var ch=[2,1,2,3,3,4,4,5],lh=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new fm(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}};new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var uh=[1,2,3,6],dh=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new fm(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=uh[o],d;return d=i<3?Sm[i]/1e3:Cm[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},fh=e=>{if(e.length<2)return null;let t=new fm(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},ph=e=>{let t=e.substreams[0];return z(t),t.fscod<3?Sm[t.fscod]:t.fscod2!==null&&t.fscod2<3?Cm[t.fscod2]:null},mh=e=>{let t=e.substreams[0];z(t);let n=ch[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n},hh=8,gh=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],_h=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],vh=[16,16,20,20,0,24,24,0],yh=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],bh=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],xh=8,Sh=44646,Ch=[32e3,44100,48e3,0],wh=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Th=[512,1024,2048,4096],Eh=e=>{let t=Oh(e),n=sp(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=kh(e.subarray(r));if(!t)break;i??=t,r+=t.frameSize}if(t)return{frameSize:i?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:i!==null};if(!i?.asset)return null;let{asset:a}=i;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Dh=e=>{let t=Eh(e);return t?.core?t.hasExtensions?`dtsh`:`dtsc`:null},Oh=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new fm(e);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==31)return null;let n=t.readBits(1),r=t.readBits(7)+1;if(r%hh!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=yh.length)return null;let o=gh[t.readBits(4)];if(o===0)return null;let s=_h[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),n&&t.skipBits(16),t.skipBits(7);let l=vh[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:yh[a]+ +!!u,sampleCount:r*32,channelLayout:bh[a]|(u?xh:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},kh=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new fm(e);t.skipBits(32),t.skipBits(8);let n=t.readBits(2),r=t.readBits(1),i=8+4*r,a=16+4*r;t.skipBits(i);let o=t.readBits(a)+1,s={frameSize:o,asset:null};if(!t.readBits(1))return s;let c=Ch[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,f=[];for(let e=0;e<u;e++)f.push(t.readBits(n+1));for(let e of f)t.skipBits(8*Bp(e));if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,n=t.readBits(2)+1;t.skipBits(n*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let p=t.readBits(5)+1,m=wh[t.readBits(4)],h=t.readBits(8)+1,g=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;g=t.readBits(e)}return c===0||t.getBitsLeft()<0?s:{frameSize:o,asset:{sampleRate:m,numberOfChannels:h,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:p}}},Ah=e=>{if(e.length<20)return null;let t=sp(e),n=t.getUint32(0);if(n===0)return null;let r=new fm(e);r.seekToByte(13);let i=r.readBits(2);r.skipBits(5);let a=r.readBits(1),o=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);let s=r.readBits(16),c=null;return s===0?o<yh.length&&(c=yh[o]+a):c=Mh(s),{sampleRate:n,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:Th[i],channelLayout:s,numberOfChannels:c}},jh=e=>{let t=/* @__PURE__ */ new Uint8Array(20),n=sp(t);n.setUint32(0,e.sampleRate),n.setUint32(4,e.bitRate),n.setUint32(8,e.bitRate),t[12]=e.pcmResolution;let r=e.core&&!e.hasExtensions?1:0,i=new fm(t);return i.seekToByte(13),i.writeBits(2,Math.max(Th.indexOf(e.sampleCount),0)),i.writeBits(5,r),i.writeBits(1,+!!e.core?.lfePresent),i.writeBits(6,e.core?.amode??0),i.writeBits(14,e.core?e.core.frameSize-1:0),i.writeBits(1,0),i.writeBits(3,0),i.writeBits(16,e.channelLayout),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(5,0),t},Mh=e=>Bp(e)+Bp(e&Sh),Nh=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Ph=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],Fh=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`],Ih=[...Fh,...Ph],Lh=[`webvtt`],Rh=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],zh=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Bh=`.01.01.01.01.00`,Vh=`.0.110.01.01.01.0`,Hh=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],Uh=[`dtsc`,`dtsh`,`dtsl`,`dtse`],Wh=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=+(r.slice(-1)===`H`),s=Number(t[3]),c=s===8?0:1,l=+(s===12),u=t[4]?Number(t[4]):0,d=t[5]?Number(t[5][0]):1,f=t[5]?Number(t[5][1]):1,p=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(c<<6)+(l<<5)+(u<<4)+(d<<3)+(f<<2)+p,0]},Gh=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s,proresFormat:c}=e;if(t===`avc`){if(z(e.avcType!==null),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${Tp(t)}`}if(!n||n.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${Tp(n.subarray(1,4))}`}if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=Dp(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let a=sp(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=Dp(a.getUint32(2)),i=c>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=r.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=o;s.length>0&&s[s.length-1]===0;)s.pop();return s.length>0&&(c+=`.`,c+=s.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}if(t===`vp8`)return`vp8`;if(t===`vp9`){if(!o){let t=e.width*e.height,n=np(zh).level;for(let e of zh)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=o.profile.toString().padStart(2,`0`),n=o.level.toString().padStart(2,`0`),r=o.bitDepth.toString().padStart(2,`0`),i=o.chromaSubsampling.toString().padStart(2,`0`),a=o.colourPrimaries.toString().padStart(2,`0`),s=o.transferCharacteristics.toString().padStart(2,`0`),c=o.matrixCoefficients.toString().padStart(2,`0`),l=o.videoFullRangeFlag.toString().padStart(2,`0`),u=`vp09.${t}.${n}.${r}.${i}`;return u+=`.${a}.${s}.${c}.${l}`,u.endsWith(Bh)&&(u=u.slice(0,-15)),u}if(t===`av1`){if(!s){let t=e.width*e.height,n=np(zh).level;for(let e of zh)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=s.profile,n=s.level.toString().padStart(2,`0`),i=s.tier?`H`:`M`,a=s.bitDepth.toString().padStart(2,`0`),o=s.monochrome?`1`:`0`,c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),l=r?.primaries?pp[r.primaries]:1,u=r?.transfer?hp[r.transfer]:1,d=r?.matrix?_p[r.matrix]:1,f=+!!r?.fullRange,p=`av01.${t}.${n}${i}.${a}`;return p+=`.${o}.${c.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith(Vh)&&(p=p.slice(0,-17)),p}if(t===`prores`)return c??`apch`;throw t!==null&&Np(t),TypeError(`Unhandled codec '${t}'.`)},Kh=e=>{switch(e.codec){case`avc`:{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Pm(e.codecDescription)?.sequenceParameterSets[0]),t){let e=Im(t);if(e)return{primaries:mp[e.colourPrimaries],transfer:gp[e.transferCharacteristics],matrix:vp[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`hevc`:{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Tm.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=Xm(e.codecDescription)?.arrays.find(e=>e.nalUnitType===Tm.SPS_NUT)?.nalUnits[0]),t){let e=Bm(t);if(e)return{primaries:mp[e.colourPrimaries],transfer:gp[e.transferCharacteristics],matrix:vp[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case`vp8`:break;case`vp9`:if(e.vp9CodecInfo)return{primaries:mp[e.vp9CodecInfo.colourPrimaries],transfer:gp[e.vp9CodecInfo.transferCharacteristics],matrix:vp[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case`av1`:if(e.av1CodecInfo)return{primaries:mp[e.av1CodecInfo.colourPrimaries],transfer:gp[e.av1CodecInfo.transferCharacteristics],matrix:vp[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case`prores`:if(e.proresCodecInfo)return{primaries:mp[e.proresCodecInfo.colourPrimaries],transfer:gp[e.proresCodecInfo.transferCharacteristics],matrix:vp[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},qh=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r,dtsFormat:i}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?hm(n).objectType:r.objectType,`mp4a.40.${e}`}}if(t===`mp3`)return`mp3`;if(t===`opus`)return`opus`;if(t===`vorbis`)return`vorbis`;if(t===`flac`)return`flac`;if(t===`ac3`)return`ac-3`;if(t===`eac3`)return`ec-3`;if(t===`dts`)return i??`dtsc`;if(t&&Ph.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},Jh=48e3,Yh=/^pcm-([usf])(\d+)(be)?$/,Xh=e=>{if(z(Ph.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=Yh.exec(e);z(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?128:0}},Zh=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:Hh.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:Uh.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:Yh.test(e)?e:e===`webvtt`?`webvtt`:null,Qh=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`,...Hh],$h=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,eg=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,tg=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ng=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,rg=(e,t)=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!Qh.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectWidth!==void 0!=(e.decoderConfig.displayAspectHeight!==void 0))throw TypeError(`Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.`);if(e.decoderConfig.description!==void 0&&!Sp(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(pp);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(hp);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(_p);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!$h.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!eg.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!tg.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)){if(!ng.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)}else if(Hh.some(t=>e.decoderConfig.codec.startsWith(t))&&!Hh.some(t=>e.decoderConfig.codec===t))throw TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Hh.join(`, `)}.`);if(t!==null&&Zh(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},ig=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`,`dts`],ag=(e,t)=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!ig.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!Sp(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if(e.decoderConfig.codec.startsWith(`dts`)){if(!Uh.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Uh.join(`, `)}.`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!Ph.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ph.join(`, `)}).`);if(t!==null&&Zh(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},og=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},sg=class{constructor(e){this.input=e}dispose(){}},cg=/* #__PURE__ */ new Uint8Array,lg=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===cg&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===cg}get microsecondTimestamp(){return Math.trunc(Up*this.timestamp)}get microsecondDuration(){return Math.trunc(Up*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`EncodedAudioChunk is not available in this environment.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},ug=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},dg=e=>{let t=sp(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=Tp(e.subarray(n,n+16));n+=16;let a=null;if(r>0){let r=t.getUint32(n);if(n+=4,r>0){a=[];for(let t=0;t<r;t++)a.push(Tp(e.subarray(n,n+16))),n+=16}}let o=t.getUint32(n);return n+=4,{systemId:i,keyIds:a,data:e.slice(n,n+o)}},fg=(e,t)=>e.systemId===t.systemId&&Xp(e.data,t.data),pg=e=>{let t=H(e),n=V_(e,4),r=8;t===1&&(t=R_(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},mg=e=>L_(e)/65536,hg=e=>L_(e)/1073741824,gg=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=V(e);if(t|=n&127,!(n&128))break}return t},_g=e=>{let t=P_(e);return e.skip(2),t=Math.min(t,e.remainingLength),up.decode(N_(e,t))},vg=e=>{let t=pg(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=H(e);e.skip(4);let r=N_(e,t.contentSize-8);switch(n){case 1:return up.decode(r);case 2:return new lp(`utf-16be`).decode(r);case 13:return new sm(r,`image/jpeg`);case 14:return new sm(r,`image/png`);case 27:return new sm(r,`image/bmp`);default:return r}},yg=/* @__PURE__ */ new Uint32Array(256),bg=/* @__PURE__ */ new Uint32Array(256),xg=/* @__PURE__ */ new Uint32Array(256),Sg=/* @__PURE__ */ new Uint32Array(256),Cg=/* @__PURE__ */ new Uint32Array(256),wg=/* @__PURE__ */ new Uint32Array(256),Tg=/* @__PURE__ */ new Uint32Array(10),Eg=!1,Dg=()=>{let e=/* @__PURE__ */ new Uint8Array(256),t=/* @__PURE__ */ new Uint8Array(256),n=/* @__PURE__ */ new Uint8Array(256);for(let e=0,r=1;e<256;e++)n[e]=r,t[r]=e,r=r^r<<1^(r&128?283:0);let r=(e,r)=>e&&r?n[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let i=n[255-t[r]],a=i^i<<1^i<<2^i<<3^i<<4;a=a>>>8^a&255^99,e[r]=a}for(let t=0;t<256;t++){let n=e[t],i=e.indexOf(t);yg[t]=n<<24|n<<16|n<<8|n,wg[t]=i<<24|i<<16|i<<8|i;let a=r(i,14),o=r(i,9),s=r(i,13),c=r(i,11),l=a<<24|o<<16|s<<8|c;bg[t]=l,xg[t]=l>>>8|l<<24,Sg[t]=l>>>16|l<<16,Cg[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)Tg[e]=i<<24,i=i<<1^(i&128?283:0);Eg=!0},Og=class{constructor(){this.roundkey=/* @__PURE__ */ new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=/* @__PURE__ */ new Uint8Array(16),this.out=/* @__PURE__ */ new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){z(e.byteLength===16),z(t.byteLength===16),Eg||Dg();let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^yg[t>>>16&255]&4278190080^yg[t>>>8&255]&16711680^yg[t>>>0&255]&65280^yg[t>>>24&255]&255^Tg[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;e<t;e+=4,t-=4)for(let n=0;n<4;n++){let r=this.roundkey[e+n];this.roundkey[e+n]=this.roundkey[t+n],this.roundkey[t+n]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let n=this.roundkey[e+t];this.roundkey[e+t]=bg[yg[n>>>24&255]&255]^xg[yg[n>>>16&255]&255]^Sg[yg[n>>>8&255]&255]^Cg[yg[n>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3],i=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),s=this.inView.getUint32(12,!1),c,l,u,d;for(let i=1;i<10;i++){let a=i*4;c=bg[e>>>24]^xg[r>>>16&255]^Sg[n>>>8&255]^Cg[t&255]^this.roundkey[a],l=bg[t>>>24]^xg[e>>>16&255]^Sg[r>>>8&255]^Cg[n&255]^this.roundkey[a+1],u=bg[n>>>24]^xg[t>>>16&255]^Sg[e>>>8&255]^Cg[r&255]^this.roundkey[a+2],d=bg[r>>>24]^xg[n>>>16&255]^Sg[t>>>8&255]^Cg[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=wg[e>>>24&255]&4278190080^wg[r>>>16&255]&16711680^wg[n>>>8&255]&65280^wg[t>>>0&255]&255^this.roundkey[40],p=wg[t>>>24&255]&4278190080^wg[e>>>16&255]&16711680^wg[r>>>8&255]&65280^wg[n>>>0&255]&255^this.roundkey[41],m=wg[n>>>24&255]&4278190080^wg[t>>>16&255]&16711680^wg[e>>>8&255]&65280^wg[r>>>0&255]&255^this.roundkey[42],h=wg[r>>>24&255]&4278190080^wg[n>>>16&255]&16711680^wg[t>>>8&255]&65280^wg[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=i,this.iv[1]=a,this.iv[2]=o,this.iv[3]=s}},kg=class e extends sg{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=Jf,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=/* @__PURE__ */ new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return ug({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1,n=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Jp(r)&&(r=await r),!r)break;let i=e,a=pg(r);if(!a)break;if(a.name===`ftyp`||a.name===`styp`){let e=V_(r,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(r.filePos,a.contentSize);if(Jp(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+a.totalSize,n=!0;break}else if(a.name===`moof`){if(!this.input._initInput)throw Error(`"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.`);await this.copyMetadataFromInitInput(this.input._initInput),t=!1,n=!0;break}e=i+a.totalSize}if(!n&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){z(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Jp(e)&&(e=await e),z(e);let t=H(e),n=this.reader.fileSize-t;if(n>=0&&n<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(n,8,16);if(Jp(e)&&(e=await e),e){let t=pg(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);Jp(n)&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}async copyMetadataFromInitInput(t){let n=await t._getDemuxer();if(n.constructor!==e)throw Error(`Init input must match the input's format.`);await n.readMetadata(),this.movieTimescale=n.movieTimescale,this.movieDurationInTimescale=n.movieDurationInTimescale,this.movieMatrix=n.movieMatrix,this.metadataTags=n.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=n.fragmentTrackDefaults,this.psshBoxes=n.psshBoxes;for(let e of n.tracks){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,matrix:e.matrix,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:e.maxBitrate,avgBitrate:e.avgBitrate,info:e.info};e.trackBacking&&(z(t.info),t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new jg(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new Mg(t),this.tracks.push(t)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;z(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&Ph.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){z(e.info?.type===`audio`);let n=Xh(e.info.codec),r=[],i=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],s=t.sampleToChunk[a+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let s=o.startSampleIndex+a*o.samplesPerChunk,c=s+o.samplesPerChunk,l=kp(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=kp(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,h=np(r);h&&h.delta===m?h.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:p,count:1,delta:m});let g=o.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;i.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);Jp(t)&&(t=await t),z(t);let n=pg(t);z(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);Jp(r)&&(r=await r),z(r),this.traverseBox(r);let i=this.lastReadFragment;z(i&&i.moofOffset===e);for(let[,e]of i.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(r)Lg(e,r.timestamp);else{let t=kp(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Lg(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=kp(n,e.startTimestamp,e=>e.startTimestamp);if((r===-1||n[r].moofOffset!==i.moofOffset)&&n.splice(r+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){let n=await Vg(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t<Math.min(e.samples.length,n.length);t++){let r=n[t];e.samples[t].encryption=r}}}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=pg(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=pg(e);if(!n)return!1;let r=e.filePos,i=t+n.totalSize;switch(n.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mvhd`:{let t=V(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=H(e),this.movieDurationInTimescale=R_(e)):(e.skip(8),this.movieTimescale=H(e),this.movieDurationInTimescale=H(e)),e.skip(16),this.movieMatrix=Rg(e)}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...um,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:Jf,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(r,n.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new jg(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new Mg(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=V(e),r=!!(F_(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=H(e),e.skip(4),t.durationInMovieTimescale=H(e);else if(n===1)e.skip(16),t.id=H(e),e.skip(4),t.durationInMovieTimescale=R_(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16),t.matrix=tp(Rg(e),this.movieMatrix)}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=V(e);e.skip(3);let r=!1,i=0,a=H(e);for(let o=0;o<a;o++){let a=n===1?R_(e):H(e),o=n===1?z_(e):L_(e),s=mg(e);if(r){om._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){om._warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=V(e);e.skip(3),n===0?(e.skip(8),t.timescale=H(e),t.durationInMediaTimescale=H(e)):n===1&&(e.skip(16),t.timescale=H(e),t.durationInMediaTimescale=R_(e));let r=P_(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;Hp(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=V_(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...xp},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,n.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=V(e);e.skip(3);let r=H(e);for(let i=0;i<r;i++){let r=e.filePos,i=pg(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=P_(e),t.info.height=P_(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let n=a===`encv`?t.frmaCodecString:a;t.frmaCodecString=null,n===`avc1`||n===`avc3`?(t.info.codec=`avc`,t.info.avcType=n===`avc1`?1:3):n===`hvc1`||n===`hev1`?t.info.codec=`hevc`:n===`vp08`?t.info.codec=`vp8`:n===`vp09`?t.info.codec=`vp9`:n===`av01`?t.info.codec=`av1`:Hh.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?om._warn(`Unknown encrypted video codec due to missing frma box.`):om._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=P_(e);e.skip(6);let s=P_(e),c=P_(e);e.skip(4);let l=H(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*H(e),e.skip(8)):o===2&&(e.skip(4),l=B_(e),s=H(e),e.skip(4),c=H(e),u=H(e),e.skip(8))),t.info.numberOfChannels=s,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let d=a===`enca`?t.frmaCodecString:a;if(t.frmaCodecString=null,d!==`mp4a`){if(d===`opus`)t.info.codec=`opus`,t.info.sampleRate=Jh;else if(d===`flac`)t.info.codec=`flac`;else if(d===`ulaw`)t.info.codec=`ulaw`;else if(d===`alaw`)t.info.codec=`alaw`;else if(d===`ac-3`)t.info.codec=`ac3`;else if(d===`ec-3`)t.info.codec=`eac3`;else if(Uh.includes(d))t.info.codec=`dts`,t.info.dtsFormat=d;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(om._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if(d===`sowt`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(om._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if(d===`raw `)t.info.codec=`pcm-u8`;else if(d===`in24`)t.info.codec=t.info.pcmLittleEndian?`pcm-s24`:`pcm-s24be`;else if(d===`in32`)t.info.codec=t.info.pcmLittleEndian?`pcm-s32`:`pcm-s32be`;else if(d===`fl32`)t.info.codec=t.info.pcmLittleEndian?`pcm-f32`:`pcm-f32be`;else if(d===`fl64`)t.info.codec=t.info.pcmLittleEndian?`pcm-f64`:`pcm-f64be`;else if(d===`ipcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===16?t.info.codec=`pcm-s16`:e===24?t.info.codec=`pcm-s24`:e===32?t.info.codec=`pcm-s32`:(om._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):e===16?t.info.codec=`pcm-s16be`:e===24?t.info.codec=`pcm-s24be`:e===32?t.info.codec=`pcm-s32be`:(om._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if(d===`fpcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===32?t.info.codec=`pcm-f32`:e===64?t.info.codec=`pcm-f64`:(om._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(om._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if(d===`lpcm`&&u!==null){let e=c+7>>3,n=!!(u&1),r=!!(u&2),i=u&4?-1:0;c>0&&c<=64&&(n?c===32&&(t.info.codec=r?`pcm-f32be`:`pcm-f32`):i&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=r?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=r?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=r?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&om._warn(`Unsupported PCM format.`)}else d===null?om._warn(`Unknown encrypted audio codec due to missing frma box.`):om._warn(`Unsupported audio codec (sample entry type '${i.name}').`)}}e.filePos=r+i.totalSize}}break;case`frma`:{let t=this.currentTrack;if(!t)break;t.frmaCodecString=V_(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=V_(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:om._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=V(e);e.skip(3),e.skip(1);let r=V(e);if(n>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=r&15):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=V(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=V(e),t.encryptionInfo.defaultKid=Tp(N_(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=V(e),r=/* @__PURE__ */ new Uint8Array(16);r.set(N_(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t||(z(t.info),n.contentSize===0))break;t.info.codecDescription=N_(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t||(z(t.info),n.contentSize===0))break;t.info.codecDescription=N_(e,n.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`),e.skip(4);let n=V(e),r=V(e),i=V(e),a=i>>4,o=i>>1&7,s=i&1,c=V(e),l=V(e),u=V(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`),e.skip(1);let r=V(e),i=r>>5,a=r&31,o=V(e),s=o>>7,c=o>>6&1,l=o>>5&1,u=o>>4&1,d=o>>3&1,f=o>>2&1,p=o&3,m=i===2&&c?l?12:10:c?10:8;e.skip(1);let h=nh(N_(e,n.contentSize-4));t.info.av1CodecInfo={profile:i,level:a,tier:s,bitDepth:m,monochrome:u,chromaSubsamplingX:d,chromaSubsamplingY:f,chromaSamplePosition:p,videoFullRangeFlag:h?.videoFullRangeFlag??0,colourPrimaries:h?.colourPrimaries??2,transferCharacteristics:h?.transferCharacteristics??2,matrixCoefficients:h?.matrixCoefficients??2}}break;case`colr`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`);let n=V_(e,4);if(n!==`nclx`&&n!==`nclc`)break;let r=P_(e),i=P_(e),a=P_(e),o;n===`nclx`&&(o=!!(V(e)&128)),t.info.colorSpace={primaries:mp[r],transfer:gp[i],matrix:vp[a],fullRange:o}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`video`);let n=H(e),r=H(e);n>0&&r>0&&(n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n))}break;case`btrt`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=H(e),r=H(e);t.maxBitrate=n>0?n:null,t.avgBitrate=r>0?r:null}break;case`wave`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4),z(V(e)===3),gg(e),e.skip(2);let n=V(e),r=!!(n&128),i=!!(n&64),a=!!(n&32);if(r&&e.skip(2),i){let t=V(e);e.skip(t)}a&&e.skip(2),z(V(e)===4);let o=gg(e),s=e.filePos,c=V(e);if(c===64||c===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?t.info.codec=`mp3`:c===221?t.info.codec=`vorbis`:c===169?t.info.codec=`dts`:om._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){z(V(e)===5);let n=gg(e);if(t.info.codecDescription=N_(e,n),t.info.codec===`aac`){let e=hm(t.info.codecDescription);e.outputNumberOfChannels!==null&&(t.info.numberOfChannels=e.outputNumberOfChannels),e.outputSampleRate!==null&&(t.info.sampleRate=e.outputSampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),t.info.pcmLittleEndian=!!(P_(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(4);let n=V(e);t.info.pcmLittleEndian=!!(n&1),t.info.pcmSampleSize=V(e)}break;case`dOps`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(1);let n=V(e),r=P_(e),i=H(e),a=I_(e),o=V(e),s;s=o===0?/* @__PURE__ */ new Uint8Array:N_(e,2+n);let c=new Uint8Array(19+s.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,n),l.setUint16(10,r,!0),l.setUint32(12,i,!0),l.setInt16(16,a,!0),l.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`),e.skip(4);let n=e.filePos;for(;e.filePos<i;){let n=V(e),r=F_(e);if((n&127)===sh.STREAMINFO){e.skip(10);let n=H(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let a=N_(e,r-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let n=new fm(N_(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=Sm[r]),t.info.numberOfChannels=ch[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let r=fh(N_(e,n.contentSize));if(!r){om._warn(`Invalid dec3 box contents, ignoring.`);break}let i=ph(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=mh(r)}break;case`ddts`:{let t=this.currentTrack;if(!t)break;z(t.info?.type===`audio`);let r=Ah(N_(e,Math.min(n.contentSize,20)));if(!r){om._warn(`Invalid ddts box contents, ignoring.`);break}t.info.sampleRate=r.sampleRate,r.numberOfChannels!==null&&(t.info.numberOfChannels=r.numberOfChannels)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=0,i=0;for(let a=0;a<n;a++){let n=H(e),a=H(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=0;for(let i=0;i<n;i++){let n=H(e),i=L_(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e),r=H(e);if(n===0)for(let n=0;n<r;n++){let n=H(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=V(e),r=H(e),i=new fm(N_(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=H(e);for(let r=0;r<n;r++){let n=H(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=H(e)-1,r=H(e),i=H(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=H(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=H(e);for(let r=0;r<n;r++){let n=R_(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mehd`:{let t=V(e);e.skip(3);let n=t===1?R_(e):H(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=H(e),n=H(e),r=H(e),i=H(e),a=H(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=V(e);e.skip(3);let n=H(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=H(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[V,P_,F_,H],l=c[a],u=c[o],d=c[s],f=H(e);for(let n=0;n<f;n++){let n=t===1?R_(e):H(e),i=t===1?R_(e):H(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:/* @__PURE__ */ new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(r,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(z(this.currentFragment),this.readContiguousBoxes(e.slice(r,n.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);cond:if(e){if(e.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break cond}e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let n=e.presentationTimestamps[t],r=e.samples[n.sampleIndex];e.firstKeyFrameTimestamp===null&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-n.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],n=e.samples[np(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=n.presentationTimestamp+n.duration;let{currentFragmentState:r}=this.currentTrack;z(r),r.startTimestamp!==null&&(Lg(e,r.startTimestamp),e.startTimestampIsFinal=!0),r.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=r.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=dg(N_(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{z(this.currentFragment),e.skip(1);let t=F_(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=H(e),u=this.tracks.find(e=>e.id===l);if(!u)break;let d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},n?u.currentFragmentState.baseDataOffset=R_(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=H(e)),i&&(u.currentFragmentState.defaultSampleDuration=H(e)),a&&(u.currentFragmentState.defaultSampleSize=H(e)),o&&(u.currentFragmentState.defaultSampleFlags=H(e)),s&&(u.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;z(t.currentFragmentState);let n=V(e);e.skip(3);let r=n===0?H(e):R_(e);t.currentFragmentState.startTimestamp=r}break;case`trun`:{let t=this.currentTrack;if(!t)break;z(this.currentFragment),z(t.currentFragmentState);let n=V(e),r=F_(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=H(e),d=null;i&&(d=L_(e));let f=null;a&&(f=H(e));let p;this.currentFragment.trackData.has(t.id)?(p=this.currentFragment.trackData.get(t.id),d!==null&&(p.currentOffset=t.currentFragmentState.baseDataOffset+d)):(p={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,p));for(let r=0;r<u;r++){let i;o?i=H(e):(z(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=H(e):(z(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=H(e):(z(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=n===0?H(e):L_(e));let m=!(u&65536);p.samples.push({presentationTimestamp:p.currentTimestamp+d,duration:i,byteOffset:p.currentOffset,byteSize:a,isKeyFrame:m,encryption:null}),p.currentOffset+=a,p.currentTimestamp+=i}this.currentFragment.implicitBaseDataOffset=p.currentOffset}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),F_(e)&1){let n=V_(e,4),r=H(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=V(e),r=H(e),i=null;n===0&&r>0&&(i=N_(e,r));let a=Bg(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=V(e);if(F_(e)&1){let n=V_(e,4),r=H(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=H(e);if(r===0)break;r>1&&om._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?H(e):Number(R_(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=Bg(t);a.offset=i}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;z(this.currentFragment);let n=this.currentFragment.trackData.get(t.id);if(!n)break;e.skip(1);let r=!!(F_(e)&2),i=H(e),a=t.encryptionInfo.defaultPerSampleIvSize;z(a!==null);for(let o=0;o<Math.min(i,n.samples.length);o++){let i=/* @__PURE__ */ new Uint8Array(16);a>0?i.set(N_(e,a),0):i.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(r){let t=P_(e);s=[];for(let n=0;n<t;n++){let t=P_(e),n=H(e);s.push({clearLen:t,protectedLen:n})}}let c=n.samples[o];c.encryption={iv:i,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=_g(n):this.metadataTags.raw[e.name]??=N_(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=up.decode(N_(n,e.contentSize)):this.metadataTags.title??=_g(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=_g(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=_g(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=_g(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=_g(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=_g(n));break;case`©day`:if(!this.currentTrack){let e=new Date(_g(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=_g(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=_g(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=H(e)!==0;this.currentMetadataKeys=/* @__PURE__ */ new Map,t?this.readContiguousBoxes(e.slice(r,n.contentSize)):this.readContiguousBoxes(e.slice(r+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=H(e);for(let n=0;n<t;n++){let t=H(e);e.skip(4);let r=up.decode(N_(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=vg(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof sm?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=sp(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=sp(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=i,!0}},Ag=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=/* @__PURE__ */ new WeakMap,this.packetToFragmentLocation=/* @__PURE__ */ new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(z(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Lp(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Ng(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!zg(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=kp(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Pg(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!zg(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=Mp(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let e=Ig(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return z(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=Fg(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=cg;else{let t=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(Jp(t)&&(t=await t),!t)return null;if(r=N_(t,n.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){let n=await Vg(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(t=n[e])}t??=Hg(this.internalTrack.encryptionInfo),t&&(r=await Ug(this.internalTrack,t,r,null))}}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new lg(r,n.isKeyFrame?`key`:`delta`,i,a,e,n.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).samples[t];z(r);let i;if(n.metadataOnly)i=cg;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(Jp(t)&&(t=await t),!t)return null;if(i=N_(t,r.byteSize),this.internalTrack.encryptionInfo){let t=r.encryption??Hg(this.internalTrack.encryptionInfo);t&&(i=await Ug(this.internalTrack,t,i,e))}}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new lg(i,r.isKeyFrame?`key`:`delta`,a,o,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,n,r,i){let a=this.internalTrack.demuxer,o=null,s=null,c=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,i);n!==-1&&(s=e,c=n)}let l=kp(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=kp(this.internalTrack.fragmentPositionCache,n,e=>e.startTimestamp),f=d===-1?null:this.internalTrack.fragmentPositionCache[d],p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(m,8,16);if(Jp(e)&&(e=await e),!e)break;let n=m,l=pg(e);if(!l)break;if(l.name===`moof`){o=await a.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,i);e!==-1&&(s=o,c=e)}m=n+l.totalSize}if(u&&(!s||s.moofOffset<u.moofOffset)){let e=this.internalTrack.fragmentLookupTable[l-1];z(!e||e.timestamp<u.timestamp);let n=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,n,r,i)}return s?this.fetchPacketInFragment(s,c,i):null}},jg=class extends Ag{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`video`}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Mm(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Vm(e.data)}else if(this.internalTrack.info.codec===`vp9`&&(!this.internalTrack.info.vp9CodecInfo||!eh(this.internalTrack.info.vp9CodecInfo))){let e=await this.getFirstPacket({}),t=e&&$m(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else if(this.internalTrack.info.codec===`av1`&&(!this.internalTrack.info.av1CodecInfo||!rh(this.internalTrack.info.av1CodecInfo))){let e=await this.getFirstPacket({}),t=e&&nh(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else if(this.internalTrack.info.codec===`prores`&&!this.internalTrack.info.proresCodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&ih(e.data)}if(!yp(this.internalTrack.info.colorSpace)){let e=Kh(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let e={codec:Gh(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},Mg=class extends Ag{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`audio`}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Dh(e.data)}return{codec:qh(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},Ng=(e,t)=>{if(e.presentationTimestamps){let n=kp(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=kp(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},Pg=(e,t)=>{if(!e.keySampleIndices)return Ng(e,t);if(e.presentationTimestamps){let n=kp(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(Op(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=Ng(e,t),r=kp(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},Fg=(e,t)=>{let n=kp(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=t)return null;let i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=kp(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=kp(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];z(l);let u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=0,m=d;if(e.sampleSizes.length===1)m+=s*(t-f),p+=s*l.samplesPerChunk;else for(let n=f;n<f+l.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(m+=r),p+=r}let h=r.delta;if(e.presentationTimestamps){let n=e.presentationTimestampIndexMap[t];z(n!==void 0),n<e.presentationTimestamps.length-1&&(h=e.presentationTimestamps[n+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:h,sampleOffset:m,sampleSize:s,chunkOffset:d,chunkSize:p,isKeyFrame:!e.keySampleIndices||Op(e.keySampleIndices,t,e=>e)!==-1}},Ig=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=kp(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Lg=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},Rg=e=>[mg(e),mg(e),hg(e),mg(e),mg(e),hg(e),mg(e),mg(e),hg(e)],zg=e=>e.sampleSizes.length===0,Bg=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Vg=async(e,t,n)=>{if(n.resolved)return n.resolved;if(n.offset===null||n.sampleCount===0)throw Error(`Incomplete saiz/saio info; cannot resolve encryption data.`);let r=0;if(n.defaultSampleInfoSize>0)r=n.defaultSampleInfoSize*n.sampleCount;else{z(n.sampleSizes);for(let e=0;e<n.sampleCount;e++)r+=n.sampleSizes[e]}let i=e.requestSlice(n.offset,r);if(Jp(i)&&(i=await i),!i)throw Error(`Failed to read auxiliary encryption info.`);let a=t.defaultPerSampleIvSize;z(a!==null);let o=[];for(let e=0;e<n.sampleCount;e++){let r=n.defaultSampleInfoSize>0?n.defaultSampleInfoSize:n.sampleSizes[e],s=/* @__PURE__ */ new Uint8Array(16);a>0?s.set(N_(i,a),0):s.set(t.defaultConstantIv,0);let c=null;if(r>a){let e=P_(i);c=[];for(let t=0;t<e;t++){let e=P_(i),t=H(i);c.push({clearLen:e,protectedLen:t})}}o.push({iv:s,subsamples:c})}return n.resolved=o,o},Hg=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Ug=async(e,t,n,r)=>{z(e.encryptionInfo);let i=e.encryptionInfo;z(i.defaultKid!==null);let a=i.defaultKid,o,s=e.demuxer.decryptionKeyCache.get(a);if(s)o=await s;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error(`Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.`);let t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>e.keyIds===null||e.keyIds.includes(a));for(let e=0;e<t.length-1;e++)for(let n=e+1;n<t.length;n++)fg(t[e],t[n])&&(t.splice(n,1),n--)}let n=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:t});if(!(typeof n==`string`&&n.length===32&&wp.test(n)||n instanceof Uint8Array&&n.byteLength===16))throw TypeError(`resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.`);return n instanceof Uint8Array?n:Ep(n)})();e.demuxer.decryptionKeyCache.set(a,t),o=await t}return i.scheme===`cenc`||i.scheme===`cens`?Wg(o,i,t,n):Gg(o,i,t,n)},Wg=async(e,t,n,r)=>{let i=/* @__PURE__ */ new Uint8Array(16);i.set(n.iv,0);let a=await crypto.subtle.importKey(`raw`,e,{name:`AES-CTR`},!1,[`decrypt`]),o=async e=>{let t=await crypto.subtle.decrypt({name:`AES-CTR`,counter:i,length:64},a,e);return new Uint8Array(t)};if(!n.subsamples)return o(r);z(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let s=Kg(n.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),c=0;for(let e of s)for(let t of e.perSubsample)c+=t.length;let l=new Uint8Array(c),u=0;for(let e of s)for(let t of e.perSubsample)l.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;let d=await o(l),f=new Uint8Array(r),p=0;for(let e of s)for(let t of e.perSubsample)f.set(d.subarray(p,p+t.length),t.offset),p+=t.length;return f},Gg=(e,t,n,r)=>{let i=new Og;i.init({key:e,iv:n.iv});let a=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(z(a!==null&&o!==null),!n.subsamples){let e=new Uint8Array(r),t=Math.floor(r.length/16);for(let n=0;n<t;n++){let t=n*16;i.in.set(r.subarray(t,t+16)),i.decrypt(),e.set(i.out,t)}return e}if(a===0&&o===0)throw Error(`cbcs with subsamples requires pattern encryption.`);let s=new Uint8Array(r),c=Kg(n.subsamples,a,o),l=new DataView(n.iv.buffer,n.iv.byteOffset,16);for(let e of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(let t of e.perSubsample){let e=t.length/16;for(let n=0;n<e;n++){let e=t.offset+n*16;i.in.set(r.subarray(e,e+16)),i.decrypt(),s.set(i.out,e)}}}return s},Kg=(e,t,n)=>{let r=[],i=t!==0||n!==0,a=0;for(let o of e){a+=o.clearLen;let e=[];if(!i)o.protectedLen>0&&e.push({offset:a,length:o.protectedLen}),a+=o.protectedLen;else{let r=o.protectedLen,i=a;for(;r>0&&!(r<16*t);){let a=16*t;e.push({offset:i,length:a}),i+=a,r-=a;let o=Math.min(16*n,r);i+=o,r-=o}a+=o.protectedLen}r.push({perSubsample:e})}return r},qg=e=>{let t=e.filePos,n=new fm(N_(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}};(/* @__PURE__ */ e(((e,t)=>{t.exports={}})))(),Zp();var Jg=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var Yg=class extends rm{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<`u`&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new k_;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,Jg),e=this._getFileSize(),z(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new k_;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw TypeError(`length, when provided, must be a non-negative integer.`);return new e_(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new Xg(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Xg=class{constructor(e){if(this._freed=!1,e._disposed)throw Error(`Cannot ref a disposed source.`);e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error(`Can't get source; ref has already been freed.`);return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error(`Illegal operation: double free on SourceRef.`);let e=this.source;z(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Zg=class extends Yg{constructor(e,t){if(typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`requestHandler must be a function.`);super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=e=>{if(!(e instanceof Yg||e instanceof Xg))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof Yg?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return Jp(t)?t.then(n):n(t)}},Qg=(e,t)=>e.path===t.path,$g=class extends Yg{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=op(e),this._view=sp(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}};typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e.cancel().catch(()=>{})});var e_=class extends Yg{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw Error(`Cannot create a slice of a disposed source.`);this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length===null?void 0:this._length:e===null?this._length===null?null:this._length:Ip(e-this._offset,0,this._length??1/0)}_read(e,t,n,r){if(this._length!==null&&t>this._length)return null;let i=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+r),a=e=>e?(e.offset-=this._offset,e):null;return Jp(i)?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},t_=class{constructor(){this._isIsobmff=!1}},n_=class extends t_{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Jp(t)&&(t=await t),!t)return null;t.skip(4);let n=V_(t,4);return n!==`ftyp`&&n!==`styp`?null:V_(t,4)}_createDemuxer(e){return new kg(e)}},r_=class extends n_{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!==`qt `;let n=0;for(let t=0;t<10;t++){let t=e._reader.requestSlice(n,8);if(Jp(t)&&(t=await t),!t)return!1;let r=H(t),i=8;if(r===1){let t=e._reader.requestSlice(n+8,8);if(Jp(t)&&(t=await t),!t)return!1;r=R_(t),i=16}if(r<i)return!1;let a=V_(t,4);if(a===`moof`||a===`sidx`)return!0;if(a===`emsg`||a===`prft`||a===`free`)n+=r;else return!1}return!1}get name(){return`MP4`}get mimeType(){return`video/mp4`}},i_=class extends n_{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},a_=/* #__PURE__ */ new r_,o_=/* #__PURE__ */ new i_,s_=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`${t}, when provided, must be an object.`);if(e.isobmff!==void 0){if(!e.isobmff||typeof e.isobmff!=`object`)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(e.isobmff.resolveKeyId!==void 0&&typeof e.isobmff.resolveKeyId!=`function`)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(e.hls!==void 0){if(!e.hls||typeof e.hls!=`object`)throw TypeError(`${t}.hls, when provided, must be an object.`);if(e.hls.offsetTimestampsByDateTime!==void 0&&typeof e.hls.offsetTimestampsByDateTime!=`boolean`)throw TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}},c_=[],l_=[],u_=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`);if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!=`boolean`)throw TypeError(`options.skipLiveWait, when defined, must be a boolean.`)},d_=e=>{if(!Qp(e))throw TypeError(`timestamp must be a number.`)},f_=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,p_=class{constructor(e){if(!(e instanceof m_))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(u_(e),this._track.input._disposed)throw new k_;return f_(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){u_(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(d_(e),u_(t),this._track.input._disposed)throw new k_;return f_(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);if(u_(t),this._track.input._disposed)throw new k_;return f_(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(d_(e),u_(t),this._track.input._disposed)throw new k_;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(z(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);if(u_(t),this._track.input._disposed)throw new k_;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(z(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof lg))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof lg))throw TypeError(`endPacket must be an EncodedPacket.`);if(u_(n),this._track.input._disposed)throw new k_;let r=[],{promise:i,resolve:a}=Ap(),{promise:o,resolve:s}=Ap(),c=!1,l=!1,u=null,d=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>p()){({promise:o,resolve:s}=Ap()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=Ap(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{d||(u=e,d=!0,a())});let m=this._track;return{async next(){for(;;)if(m.input._disposed)throw new k_;else if(l)return{value:void 0,done:!0};else if(d)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},m_=class e{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof __}isAudioTrack(){return this instanceof v_}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return h_(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return h_(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return h_(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return h_(this._backing.getTimeResolution(),`timeResolution`,`getTimeResolution`)}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return h_(this._backing.getDisposition(),`disposition`,`getDisposition`)}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return zp((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new p_(this),r=1/0,i=-1/0,a=0,o=0;for await(let s of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&s.timestamp>=i)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,o+=s.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(i-r)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an InputTrack.`);return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(S_({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(S_({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(S_({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(S_({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(S_({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=g_(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=g_(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=g_(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},h_=(e,t,n)=>{if(Jp(e))throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},g_=e=>{if(e!==void 0&&typeof e!=`function`)throw TypeError(`predicate, when provided, must be a function.`);return e?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`predicate must return or resolve to a boolean value.`);return e},r=e(t);return Jp(r)?r.then(n):n(r)}:void 0},__=class extends m_{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return`video`}async getCodec(){return this._backing.getCodec()}get codec(){return h_(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()===`prores`}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return h_(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return h_(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Xf(await this._backing.getTransformationMatrix())}get rotation(){return Xf(h_(this._backing.getTransformationMatrix(),`rotation`,`getRotation`))}async getFlip(){return Zf(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return h_(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return h_(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=tm({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=tm({num:h_(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*h_(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:h_(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*h_(this._backing.getCodedWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)})}async getDisplayWidth(){return await this._backing.getMetadataDisplayWidth?.()??(await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let t=h_(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}return h_(Xf(h_(this._backing.getTransformationMatrix(),`displayWidth`,`getDisplayWidth`))%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight(),`displayWidth`,`getDisplayWidth`)}async getDisplayHeight(){return await this._backing.getMetadataDisplayHeight?.()??(await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let t=h_(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}return h_(Xf(h_(this._backing.getTransformationMatrix(),`displayHeight`,`getDisplayHeight`))%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth(),`displayHeight`,`getDisplayHeight`)}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pq`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return z(t!==null),c_.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return om._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();if(t===null)return null;let n=await this.getDecoderConfig();return z(n),oh(t,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!Qp(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError(`options.targetPacketCount must be a non-negative number.`);let t=await this.getTimeResolution(),n=e.targetPacketCount??256,r=new p_(this),i=[],a=-1/0,o=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(i.length>=n&&e.timestamp>=a)break;i.push(e.timestamp),a=Math.max(a,e.timestamp),o++}let s=new Float64Array(i.length);for(let e=0;e<i.length;e++)s[e]=Math.round(i[e]*t);s.sort();let c=1;for(let e=1;e<s.length;e++)s[e]!==s[c-1]&&(s[c++]=s[e]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};let l=s.subarray(0,c),u=w_(l,t),d=u??t,f=u===null?null:t/u,p=/* @__PURE__ */ new Map,m=1/0,h=-1/0,g=0;for(let e=1;e<c;e++){let t=l[e]-l[e-1],n=f===null?t:Math.max(1,Math.round(t/f));p.set(n,(p.get(n)??0)+1),m=Math.min(m,n),h=Math.max(h,n),g+=n}let _=c-1,v=[...p.keys()].sort((e,t)=>e-t),y=_-1>>1,b=_>>1,x=0,S=0,C=0;for(let e of v)if(C+=p.get(e),x===0&&C>y&&(x=e),C>b){S=e;break}let w=(d/x+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:u===null?E_(w):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:w,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},v_=class extends m_{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return h_(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return h_(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return h_(this._backing.getSampleRate(),`sampleRate`,`getSampleRate`)}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return z(t!==null),l_.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return om._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}},y_=e=>-(e??-1/0),b_=e=>-e,x_=e=>{if(typeof e!=`object`||!e)throw TypeError(`query must be an object.`);if(e.filter!==void 0&&typeof e.filter!=`function`)throw TypeError(`query.filter, when provided, must be a function.`);if(e.sortBy!==void 0&&typeof e.sortBy!=`function`)throw TypeError(`query.sortBy, when provided, must be a function.`);return{filter:e.filter?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`query.filter must return or resolve to a boolean.`);return e},r=e.filter(t);return Jp(r)?r.then(n):n(r)}:void 0,sortBy:e.sortBy?t=>{let n=e=>{if(typeof e!=`number`&&(!Array.isArray(e)||!e.every(e=>typeof e==`number`)))throw TypeError(`query.sortBy must return or resolve to a number or an array of numbers.`);return e},r=e.sortBy(t);return Jp(r)?r.then(n):n(r)}:void 0}},S_=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return Jp(r)?r.then(i):i(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?n=>{let r=e?.sortBy?.(n)??[],i=t?.sortBy?.(n)??[],a=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return Jp(r)||Jp(i)?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),C_=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>Jp(e))){let t=await Promise.all(r);n=e.filter((e,n)=>t[n])}else n=e.filter((e,t)=>r[t])}if(!t?.sortBy)return n;let r=n.map(e=>t.sortBy(e)),i=r.some(e=>Jp(e))?await Promise.all(r):r;return n.map((e,t)=>({track:e,sortValue:i[t]})).sort((e,t)=>{let n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}).map(e=>e.track)},w_=(e,t)=>{let n=1e6,r=.98,i=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;let o=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let n=e[t]-e[t-1];if(!(n>0))return null;o[t-1]=n}let s=o.slice();s.sort();let c=s[Math.floor(s.length*.05)];for(let e=0;e<6;e++){let e=0,t=0;for(let n of o){let r=Math.max(1,Math.round(n/c));Math.abs(n-r*c)>=i||(e+=n,t+=r)}if(t===0)return null;let n=e/t;if(Math.abs(n-c)<=1e-12*Math.max(1,c)){c=n;break}c=n}let l=0,u=0,d=0;for(let e of o){let t=Math.max(1,Math.round(e/c));Math.abs(e-t*c)>=i||(l++,u+=e,d+=t)}if(l/o.length<r)return null;c=u/d;let f=1/Math.min(d,1e3),p=Math.max(2**-52,c-f),m=c+f,h=t/m,g=t/p,_=t/c,v=null,y=1/0;for(let e of a){if(e<h||e>g)continue;let t=Math.abs(e/_-1);t<y&&(v=e,y=t)}if(v===null){let e=T_(p,m,n),r=T_(h,g,n);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))v=r.num/r.den;else if(e)v=t*e.den/e.num;else return null}let b=t/v,x=0;for(let e of o){let t=Math.max(1,Math.round(e/b));Math.abs(e-t*b)<i&&x++}return x/o.length<r?null:v},T_=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return tm({num:n,den:r})}return null},E_=e=>{let t=[24/1.001,30/1.001,60/1.001,120/1.001],n=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(let n of t)if(Math.abs(n/e-1)<=5e-4)return n;let r=e,i=1/0;for(let t of n){let n=Math.abs(t/e-1);n<=.025&&n<i&&(r=t,i=n)}return r};Zp();var D_=class e extends rm{get disposed(){return this._disposed}constructor(t){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=/* @__PURE__ */ new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof t_)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof Yg||t.source instanceof Xg))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof Yg&&t.source._disposed)throw TypeError(`options.source must not be a disposed Source.`);if(t.initInput!==void 0&&!(t.initInput instanceof e))throw TypeError(`options.initInput, when provided, must be an Input.`);t.formatOptions!==void 0&&s_(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof Yg?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){z(this._rootSource instanceof Zg);let t=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){let n=this._sourceCache.find(n=>n.cacheGroup===t&&Qg(n.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let r=this._sourceCachePromises.find(n=>n.cacheGroup===t&&Qg(n.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());let i=(async()=>{let n=await this._getSourceUncached(e);if($p(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=em(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1?e.age:1/0);z(e!==-1);let n=this._sourceCache[e];this._sourceCache.splice(e,1),n.sourceRef.free(),jp(this._sourceRefs,n.sourceRef)}this._sourceRefs.push(n);let r=this._sourceCachePromises.findIndex(t=>t.request===e);return z(r!==-1),this._sourceCachePromises.splice(r,1),{request:e,sourceRef:n,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:i}),i.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new A_(this._rootSource),this._emit(`source`,{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new O_})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),z(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof O_)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(e=>e!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...n.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null);if(n.length===0)return 0;let r=await Promise.all(n.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null),r=(await Promise.all(n.map(e=>e.getDurationFromMetadata(t)))).filter(e=>e!==null);return r.length===0?null:Math.max(...r)}async getTracks(e){return e&&=x_(e),C_((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=x_(e),C_((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=x_(e),C_((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=x_(e);let t=S_(e,{sortBy:async e=>[b_((await e.getDisposition()).default),b_(await e.hasPairableAudioTrack()),b_(!await e.hasOnlyKeyPackets()),y_(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=x_(e);let t=await this.getPrimaryVideoTrack(),n=S_(e,{sortBy:async e=>[b_(!t||e.canBePairedWith(t)),b_((await e.getDisposition()).default),y_(await e.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let n=e.getType()===`video`?new __(this,e):new v_(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},O_=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},k_=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},A_=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw Error(`Reading file size too early; read required first.`);return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new k_;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=/* @__PURE__ */ new Uint8Array;return new j_(t,sp(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,Jg);return Jp(r)?r.then(t=>t?new j_(t.bytes,t.view,t.offset,e,n):null):r?new j_(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new k_;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Ip(this.fileSizeNonStrict-e,t,n));{let r=this.requestSlice(e,n),i=r=>r||(z(this.fileSizeNonStrict!==null),this.requestSlice(e,Ip(this.fileSizeNonStrict-e,t,n)));return Jp(r)?r.then(i):i(r)}}requestEntireFile(){return this.fileSizeNonStrict===null?(async()=>{let e=[],t=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let n=this.requestSliceRange(t,0,1024);if(Jp(n)&&(n=await n),!n||n.length===0)break;let r=N_(n,n.length);e.push(r),t+=n.length}let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new j_(n,sp(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},j_=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,sp(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},M_=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},N_=(e,t)=>{M_(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},V=e=>(M_(e,1),e.view.getUint8(e.bufferPos++)),P_=e=>{M_(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},F_=e=>{M_(e,3);let t=Pp(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},I_=e=>{M_(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},H=e=>{M_(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},L_=e=>{M_(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},R_=e=>{let t=H(e),n=H(e);return t*4294967296+n},z_=e=>{let t=L_(e),n=H(e);return t*4294967296+n},B_=e=>{M_(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},V_=(e,t)=>{M_(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},H_=class{constructor(e){this.mutex=new Cp,this.trackTimestampInfo=/* @__PURE__ */ new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},U_=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,W_=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},G_=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);z(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},U=/* #__PURE__ */ new Uint8Array(8),K_=/* #__PURE__ */ new DataView(U.buffer),q_=e=>[(e%256+256)%256],W=e=>(K_.setUint16(0,e,!1),[U[0],U[1]]),J_=e=>(K_.setInt16(0,e,!1),[U[0],U[1]]),Y_=e=>(K_.setUint32(0,e,!1),[U[1],U[2],U[3]]),G=e=>(K_.setUint32(0,e,!1),[U[0],U[1],U[2],U[3]]),X_=e=>(K_.setInt32(0,e,!1),[U[0],U[1],U[2],U[3]]),Z_=e=>(K_.setUint32(0,Math.floor(e/2**32),!1),K_.setUint32(4,e,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),Q_=e=>(K_.setInt32(0,Math.floor(e/2**32),!1),K_.setUint32(4,e,!1),[U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7]]),$_=e=>(K_.setInt16(0,256*e,!1),[U[0],U[1]]),ev=e=>(K_.setInt32(0,2**16*e,!1),[U[0],U[1],U[2],U[3]]),tv=e=>(K_.setInt32(0,2**30*e,!1),[U[0],U[1],U[2],U[3]]),nv=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},rv=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},iv=e=>[ev(e[0]),ev(e[1]),tv(e[2]),ev(e[3]),ev(e[4]),tv(e[5]),ev(e[6]),ev(e[7]),tv(e[8])],K=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),av=(e,t,n,r,i)=>K(e,[q_(t),Y_(n),r??[]],i),ov=e=>e.isQuickTime?K(`ftyp`,[rv(`qt `),G(512),rv(`qt `)]):e.fragmented?e.cmaf?K(`ftyp`,[rv(`iso5`),G(512),rv(`iso5`),rv(`iso6`),rv(`mp41`),rv(`cmfc`),rv(`dash`)]):K(`ftyp`,[rv(`iso5`),G(512),rv(`iso5`),rv(`iso6`),rv(`mp41`)]):K(`ftyp`,[rv(`isom`),G(512),rv(`isom`),e.holdsAvc?rv(`avc1`):[],rv(`mp41`)]),sv=()=>K(`styp`,[rv(`iso5`),G(0),rv(`iso5`),rv(`iso6`),rv(`mp41`),rv(`cmfc`),rv(`dash`)]),cv=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),av(`sidx`,1,0,[G(1),G(By),Z_(Uy(n,By)),Z_(0),W(0),W(1),G(t&2147483647),G(Uy(r,By)),G(0)])},lv=e=>({type:`mdat`,largeSize:e}),uv=e=>({type:`free`,size:e}),dv=e=>K(`moov`,void 0,[fv(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>pv(t,e.creationTime)),e.isFragmented?ny(e.trackDatas):null,_y(e)]),fv=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,Uy(Wy(e),By)+Uy(e.startTimestampOffset??0,By)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!rp(e)||!rp(n),a=i?Z_:G;return av(`mvhd`,+i,0,[a(e),a(e),G(By),a(n),ev(1),$_(1),Array(10).fill(0),iv(Jf),Array(24).fill(0),G(r)])},pv=(e,t)=>{let n=Hy(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return K(`trak`,void 0,[mv(e,t),r?hv(e):null,gv(e,t),n.name===void 0?null:K(`udta`,void 0,[K(`name`,[...dp.encode(n.name)])])])},mv=(e,t)=>{let n=Math.max(0,Uy(Wy(e),By)+Uy(e.startTimestampOffset??0,By)),r=!rp(t)||!rp(n),i=r?Z_:G,a;if(e.type===`video`&&e.track.metadata.transformationMatrix)a=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata;a=Yf(tp(Qf(t??0),ep(n?-1:1,1)),e.info.width,e.info.height)}else a=Jf;let o=2;e.track.metadata.disposition?.default!==!1&&(o|=1);let s=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:Np(e);return av(`tkhd`,+r,o,[i(t),i(t),G(e.track.id),G(0),i(n),Array(8).fill(0),W(0),W(s),$_(+(e.type===`audio`)),W(0),iv(a),ev(e.type===`video`?e.info.width:0),ev(e.type===`video`?e.info.height:0)])},hv=e=>{let t=e.startTimestampOffset;if(z(t!==null),t>0){let n=Uy(t,By),r=Uy(Wy(e),By),i=!rp(n)||!rp(r),a=i?Z_:G,o=i?Q_:X_;return K(`edts`,void 0,[av(`elst`,+!!i,0,[G(2),a(n),o(-1),ev(1),a(r),o(0),ev(1)])])}{let n=Uy(-t,e.timescale),r=Math.max(0,Uy(Wy(e),By)+Uy(t,By)),i=!ip(n)||!rp(r),a=i?Z_:G,o=i?Q_:X_;return K(`edts`,void 0,[av(`elst`,+!!i,0,[G(1),a(r),o(n),ev(1)])])}},gv=(e,t)=>K(`mdia`,void 0,[_v(e,t),bv(!0,vv[e.type],yv[e.type]),xv(e)]),_v=(e,t)=>{let n=Uy(Wy(e),e.timescale),r=!rp(t)||!rp(n),i=r?Z_:G;return av(`mdhd`,+r,0,[i(t),i(t),G(e.timescale),i(n),W(jy(e.track.metadata.languageCode??`und`)),W(0)])},vv={video:`vide`,audio:`soun`,subtitle:`text`},yv={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},bv=(e,t,n,r=`\0\0\0\0`)=>av(`hdlr`,0,0,[e?rv(`mhlr`):G(0),rv(t),rv(r),G(0),G(0),rv(n,!0)]),xv=e=>K(`minf`,void 0,[Sv[e.type](),Cv(),Ev(e)]),Sv={video:()=>av(`vmhd`,0,1,[W(0),W(0),W(0),W(0)]),audio:()=>av(`smhd`,0,0,[W(0),W(0)]),subtitle:()=>av(`nmhd`,0,0)},Cv=()=>K(`dinf`,void 0,[wv()]),wv=()=>av(`dref`,0,0,[G(1)],[Tv()]),Tv=()=>av(`url `,0,1),Ev=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return K(`stbl`,void 0,[Dv(e),Yv(e),t?ey(e):null,t?ty(e):null,Zv(e),Qv(e),$v(e),Xv(e)])},Dv=e=>{let t;if(e.type===`video`)t=Ov(Ty(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Dy(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);z(n),t=Iv(n,e)}else e.type===`subtitle`&&(t=qv(ky[e.track.source._codec],e));return z(t),av(`stsd`,0,0,[G(1)],[t])},Ov=(e,t)=>K(e,[[,,,,,,].fill(0),W(1),W(0),W(0),Array(12).fill(0),W(t.info.width),W(t.info.height),G(4718592),G(4718592),G(0),W(1),q_(10),rv(`Mediabunny`),Array(21).fill(0),W(t.info.hasAlphaChannel?32:24),J_(65535)],[Ey[t.track.source._codec]?.(t)??null,Av(t),bp(t.info.decoderConfig.colorSpace)?null:jv(t),kv(t)]),kv=e=>e.avgBitrate===0&&e.maxBitrate===0?null:K(`btrt`,[G(0),G(e.maxBitrate),G(e.avgBitrate)]),Av=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:K(`pasp`,[G(e.info.pixelAspectRatio.num),G(e.info.pixelAspectRatio.den)]),jv=e=>{let t=e.info.decoderConfig.colorSpace;return K(`colr`,[rv(e.muxer.isQuickTime?`nclc`:`nclx`),W(t?.primaries==null?2:pp[t.primaries]),W(t?.transfer==null?2:hp[t.transfer]),W(t?.matrix==null?2:_p[t.matrix]),e.muxer.isQuickTime?[]:q_(!!t?.fullRange<<7)])},Mv=e=>e.info.decoderConfig&&K(`avcC`,[...op(e.info.decoderConfig.description)]),Nv=e=>e.info.decoderConfig&&K(`hvcC`,[...op(e.info.decoderConfig.description)]),Pv=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?pp[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?hp[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?_p[t.colorSpace.matrix]:1;return av(`vpcC`,1,0,[q_(r),q_(i),q_(c),q_(l),q_(u),q_(d),W(0)])},Fv=e=>K(`av1C`,Wh(e.info.decoderConfig.codec)),Iv=(e,t)=>{let n=0,r,i=16,a=Ph.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=Xh(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),W(1),W(n),W(0),G(0),W(t.info.numberOfChannels),W(i),W(0),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),W(1),W(n),W(0),G(0),W(t.info.numberOfChannels),W(Math.min(i,16)),J_(e),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0),a?[G(1),G(i/8),G(t.info.numberOfChannels*i/8)]:[G(0),G(0),G(0)],G(2)]}return K(e,r,[Oy(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,kv(t)])},Lv=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...q_(t),...q_(21),...Y_(0),...G(e.maxBitrate),...G(e.avgBitrate)];if(e.info.decoderConfig.description){let t=op(e.info.decoderConfig.description);n=[...n,...q_(5),...nv(t.byteLength),...t]}return n=[...W(1),...q_(0),...q_(4),...nv(n.length),...n,...q_(6),...q_(1),...q_(2)],n=[...q_(3),...nv(n.length),...n],av(`esds`,0,0,n)},Rv=e=>K(`wave`,void 0,[zv(e),Bv(e),K(`\0\0\0\0`)]),zv=e=>K(`frma`,[rv(Dy(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),Bv=e=>{let{littleEndian:t}=Xh(e.track.source._codec);return K(`enda`,[W(+t)])},Vv=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=/* @__PURE__ */ new Uint8Array,s=e.info.decoderConfig?.description;if(s){z(s.byteLength>=18);let e=ah(op(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return K(`dOps`,[q_(0),q_(t),W(n),G(r),J_(i),q_(a),...o])},Hv=e=>{let t=e.info.decoderConfig?.description;return z(t),av(`dfLa`,0,0,[...op(t).subarray(4)])},Uv=e=>{let{littleEndian:t,sampleSize:n}=Xh(e.track.source._codec);return av(`pcmC`,0,0,[q_(+t),q_(8*n)])},Wv=e=>{z(e.info.primingPacket);let t=lh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=/* @__PURE__ */ new Uint8Array(3),r=new fm(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),K(`dac3`,[...n])},Gv=e=>{z(e.info.primingPacket);let t=dh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new fm(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return K(`dec3`,[...i])},Kv=e=>{z(e.info.primingPacket);let t=Eh(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return K(`ddts`,[...jh(t)])},qv=(e,t)=>K(e,[[,,,,,,].fill(0),W(1)],[Ay[t.track.source._codec](t),kv(t)]),Jv=e=>K(`vttC`,[...dp.encode(e.info.config.description)]),Yv=e=>av(`stts`,0,0,[G(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[G(e.sampleCount),G(e.sampleDelta)])]),Xv=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return av(`stss`,0,0,[G(t.length),t.map(([e])=>G(e+1))])},Zv=e=>av(`stsc`,0,0,[G(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[G(e.firstChunk),G(e.samplesPerChunk),G(1)])]),Qv=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=Xh(e.track.source._codec);return av(`stsz`,0,0,[G(t*e.info.numberOfChannels),G(e.samples.reduce((t,n)=>t+Uy(n.duration,e.timescale),0))])}return av(`stsz`,0,0,[G(0),G(e.samples.length),e.samples.map(e=>G(e.size))])},$v=e=>e.finalizedChunks.length>0&&np(e.finalizedChunks).offset>=2**32?av(`co64`,0,0,[G(e.finalizedChunks.length),e.finalizedChunks.map(e=>Z_(e.offset))]):av(`stco`,0,0,[G(e.finalizedChunks.length),e.finalizedChunks.map(e=>G(e.offset))]),ey=e=>av(`ctts`,1,0,[G(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[G(e.sampleCount),X_(e.sampleCompositionTimeOffset)])]),ty=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;z(e.compositionTimeOffsetTable.length>0),z(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Uy(n.timestamp,e.timescale)),i=Math.max(i,Uy(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:av(`cslg`,0,0,[X_(a),X_(t),X_(n),X_(r),X_(i)])},ny=e=>K(`mvex`,void 0,e.map(ry)),ry=e=>av(`trex`,0,0,[G(e.track.id),G(1),G(0),G(0),G(0)]),iy=(e,t)=>K(`moof`,void 0,[ay(e),...t.map(sy)]),ay=e=>av(`mfhd`,0,0,[G(e)]),oy=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},sy=e=>K(`traf`,void 0,[cy(e),ly(e),uy(e)]),cy=e=>{z(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:oy(n)};return av(`tfhd`,0,t,[G(e.track.id),G(r.duration),G(r.size),G(r.flags)])},ly=e=>(z(e.currentChunk),av(`tfdt`,1,0,[Z_(Uy(e.currentChunk.startTimestamp,e.timescale))])),uy=e=>{z(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(oy),i=e.currentChunk.samples.map(t=>Uy(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,av(`trun`,1,m,[G(e.currentChunk.samples.length),G(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?G(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?G(t[a]):[],d?G(n[a]):[],f?G(r[a]):[],p?X_(i[a]):[]])])},dy=e=>K(`mfra`,void 0,[...e.map(fy),py()]),fy=e=>av(`tfra`,1,0,[G(e.track.id),G(63),G(e.finalizedChunks.length),e.finalizedChunks.map(t=>[Z_(Uy(t.samples[0].timestamp,e.timescale)),Z_(t.moofOffset),G(t.trafIndex+1),G(1),G(1)])]),py=()=>av(`mfro`,0,0,[G(0)]),my=()=>K(`vtte`),hy=(e,t,n,r,i)=>K(`vttc`,void 0,[i===null?null:K(`vsid`,[X_(i)]),n===null?null:K(`iden`,[...dp.encode(n)]),t===null?null:K(`ctim`,[...dp.encode(W_(t))]),r===null?null:K(`sttg`,[...dp.encode(r)]),K(`payl`,[...dp.encode(e)])]),gy=e=>K(`vtta`,[...dp.encode(e)]),_y=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Sy(r);e&&t.push(e)}else if(n===`mdta`){let e=Cy(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&vy(t,e.output._metadataTags);return t.length===0?null:K(`udta`,void 0,t)},vy=(e,t)=>{for(let{key:n,value:r}of Yp(t))switch(n){case`title`:e.push(yy(`©nam`,r));break;case`description`:e.push(yy(`©des`,r));break;case`artist`:e.push(yy(`©ART`,r));break;case`album`:e.push(yy(`©alb`,r));break;case`albumArtist`:e.push(yy(`albr`,r));break;case`genre`:e.push(yy(`©gen`,r));break;case`date`:e.push(yy(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(yy(`©cmt`,r));break;case`lyrics`:e.push(yy(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:Np(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(yy(n,r)):r instanceof Uint8Array&&e.push(K(n,Array.from(r))))}},yy=(e,t)=>{let n=dp.encode(t);return K(e,[W(n.length),W(jy(`und`)),Array.from(n)])},by={"image/jpeg":13,"image/png":14,"image/bmp":27},xy=(e,t)=>{let n=[];for(let{key:r,value:i}of Yp(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:wy(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:wy(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:wy(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:wy(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:wy(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:wy(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:wy(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:wy(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:wy(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:K(`data`,[G(by[e.mimeType]??0),G(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:wy(t)})}else n.push({key:`trkn`,value:K(`data`,[G(0),G(0),W(0),W(i),W(e.tracksTotal??0),W(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:K(`data`,[G(0),G(0),W(0),W(i),W(e.discsTotal??0),W(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Np(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:wy(i)}):i instanceof Uint8Array?n.push({key:r,value:K(`data`,[G(0),G(0),Array.from(i)])}):i instanceof sm&&n.push({key:r,value:K(`data`,[G(by[i.mimeType]??0),G(0),Array.from(i.data)])}))}return n},Sy=e=>{let t=xy(e,!1);return t.length===0?null:av(`meta`,0,0,void 0,[bv(!1,`mdir`,``,`appl`),K(`ilst`,void 0,t.map(e=>K(e.key,void 0,[e.value])))])},Cy=e=>{let t=xy(e,!0);return t.length===0?null:K(`meta`,void 0,[bv(!1,`mdta`,``),av(`keys`,0,0,[G(t.length)],t.map(e=>K(`mdta`,[...dp.encode(e.key)]))),K(`ilst`,void 0,t.map((e,t)=>K(String.fromCharCode(...G(t+1)),void 0,[e.value])))])},wy=e=>K(`data`,[G(1),G(0),...dp.encode(e)]),Ty=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},Ey={avc:Mv,hevc:Nv,vp8:Pv,vp9:Pv,av1:Fv,prores:null},Dy=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},Oy=(e,t)=>{switch(e){case`aac`:return Lv;case`mp3`:return Lv;case`opus`:return Vv;case`vorbis`:return Lv;case`flac`:return Hv;case`ac3`:return Wv;case`eac3`:return Gv;case`dts`:return Kv}if(t)switch(e){case`pcm-s24`:return Rv;case`pcm-s24be`:return Rv;case`pcm-s32`:return Rv;case`pcm-s32be`:return Rv;case`pcm-f32`:return Rv;case`pcm-f32be`:return Rv;case`pcm-f64`:return Rv;case`pcm-f64be`:return Rv}else switch(e){case`pcm-s16`:return Uv;case`pcm-s16be`:return Uv;case`pcm-s24`:return Uv;case`pcm-s24be`:return Uv;case`pcm-s32`:return Uv;case`pcm-s32be`:return Uv;case`pcm-f32`:return Uv;case`pcm-f32be`:return Uv;case`pcm-f64`:return Uv;case`pcm-f64be`:return Uv}return null},ky={webvtt:`wvtt`},Ay={webvtt:Jv},jy=e=>{z(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},My=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){z(!this.started),this.target._start(),this.started=!0}write(e){z(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return z(this.started&&!this.finalized),this.target._flush()}async finalize(){z(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=/* @__PURE__ */ new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},Ny=class extends rm{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new Ry(this,e)}},Py=2**16,Fy=2**32,Iy=class extends Ny{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in/* @__PURE__ */ new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Py,{maxByteLength:Fy})}catch{this._buffer=new ArrayBuffer(Py),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Py);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Fy)throw Error(`ArrayBuffer exceeded maximum size of ${Fy} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},Ly=class extends Ny{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit(`finalized`)}async _close(){}},Ry=class extends Ny{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},zy=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},By=57600,Vy=2082844800,Hy=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Uy=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Wy=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},Gy=class extends H_{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Iy,this.auxWriter=new My(this.auxTarget,!1),this.auxBoxWriter=new G_(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ap(),this.creationTime=Math.floor(Date.now()/1e3)+Vy,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof tb,this.isCmaf=t instanceof eb,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof eb?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof Iy:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new G_(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Iy&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new My(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new G_(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(z(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(ov({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(z(this.writer),z(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=lv(!0),this.boxWriter.writeBox(this.mdat))}await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return ug({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;rg(n,e.source._codec),z(n),z(n.decoderConfig);let i={...n.decoderConfig};z(i.codedWidth!==void 0),z(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=Mm(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Nm(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=Vm(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=Ym(e),a=!0}let o=Wp(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:tm({num:s*i.codedHeight,den:c*i.codedWidth}),u=i.codec===`ap4h`||i.codec===`ap4x`,d={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a,hasAlphaChannel:u},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ag(n,e.source._codec),z(n),z(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=qg(j_.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=pm[e.samplingFrequencyIndex],r=mm[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=vm({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),a=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Ph.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,primingPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;og(t),z(t),z(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */ new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...Em(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=jm(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=qg(j_.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=Xh(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=Uy(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=Xh(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=/* @__PURE__ */ new Set([]);for(let r of e.cueQueue)z(r.timestamp<=t),z(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=my();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;U_.lastIndex=0;let r=U_.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=gy(n.notes);this.auxBoxWriter.writeBox(e)}let c=hy(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Uy(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){z(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Uy(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=np(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=Uy(r.timestamp-r.decodeTimestamp,e.timescale),a=Uy(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){z(e.lastSample);let t=Uy(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(z(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=np(e.timeToSampleTable);if(z(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=np(e.compositionTimeOffsetTable);z(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Uy(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,z(e.lastSample),z(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){z(t.type===`key`);let n=Uy(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(z(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),z(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(z(!this.isFragmented),z(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Uy(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||np(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)z(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(z(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(z(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;z(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=dv(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){z(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new G_(this.writer);let e=this.boxWriter.measureBox(sv()),t=this.boxWriter.measureBox(cv(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}z(this.writer),z(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=iy(n,t),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e=0;e<t.length;e++){let n=t[e];z(n.currentChunk),z(n.startTimestampOffset!==null),n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e,n.currentChunk.startTimestamp-=n.startTimestampOffset;for(let e of n.currentChunk.samples)o+=e.size,e.timestamp-=n.startTimestampOffset,e.decodeTimestamp-=n.startTimestampOffset;s=Math.min(s,n.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=iy(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}z(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=lv(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){z(this.writer),z(this.boxWriter),this.ensureOneEnabledTrack();let e=dv(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;z(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=lv(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){z(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;z(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){z(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e);let t=Wy(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(z(this.writer),z(this.boxWriter),this.fastStart===`in-memory`){this.mdat=lv(!1);let e;for(let t=0;t<2;t++){let t=dv(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)z(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=dv(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)z(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(sv()),this.boxWriter.writeBox(cv(this,e))}else{let e=this.writer.getPos(),t=dy(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{z(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);z(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=dv(this);if(this.fastStart===`reserve`){z(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(uv(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}},Ky=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},qy=class extends Ky{constructor(e){if(super(),this._connectedTrack=null,!Nh.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${Nh.join(`, `)}.`);this._codec=e}},Jy=class extends Ky{constructor(e){if(super(),this._connectedTrack=null,!Ih.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ih.join(`, `)}.`);this._codec=e}},Yy=class extends Jy{constructor(e){super(e)}add(e,t){if(!(e instanceof lg))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},Xy=class extends Ky{constructor(e){if(super(),this._connectedTrack=null,!Lh.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Lh.join(`, `)}.`);this._codec=e}},Zy=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Nh.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ih.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Lh.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Qy=class extends Zy{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Qp(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new Gy(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},$y=class extends Qy{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Nh,...Fh,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Lh]}_codecUnsupportedHint(e){return new tb().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},eb=class extends Qy{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Nh,...Fh,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Lh]}},tb=class extends Qy{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...Nh,...Ih]}_codecUnsupportedHint(e){return new $y().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},nb=[`video`,`audio`,`subtitle`],rb=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=nm(this.metadata.group),r=nm(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},ib=class extends rb{constructor(e,t,n,r){super(e,t,`video`,n,r)}},ab=class extends rb{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},ob=class extends rb{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},sb=class e{constructor(){this._pairedGroups=/* @__PURE__ */ new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},cb=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Hp(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&dm(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof sb)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof sb))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},lb=class extends rm{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(Jp(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new sb,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=/* @__PURE__ */ new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Cp,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Zy))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Ny||e.target instanceof zy))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Ny&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Ny)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Ny&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){z(this._target instanceof zy);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof Ny))throw TypeError(`getTarget must return a Target.`);return e};return Jp(t)?t.then(n):n(t)}async _getTarget(e){z(this._target instanceof zy);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(z(this._initTarget!==null),this._initTarget instanceof Ny)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Ny)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return Jp(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new My(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof qy))throw TypeError(`source must be a VideoSource.`);if(cb(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.decoderConfig!==void 0&&rg({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof lg))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ib(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Jy))throw TypeError(`source must be an AudioSource.`);if(cb(t),t.decoderConfig!==void 0&&ag({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof lg))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ab(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Xy))throw TypeError(`source must be a SubtitleSource.`);cb(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ob(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(lm(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of nb)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of nb){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(om._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&om._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(om._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,e}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};function ub(e){let t=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);return Uint8Array.from(t)}function db(e,t){return{codec:e.codec,codedWidth:e.codedWidth??t.codedWidth,codedHeight:e.codedHeight??t.codedHeight,description:e.description===void 0?void 0:ub(e.description),colour:t.colour}}function fb(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,description:e.description===void 0?void 0:ub(e.description)}}function pb(e){return{primaries:el(Zc,e?.primaries),transfer:el(Qc,e?.transfer),matrix:el($c,e?.matrix),range:mb(e?.fullRange)}}function mb(e){return e===!0?`full`:e===!1?`limited`:`unspecified`}var hb=[a_,o_],gb=class{async read(e){let t=new D_({formats:hb,source:new $g(e)});try{let[e,n]=await Promise.all([t.getVideoTracks(),t.getAudioTracks()]);return{video:await Promise.all(e.map((e,t)=>_b(e,t))),audio:(await Promise.all(n.map(e=>yb(e)))).flat()}}catch(e){throw bb(e)}finally{t.dispose()}}};async function _b(e,t){let[n,r,i]=await Promise.all([vb(e),e.getCodedWidth(),e.getCodedHeight()]);if(n===null)throw new j(`codec-unsupported`,`video track ${t} has no decoder configuration in its sample entry`);let a={trackIndex:t,codedWidth:r,codedHeight:i,codec:n.codec,colour:pb(n.colorSpace)};return{trackId:e.id,description:a,configuration:db(n,a)}}async function vb(e){try{return await e.getDecoderConfig()}catch{return null}}async function yb(e){let t=await e.getDecoderConfig();return t===null?[]:[{trackId:e.id,configuration:fb(t)}]}function bb(e){return re(e)||e instanceof j?e:new j(`unsupported-container`,`the movie box is not a readable movie`,{cause:e})}var xb=class{capacity;queue=[];roomWaiters=[];takeWaiter;isClosedNow=!1;failure;constructor(e){this.capacity=e}get isClosed(){return this.isClosedNow}push(e){this.isClosedNow||(this.queue.push(e),this.wakeTaker())}waitForRoom(){return this.queue.length<this.capacity||this.isClosedNow?Promise.resolve():new Promise(e=>{this.roomWaiters.push(e)})}close(){this.isClosedNow=!0,this.wakeTaker(),this.wakeRoomWaiters()}fail(e){this.failure??=e instanceof Error?e:new j(`decode`,`audio re-packaging failed`,{cause:e}),this.close()}segments(e=Cb){return new Sb({take:()=>this.take(),close:()=>{this.close()},onEnd:e})}async take(){for(;this.queue.length===0&&!this.isClosedNow;)await this.nextPush();let e=this.queue.shift();if(e)return this.wakeRoomWaiters(),e;if(this.failure)throw this.failure}nextPush(){return N(this.takeWaiter===void 0,`a segment channel has one consumer`),new Promise(e=>{this.takeWaiter=e})}wakeTaker(){let e=this.takeWaiter;this.takeWaiter=void 0,e?.()}wakeRoomWaiters(){if(this.queue.length>=this.capacity&&!this.isClosedNow)return;let e=this.roomWaiters;this.roomWaiters=[];for(let t of e)t()}},Sb=class{parts;hasEnded=!1;constructor(e){this.parts=e}async next(){if(this.hasEnded)return yl;try{let e=await this.parts.take();return e===void 0||this.wasEnded()?this.end():{done:!1,value:e}}catch(e){throw this.end(),e}}return(){return this.parts.close(),Promise.resolve(this.end())}[Symbol.asyncIterator](){return this}wasEnded(){return this.hasEnded}end(){return this.hasEnded||this.parts.onEnd(),this.hasEnded=!0,yl}};function Cb(){}var wb=1,Tb=2,Eb=`mp4a.40.`,Db=`aac`,Ob=class{segmentsOf(e,t){let n=kb(t);return{mimeType:`audio/mp4; codecs="${t.codec}"`,duration:e.duration,segmentsFrom:r=>({[Symbol.asyncIterator]:()=>Ab({samples:e,configuration:t,codec:n},r)})}}};function kb(e){if(e.codec.startsWith(Eb))return Db;throw new j(`codec-unsupported`,`audio in ${e.codec} cannot be re-packaged for playback`)}function Ab(e,t){let n=new xb(Tb),r=new lb({format:Fb(n),target:new Ly}),i=new Yy(e.codec);r.addAudioTrack(i);let a=e.samples.samplesFrom(t)[Symbol.asyncIterator](),o=Mb({samples:a,configuration:e.configuration,output:r,source:i,channel:n});return n.segments(()=>{a.return?.(),jb(o,r)})}async function jb(e,t){if(await e,t.state!==`finalized`)try{await t.cancel()}catch{}}async function Mb(e){try{await e.output.start();let t={decoderConfig:Pb(e.configuration)};for(let n=await e.samples.next();n.done!==!0;n=await e.samples.next()){if(await e.channel.waitForRoom(),e.channel.isClosed)return;await e.source.add(Nb(n.value),t),t=void 0}if(e.channel.isClosed)return;await e.output.finalize(),e.channel.close()}catch(t){e.channel.fail(t)}}function Nb(e){return new lg(e.data,`key`,e.timestamp,e.duration)}function Pb(e){return{codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,...e.description&&{description:e.description}}}function Fb(e){let t=new Ib(e);return new $y({fastStart:`fragmented`,minimumFragmentDuration:wb,onFtyp:e=>{t.begin(e)},onMoov:e=>{t.end(e)},onMoof:e=>{t.begin(e)},onMdat:e=>{t.end(e)}})}var Ib=class{channel;opening;constructor(e){this.channel=e}begin(e){N(this.opening===void 0,`a segment began before the last one ended`),this.opening=new Uint8Array(e)}end(e){let{opening:t}=this;N(t!==void 0,`a segment ended that never began`);let n=new Uint8Array(t.byteLength+e.byteLength);n.set(t),n.set(e,t.byteLength),this.opening=void 0,this.channel.push(n)}};function Lb(e){let t=e.range===`unspecified`?void 0:{fullRange:e.range===`full`},n={...e.primaries!==`unspecified`&&{primaries:e.primaries},...e.transfer!==`unspecified`&&{transfer:e.transfer},...e.matrix!==`unspecified`&&{matrix:e.matrix},...t};return Object.keys(n).length===0?void 0:Rb(n)??t}function Rb(e){try{return new VideoColorSpace(e).toJSON()}catch{return}}var zb=`no-preference`,Bb=class{async isSupported(e){if(typeof VideoDecoder>`u`)throw Hb();try{return(await VideoDecoder.isConfigSupported(this.toWebCodecsConfig(e))).supported===!0}catch{return!1}}create(e,t){try{return Promise.resolve(this.configureDecoder(e,t))}catch(e){return Promise.reject(ne(e,`codec-unsupported`,`the decoder rejected its configuration`))}}configureDecoder(e,t){if(typeof VideoDecoder>`u`)throw Hb();return new Vb(this.toWebCodecsConfig(e),t)}toWebCodecsConfig(e){let{description:t}=e,n=Lb(e.colour);return{codec:e.codec,codedWidth:e.codedWidth,codedHeight:e.codedHeight,...t&&{description:t},...n&&{colorSpace:n},hardwareAcceleration:zb,optimizeForLatency:!1}}},Vb=class{decoder;failure;constructor(e,t){this.decoder=new VideoDecoder({output:e=>{t.onFrame(Wb(e))},error:e=>{this.failure??=new j(`decode`,`video decoder failed: ${e.message}`,{cause:e}),t.onError(this.failure)}});try{this.decoder.configure(e)}catch(e){throw this.decoder.close(),e}}get pendingCount(){return this.decoder.decodeQueueSize}decode(e){if(this.failure)throw this.failure;try{this.decoder.decode(Ub(e))}catch(e){throw new j(`decode`,`the decoder refused a packet: ${ie(e)}`,{cause:e})}}waitForPendingBelow(e){return this.decoder.decodeQueueSize<e?Promise.resolve():new Promise(t=>{let n=()=>{this.decoder.decodeQueueSize>=e&&this.decoder.state===`configured`||(this.decoder.removeEventListener(`dequeue`,n),t())};this.decoder.addEventListener(`dequeue`,n)})}async flush(){if(this.decoder.state!==`configured`)throw this.failure??new j(`decode`,`flush on a closed decoder`);try{await this.decoder.flush()}catch(e){throw this.failure??new j(`decode`,`the decoder could not be flushed`,{cause:e})}}close(){this.decoder.state!==`closed`&&this.decoder.close()}};function Hb(){return new j(`webcodecs-unavailable`,globalThis.isSecureContext?`this browser has no WebCodecs VideoDecoder`:`WebCodecs exists only in secure contexts (HTTPS), and this page is not one`)}function Ub(e){return new EncodedVideoChunk({type:e.isKeyFrame?`key`:`delta`,timestamp:_t(e.timestamp),duration:_t(e.duration),data:e.data})}function Wb(e){return{timestamp:mt(ft(e.timestamp)),handle:e,close:()=>{e.close()}}}function Gb(e){return`url`in e}function Kb(e){return Gb(e)?ia(e.url):e.name}var qb=15e3;function Jb(e={}){let t=e.http??{},n=e.probeTimeoutMs??qb;return{sources:Yb(t),codecReader:new gb,audioPackager:new Ob,decoderPort:new Bb,locatorFor:e=>new Wf(Qb(t,e)),probeDeadline:()=>$b(n)}}function Yb(e){return{open:(t,n)=>Gb(t)?Xb(t,e,n):Zb(t)}}function Xb(e,t,n){let r=new Bf(e.url,Qb(t,e),n);return{source:new pf(r),stream:new df(r)}}function Zb(e){let t=new $d(e.blob);return{source:t,stream:new xl(t)}}function Qb(e,t){let{credentials:n}=t;return n===void 0?e:{...e,requestInit:{...e.requestInit,credentials:n}}}function $b(e){let t=new Ou;return setTimeout(()=>{t.resolve()},e),t}function ex(e,t,n){let r=new AbortController;return n?.addEventListener(`abort`,()=>{r.abort()},{once:!0,signal:r.signal}),new Promise(n=>{for(let i of t)e.addEventListener(i,()=>{r.abort(),n(i)},{once:!0,signal:r.signal})})}var tx=`ManagedMediaSource`,nx=`MediaSource`;function rx(e){return typeof e==`function`&&typeof e.isTypeSupported==`function`}function ix(e){let t=Reflect.get(globalThis,e);return rx(t)?t:void 0}function ax(){return ix(tx)??ix(nx)}function ox(e){return ax()?.isTypeSupported(e)??!1}var sx=1e4;async function cx(e,t){let n=new t,r=lx(e,n),i=URL.createObjectURL(n);e.disableRemotePlayback=!0,e.src=i;let a={mediaSource:n,detach:()=>{e.src===i&&(e.removeAttribute(`src`),e.load()),URL.revokeObjectURL(i)}},o=await r;if(o!==`sourceopen`)throw a.detach(),new j(`decode`,`the audio element could not open its media source (${o})`);return a}async function lx(e,t){let n=new AbortController;try{return await Promise.race([ex(t,[`sourceopen`],n.signal),ex(e,[`error`],n.signal),ux(sx,n.signal)])}finally{n.abort()}}function ux(e,t){return new Promise(n=>{let r=setTimeout(()=>{n(`timeout`)},e);t.addEventListener(`abort`,()=>{clearTimeout(r)},{once:!0})})}var dx=30,fx=30,px=60,mx=1,hx=[`timeupdate`,`seeking`,`waiting`,`play`],gx=class{parts;stop=new Au;run=Promise.resolve();failureValue;constructor(e){this.parts=e}get failure(){return this.failureValue}restartFrom(e){this.stop.stop();let t=new Au;this.stop=t,this.run=this.feedAfter(this.run,e,t)}dispose(){this.stop.stop()}async feedAfter(e,t,n){await e,await this.feed(t,n)}async feed(e,t){try{if(await this.settlePendingAppend(),t.wasStopped||this.hasElementFailed()||this.hasAllAudioFrom(e))return;await this.feedFrom(this.startOf(e),t)}catch(e){this.failureValue??=ne(e,`decode`,`feeding the audio buffer failed`)}}async feedFrom(e,t){let n=this.parts.source.segmentsFrom(e)[Symbol.asyncIterator]();try{await this.pump(n,t)&&this.endStream()}finally{n.return?.()}}hasAllAudioFrom(e){let{buffered:t}=this.parts.element,n=this.bufferedEndAt(e);return this.parts.mediaSource.readyState===`ended`&&n>e&&n===t.end(t.length-1)}startOf(e){let t=this.bufferedEndAt(e);return R(t>e?t:Math.max(0,e-mx))}async pump(e,t){let n=await this.nextWhenNeeded(e,t);for(;n!==ku;){if(n.done===!0)return!0;if(this.hasElementFailed())return!1;this.evictBehind(),await this.append(n.value),n=await this.nextWhenNeeded(e,t)}return!1}async nextWhenNeeded(e,t){return await this.waitUntilNeeded(t),t.race(()=>e.next())}async waitUntilNeeded(e){for(;!e.wasStopped&&this.bufferedAhead()>=dx;){let t=new AbortController;await e.race(()=>ex(this.parts.element,hx,t.signal)),t.abort()}}bufferedAhead(){let{currentTime:e}=this.parts.element;return R(this.bufferedEndAt(e)-e)}bufferedEndAt(e){let{buffered:t}=this.parts.element;for(let n=0;n<t.length;n+=1)if(t.start(n)<=e&&e<t.end(n))return t.end(n);return e}evictBehind(){let{buffered:e,currentTime:t}=this.parts.element;t-(e.length>0?e.start(0):t)<px||this.parts.sourceBuffer.updating||this.parts.sourceBuffer.remove(0,t-fx)}async append(e){let{sourceBuffer:t}=this.parts;await this.settlePendingAppend();let n=ex(t,[`updateend`,`error`]);try{t.appendBuffer(e)}catch(e){throw new j(`decode`,`the audio buffer rejected a segment`,{cause:e})}if(await n===`error`)throw new j(`decode`,`the audio buffer could not parse a segment`)}hasElementFailed(){return this.parts.element.error!==null}async settlePendingAppend(){this.parts.sourceBuffer.updating&&await ex(this.parts.sourceBuffer,[`updateend`])}endStream(){let{mediaSource:e,sourceBuffer:t}=this.parts;e.readyState===`open`&&!t.updating&&e.endOfStream()}},_x=class e{element;feeder;attached;standingEnd;constructor(e,t,n){this.element=e,this.feeder=t,this.attached=n}static isSupported(e){return ox(e.mimeType)}static async open(t,n){let r=ax();if(!r?.isTypeSupported(n.mimeType))throw new j(`codec-unsupported`,`${n.mimeType} cannot play through Media Source Extensions here`);let i=await cx(t,r);try{let r=i.mediaSource.addSourceBuffer(n.mimeType);i.mediaSource.duration=n.duration;let a=new gx({element:t,mediaSource:i.mediaSource,sourceBuffer:r,source:n});return a.restartFrom(R(0)),new e(t,a,i)}catch(e){throw i.detach(),bx(e)}}get currentTime(){return this.standingEnd??R(this.element.currentTime)}get isRunning(){return!this.element.paused}get hasEnded(){return this.standingEnd!==void 0||this.element.ended}get failure(){return this.feeder.failure??yx(this.element)}async start(){if(!this.hasEnded)try{await this.element.play()}catch(e){if(re(e))return;let t=vx(e,`NotAllowedError`);throw new j(t?`playback-blocked`:`decode`,t?`the browser refused to start audio playback; a user gesture is needed`:`audio playback failed to start`,{cause:e})}}pause(){this.element.pause()}seek(e){let t=this.attached.mediaSource.duration;if(e>=t){this.standAtEnd(R(t));return}this.standingEnd=void 0,this.element.currentTime=e,this.feeder.restartFrom(e)}dispose(){this.feeder.dispose(),this.element.pause(),this.attached.detach()}standAtEnd(e){this.element.pause(),this.standingEnd=e}};function vx(e,t){return e instanceof Error&&e.name===t}function yx(e){let{error:t}=e;return t===null?void 0:new j(`decode`,`the audio element failed (media error ${t.code})`,{cause:t})}function bx(e){return e instanceof j?e:new j(vx(e,`NotSupportedError`)?`codec-unsupported`:`decode`,`the audio element refused the recording's sound: ${ie(e)}`,{cause:e})}var xx=1e3,Sx=1001,Cx=1002,wx=1003,Tx=1004,Ex=1005,Dx=1006,Ox=1007,kx=1008,Ax=1009,jx=1010,Mx=1011,Nx=1012,Px=1013,Fx=1014,Ix=1015,Lx=1016,Rx=1017,zx=1018,Bx=1020,Vx=35902,Hx=35899,Ux=1021,Wx=1022,Gx=1023,Kx=1026,qx=1027,Jx=1028,Yx=1029,Xx=1030,Zx=1031,Qx=1033,$x=33776,eS=33777,tS=33778,nS=33779,rS=35840,iS=35841,aS=35842,oS=35843,sS=36196,cS=37492,lS=37496,uS=37488,dS=37489,fS=37490,pS=37491,mS=37808,hS=37809,gS=37810,_S=37811,vS=37812,yS=37813,bS=37814,xS=37815,SS=37816,CS=37817,wS=37818,TS=37819,ES=37820,DS=37821,OS=36492,kS=36494,AS=36495,jS=36283,MS=36284,NS=36285,PS=36286,FS=2300,IS=2301,LS=2302,RS=2303,zS=2400,BS=2401,VS=2402,HS=3200,US=`srgb`,WS=`srgb-linear`,GS=`linear`,KS=`srgb`,qS=7680,JS=35044,YS=`300 es`,XS=2e3;function ZS(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function QS(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function $S(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function eC(){let e=$S(`canvas`);return e.style.display=`block`,e}var tC={};function nC(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function rC(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function q(...e){e=rC(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function J(...e){e=rC(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function iC(...e){let t=e.join(` `);t in tC||(tC[t]=!0,q(...e))}function aC(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var oC={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},sC=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},cC=/* @__PURE__ */ `00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),lC=Math.PI/180,uC=180/Math.PI;function dC(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(cC[e&255]+cC[e>>8&255]+cC[e>>16&255]+cC[e>>24&255]+`-`+cC[t&255]+cC[t>>8&255]+`-`+cC[t>>16&15|64]+cC[t>>24&255]+`-`+cC[n&63|128]+cC[n>>8&255]+`-`+cC[n>>16&255]+cC[n>>24&255]+cC[r&255]+cC[r>>8&255]+cC[r>>16&255]+cC[r>>24&255]).toLowerCase()}function fC(e,t,n){return Math.max(t,Math.min(n,e))}function pC(e,t){return(e%t+t)%t}function mC(e,t,n){return(1-n)*e+n*t}function hC(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}function gC(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}var Y=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`THREE.Vector2: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`THREE.Vector2: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=fC(this.x,e.x,t.x),this.y=fC(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=fC(this.x,e,t),this.y=fC(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(fC(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(fC(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},_C=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:q(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(fC(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},X=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`THREE.Vector3: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`THREE.Vector3: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(yC.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(yC.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=fC(this.x,e.x,t.x),this.y=fC(this.y,e.y,t.y),this.z=fC(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=fC(this.x,e,t),this.y=fC(this.y,e,t),this.z=fC(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(fC(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return vC.copy(this).projectOnVector(e),this.sub(vC)}reflect(e){return this.sub(vC.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(fC(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},vC=/*@__PURE__*/ new X,yC=/*@__PURE__*/ new _C,Z=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return iC(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(bC.makeScale(e,t)),this}rotate(e){return iC(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(bC.makeRotation(-e)),this}translate(e,t){return iC(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(bC.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},bC=/*@__PURE__*/ new Z,xC=/*@__PURE__*/ new Z().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),SC=/*@__PURE__*/ new Z().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function CC(){let e={enabled:!0,workingColorSpace:WS,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=TC(e.r),e.g=TC(e.g),e.b=TC(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=EC(e.r),e.g=EC(e.g),e.b=EC(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?GS:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return iC(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return iC(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[WS]:{primaries:t,whitePoint:r,transfer:GS,toXYZ:xC,fromXYZ:SC,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:US},outputColorSpaceConfig:{drawingBufferColorSpace:US}},[US]:{primaries:t,whitePoint:r,transfer:KS,toXYZ:xC,fromXYZ:SC,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:US}}}),e}var wC=/*@__PURE__*/ CC();function TC(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function EC(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var DC,OC=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{DC===void 0&&(DC=$S(`canvas`)),DC.width=e.width,DC.height=e.height;let t=DC.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=DC}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=$S(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=TC(i[e]/255)*255;return n.putImageData(r,0,0),t}if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(TC(t[e]/255)*255):t[e]=TC(t[e]);return{data:t,width:e.width,height:e.height}}return q(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},kC=0,AC=class{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:kC++}),this.uuid=dC(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<`u`&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(jC(r[t].image)):e.push(jC(r[t]))}else e=jC(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function jC(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?OC.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(q(`Texture: Unable to serialize Texture.`),{})}var MC=0,NC=/*@__PURE__*/ new X,PC=class e extends sC{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=Sx,i=Sx,a=Dx,o=kx,s=Gx,c=Ax,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:MC++}),this.uuid=dC(),this.name=``,this.source=new AC(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new Y(0,0),this.repeat=new Y(1,1),this.center=new Y(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Z,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(NC).x}get height(){return this.source.getSize(NC).y}get depth(){return this.source.getSize(NC).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){q(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){q(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case xx:e.x-=Math.floor(e.x);break;case Sx:e.x=e.x<0?0:1;break;case Cx:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case xx:e.y-=Math.floor(e.y);break;case Sx:e.y=e.y<0?0:1;break;case Cx:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};PC.DEFAULT_IMAGE=null,PC.DEFAULT_MAPPING=300,PC.DEFAULT_ANISOTROPY=1;var FC=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`THREE.Vector4: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`THREE.Vector4: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=fC(this.x,e.x,t.x),this.y=fC(this.y,e.y,t.y),this.z=fC(this.z,e.z,t.z),this.w=fC(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=fC(this.x,e,t),this.y=fC(this.y,e,t),this.z=fC(this.z,e,t),this.w=fC(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(fC(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},IC=class extends sC{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Dx,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new FC(0,0,e,t),this.scissorTest=!1,this.viewport=new FC(0,0,e,t),this.textures=[];let r=new PC({width:e,height:t,depth:n.depth}),i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:Dx,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),e!==null&&e.renderTarget===null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new AC(n)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null){if(e.depthTexture.renderTarget===e){let t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture}return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:`dispose`})}},LC=class extends IC{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},RC=class extends PC{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=wx,this.minFilter=wx,this.wrapR=Sx,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=/* @__PURE__ */ new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},zC=class extends PC{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=wx,this.minFilter=wx,this.wrapR=Sx,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}},BC=class e{static{e.prototype.isMatrix4=!0}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,r=1/VC.setFromMatrixColumn(e,0).length(),i=1/VC.setFromMatrixColumn(e,1).length(),a=1/VC.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(UC,e,WC)}lookAt(e,t,n){let r=this.elements;return qC.subVectors(e,t),qC.lengthSq()===0&&(qC.z=1),qC.normalize(),GC.crossVectors(n,qC),GC.lengthSq()===0&&(Math.abs(n.z)===1?qC.x+=1e-4:qC.z+=1e-4,qC.normalize(),GC.crossVectors(n,qC)),GC.normalize(),KC.crossVectors(qC,GC),r[0]=GC.x,r[4]=KC.x,r[8]=qC.x,r[1]=GC.y,r[5]=KC.y,r[9]=qC.y,r[2]=GC.z,r[6]=KC.z,r[10]=qC.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],A=r[6],ee=r[10],te=r[14],j=r[3],ne=r[7],re=r[11],M=r[15];return i[0]=a*x+o*T+s*k+c*j,i[4]=a*S+o*E+s*A+c*ne,i[8]=a*C+o*D+s*ee+c*re,i[12]=a*w+o*O+s*te+c*M,i[1]=l*x+u*T+d*k+f*j,i[5]=l*S+u*E+d*A+f*ne,i[9]=l*C+u*D+d*ee+f*re,i[13]=l*w+u*O+d*te+f*M,i[2]=p*x+m*T+h*k+g*j,i[6]=p*S+m*E+h*A+g*ne,i[10]=p*C+m*D+h*ee+g*re,i[14]=p*w+m*O+h*te+g*M,i[3]=_*x+v*T+y*k+b*j,i[7]=_*S+v*E+y*A+b*ne,i[11]=_*C+v*D+y*ee+b*re,i[15]=_*w+v*O+y*te+b*M,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15],_=s*f-c*d,v=o*f-c*u,y=o*d-s*u,b=a*f-c*l,x=a*d-s*l,S=a*u-o*l;return t*(m*_-h*v+g*y)-n*(p*_-h*b+g*x)+r*(p*v-m*b+g*S)-i*(p*y-m*x+h*S)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[1],a=e[5],o=e[9],s=e[2],c=e[6],l=e[10];return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=t*o-n*a,v=t*s-r*a,y=t*c-i*a,b=n*s-r*o,x=n*c-i*o,S=r*c-i*s,C=l*m-u*p,w=l*h-d*p,T=l*g-f*p,E=u*h-d*m,D=u*g-f*m,O=d*g-f*h,k=_*O-v*D+y*E+b*T-x*w+S*C;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let A=1/k;return e[0]=(o*O-s*D+c*E)*A,e[1]=(r*D-n*O-i*E)*A,e[2]=(m*S-h*x+g*b)*A,e[3]=(d*x-u*S-f*b)*A,e[4]=(s*T-a*O-c*w)*A,e[5]=(t*O-r*T+i*w)*A,e[6]=(h*y-p*S-g*v)*A,e[7]=(l*S-d*y+f*v)*A,e[8]=(a*D-o*T+c*C)*A,e[9]=(n*T-t*D-i*C)*A,e[10]=(p*x-m*y+g*_)*A,e[11]=(u*y-l*x-f*_)*A,e[12]=(o*w-a*E-s*C)*A,e[13]=(t*E-n*w+r*C)*A,e[14]=(m*v-p*b-h*_)*A,e[15]=(l*b-u*v+d*_)*A,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let i=this.determinantAffine();if(i===0)return n.set(1,1,1),t.identity(),this;let a=VC.set(r[0],r[1],r[2]).length(),o=VC.set(r[4],r[5],r[6]).length(),s=VC.set(r[8],r[9],r[10]).length();i<0&&(a=-a),HC.copy(this);let c=1/a,l=1/o,u=1/s;return HC.elements[0]*=c,HC.elements[1]*=c,HC.elements[2]*=c,HC.elements[4]*=l,HC.elements[5]*=l,HC.elements[6]*=l,HC.elements[8]*=u,HC.elements[9]*=u,HC.elements[10]*=u,t.setFromRotationMatrix(HC),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=XS,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=XS,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},VC=/*@__PURE__*/ new X,HC=/*@__PURE__*/ new BC,UC=/*@__PURE__*/ new X(0,0,0),WC=/*@__PURE__*/ new X(1,1,1),GC=/*@__PURE__*/ new X,KC=/*@__PURE__*/ new X,qC=/*@__PURE__*/ new X,JC=/*@__PURE__*/ new BC,YC=/*@__PURE__*/ new _C,XC=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(fC(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-fC(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(fC(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-fC(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(fC(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-fC(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:q(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return JC.makeRotationFromQuaternion(e),this.setFromRotationMatrix(JC,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return YC.setFromEuler(this),this.setFromQuaternion(YC,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};XC.DEFAULT_ORDER=`XYZ`;var ZC=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return!!(this.mask&(1<<e|0))}},QC=0,$C=/*@__PURE__*/ new X,ew=/*@__PURE__*/ new _C,tw=/*@__PURE__*/ new BC,nw=/*@__PURE__*/ new X,rw=/*@__PURE__*/ new X,iw=/*@__PURE__*/ new X,aw=/*@__PURE__*/ new _C,ow=/*@__PURE__*/ new X(1,0,0),sw=/*@__PURE__*/ new X(0,1,0),cw=/*@__PURE__*/ new X(0,0,1),lw={type:`added`},uw={type:`removed`},dw={type:`childadded`,child:null},fw={type:`childremoved`,child:null},pw=class e extends sC{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:QC++}),this.uuid=dC(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new X,n=new XC,r=new _C,i=new X(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new BC},normalMatrix:{value:new Z}}),this.matrix=new BC,this.matrixWorld=new BC,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ZC,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return ew.setFromAxisAngle(e,t),this.quaternion.multiply(ew),this}rotateOnWorldAxis(e,t){return ew.setFromAxisAngle(e,t),this.quaternion.premultiply(ew),this}rotateX(e){return this.rotateOnAxis(ow,e)}rotateY(e){return this.rotateOnAxis(sw,e)}rotateZ(e){return this.rotateOnAxis(cw,e)}translateOnAxis(e,t){return $C.copy(e).applyQuaternion(this.quaternion),this.position.add($C.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(ow,e)}translateY(e){return this.translateOnAxis(sw,e)}translateZ(e){return this.translateOnAxis(cw,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(tw.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?nw.copy(e):nw.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),rw.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?tw.lookAt(rw,nw,this.up):tw.lookAt(nw,rw,this.up),this.quaternion.setFromRotationMatrix(tw),r&&(tw.extractRotation(r.matrixWorld),ew.setFromRotationMatrix(tw),this.quaternion.premultiply(ew.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(J(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(lw),dw.child=e,this.dispatchEvent(dw),dw.child=null):J(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(uw),fw.child=e,this.dispatchEvent(fw),fw.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),tw.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),tw.multiply(e.parent.matrixWorld)),e.applyMatrix4(tw),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(lw),dw.child=e,this.dispatchEvent(dw),dw.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rw,e,iw),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rw,aw,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,i=this.matrix.elements;i[12]+=t-i[0]*t-i[4]*n-i[8]*r,i[13]+=n-i[1]*t-i[5]*n-i[9]*r,i[14]+=r-i[2]*t-i[6]*n-i[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let r=this.parent;if(e===!0&&r!==null&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),t===!0){let e=this.children;for(let t=0,r=e.length;t<r;t++)e[t].updateWorldMatrix(!1,!0,n)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,r.name=this.name,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,r.visible=this.visible,r.frustumCulled=this.frustumCulled,r.renderOrder=this.renderOrder,r.static=this.static,r.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0){if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material)}if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}dispose(){this.dispatchEvent({type:`dispose`})}};pw.DEFAULT_UP=/*@__PURE__*/ new X(0,1,0),pw.DEFAULT_MATRIX_AUTO_UPDATE=!0,pw.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var mw=class extends pw{constructor(){super(),this.isGroup=!0,this.type=`Group`}},hw={type:`move`},gw=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new mw,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new mw,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new X,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new X),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new mw,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new X,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new X,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position);c.inputState.pinching&&o>.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(hw)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new mw;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},_w={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},vw={h:0,s:0,l:0},yw={h:0,s:0,l:0};function bw(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var xw=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=US){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,wC.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=wC.workingColorSpace){return this.r=e,this.g=t,this.b=n,wC.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=wC.workingColorSpace){if(e=pC(e,1),t=fC(t,0,1),n=fC(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=bw(i,r,e+1/3),this.g=bw(i,r,e),this.b=bw(i,r,e-1/3)}return wC.colorSpaceToWorking(this,r),this}setStyle(e,t=US){function n(t){t!==void 0&&parseFloat(t)<1&&q(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:q(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);q(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=US){let n=_w[e.toLowerCase()];return n===void 0?q(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=TC(e.r),this.g=TC(e.g),this.b=TC(e.b),this}copyLinearToSRGB(e){return this.r=EC(e.r),this.g=EC(e.g),this.b=EC(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=US){return wC.workingToColorSpace(Sw.copy(this),e),Math.round(fC(Sw.r*255,0,255))*65536+Math.round(fC(Sw.g*255,0,255))*256+Math.round(fC(Sw.b*255,0,255))}getHexString(e=US){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=wC.workingColorSpace){wC.workingToColorSpace(Sw.copy(this),t);let n=Sw.r,r=Sw.g,i=Sw.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=wC.workingColorSpace){return wC.workingToColorSpace(Sw.copy(this),t),e.r=Sw.r,e.g=Sw.g,e.b=Sw.b,e}getStyle(e=US){wC.workingToColorSpace(Sw.copy(this),e);let t=Sw.r,n=Sw.g,r=Sw.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(vw),this.setHSL(vw.h+e,vw.s+t,vw.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(vw),e.getHSL(yw);let n=mC(vw.h,yw.h,t),r=mC(vw.s,yw.s,t),i=mC(vw.l,yw.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Sw=/*@__PURE__*/ new xw;xw.NAMES=_w;var Cw=class extends pw{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new XC,this.environmentIntensity=1,this.environmentRotation=new XC,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}},ww=/*@__PURE__*/ new X,Tw=/*@__PURE__*/ new X,Ew=/*@__PURE__*/ new X,Dw=/*@__PURE__*/ new X,Ow=/*@__PURE__*/ new X,kw=/*@__PURE__*/ new X,Aw=/*@__PURE__*/ new X,jw=/*@__PURE__*/ new X,Mw=/*@__PURE__*/ new X,Nw=/*@__PURE__*/ new X,Pw=/*@__PURE__*/ new FC,Fw=/*@__PURE__*/ new FC,Iw=/*@__PURE__*/ new FC,Lw=class e{constructor(e=new X,t=new X,n=new X){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),ww.subVectors(e,t),r.cross(ww);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){ww.subVectors(r,t),Tw.subVectors(n,t),Ew.subVectors(e,t);let a=ww.dot(ww),o=ww.dot(Tw),s=ww.dot(Ew),c=Tw.dot(Tw),l=Tw.dot(Ew),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Dw)!==null&&Dw.x>=0&&Dw.y>=0&&Dw.x+Dw.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Dw)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Dw.x),s.addScaledVector(a,Dw.y),s.addScaledVector(o,Dw.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Pw.setScalar(0),Fw.setScalar(0),Iw.setScalar(0),Pw.fromBufferAttribute(e,t),Fw.fromBufferAttribute(e,n),Iw.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Pw,i.x),a.addScaledVector(Fw,i.y),a.addScaledVector(Iw,i.z),a}static isFrontFacing(e,t,n,r){return ww.subVectors(n,t),Tw.subVectors(e,t),ww.cross(Tw).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return ww.subVectors(this.c,this.b),Tw.subVectors(this.a,this.b),ww.cross(Tw).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Ow.subVectors(r,n),kw.subVectors(i,n),jw.subVectors(e,n);let s=Ow.dot(jw),c=kw.dot(jw);if(s<=0&&c<=0)return t.copy(n);Mw.subVectors(e,r);let l=Ow.dot(Mw),u=kw.dot(Mw);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Ow,a);Nw.subVectors(e,i);let f=Ow.dot(Nw),p=kw.dot(Nw);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(kw,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Aw.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Aw,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Ow,a).addScaledVector(kw,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Rw=class{constructor(e=new X(1/0,1/0,1/0),t=new X(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Bw.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Bw.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Bw.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,Bw):Bw.fromBufferAttribute(r,t),Bw.applyMatrix4(e.matrixWorld),this.expandByPoint(Bw);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Vw.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Vw.copy(e.boundingBox)),Vw.applyMatrix4(e.matrixWorld),this.union(Vw)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Bw),Bw.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Jw),Yw.subVectors(this.max,Jw),Hw.subVectors(e.a,Jw),Uw.subVectors(e.b,Jw),Ww.subVectors(e.c,Jw),Gw.subVectors(Uw,Hw),Kw.subVectors(Ww,Uw),qw.subVectors(Hw,Ww);let t=[0,-Gw.z,Gw.y,0,-Kw.z,Kw.y,0,-qw.z,qw.y,Gw.z,0,-Gw.x,Kw.z,0,-Kw.x,qw.z,0,-qw.x,-Gw.y,Gw.x,0,-Kw.y,Kw.x,0,-qw.y,qw.x,0];return!Qw(t,Hw,Uw,Ww,Yw)||(t=[1,0,0,0,1,0,0,0,1],!Qw(t,Hw,Uw,Ww,Yw))?!1:(Xw.crossVectors(Gw,Kw),t=[Xw.x,Xw.y,Xw.z],Qw(t,Hw,Uw,Ww,Yw))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Bw).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Bw).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(zw[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),zw[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),zw[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),zw[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),zw[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),zw[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),zw[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),zw[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(zw),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},zw=[/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X,/*@__PURE__*/ new X],Bw=/*@__PURE__*/ new X,Vw=/*@__PURE__*/ new Rw,Hw=/*@__PURE__*/ new X,Uw=/*@__PURE__*/ new X,Ww=/*@__PURE__*/ new X,Gw=/*@__PURE__*/ new X,Kw=/*@__PURE__*/ new X,qw=/*@__PURE__*/ new X,Jw=/*@__PURE__*/ new X,Yw=/*@__PURE__*/ new X,Xw=/*@__PURE__*/ new X,Zw=/*@__PURE__*/ new X;function Qw(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Zw.fromArray(e,a);let o=i.x*Math.abs(Zw.x)+i.y*Math.abs(Zw.y)+i.z*Math.abs(Zw.z),s=t.dot(Zw),c=n.dot(Zw),l=r.dot(Zw);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var $w=/*@__PURE__*/ new X,eT=/*@__PURE__*/ new Y,tT=0,nT=class extends sC{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:tT++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=JS,this.updateRanges=[],this.gpuType=Ix,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)eT.fromBufferAttribute(this,t),eT.applyMatrix3(e),this.setXY(t,eT.x,eT.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)$w.fromBufferAttribute(this,t),$w.applyMatrix3(e),this.setXYZ(t,$w.x,$w.y,$w.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)$w.fromBufferAttribute(this,t),$w.applyMatrix4(e),this.setXYZ(t,$w.x,$w.y,$w.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)$w.fromBufferAttribute(this,t),$w.applyNormalMatrix(e),this.setXYZ(t,$w.x,$w.y,$w.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)$w.fromBufferAttribute(this,t),$w.transformDirection(e),this.setXYZ(t,$w.x,$w.y,$w.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=hC(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=gC(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=hC(t,this.array)),t}setX(e,t){return this.normalized&&(t=gC(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=hC(t,this.array)),t}setY(e,t){return this.normalized&&(t=gC(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=hC(t,this.array)),t}setZ(e,t){return this.normalized&&(t=gC(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=hC(t,this.array)),t}setW(e,t){return this.normalized&&(t=gC(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=gC(t,this.array),n=gC(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=gC(t,this.array),n=gC(n,this.array),r=gC(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=gC(t,this.array),n=gC(n,this.array),r=gC(r,this.array),i=gC(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:`dispose`})}},rT=class extends nT{constructor(e,t,n){super(new Uint16Array(e),t,n)}},iT=class extends nT{constructor(e,t,n){super(new Uint32Array(e),t,n)}},aT=class extends nT{constructor(e,t,n){super(new Float32Array(e),t,n)}},oT=/*@__PURE__*/ new Rw,sT=/*@__PURE__*/ new X,cT=/*@__PURE__*/ new X,lT=class{constructor(e=new X,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?oT.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;sT.subVectors(e,this.center);let t=sT.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(sT,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(cT.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(sT.copy(e.center).add(cT)),this.expandByPoint(sT.copy(e.center).sub(cT))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},uT=0,dT=/*@__PURE__*/ new BC,fT=/*@__PURE__*/ new pw,pT=/*@__PURE__*/ new X,mT=/*@__PURE__*/ new Rw,hT=/*@__PURE__*/ new Rw,gT=/*@__PURE__*/ new X,_T=class e extends sC{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:uT++}),this.uuid=dC(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(ZS(e)?iT:rT)(e,1):e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new Z().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return dT.makeRotationFromQuaternion(e),this.applyMatrix4(dT),this}rotateX(e){return dT.makeRotationX(e),this.applyMatrix4(dT),this}rotateY(e){return dT.makeRotationY(e),this.applyMatrix4(dT),this}rotateZ(e){return dT.makeRotationZ(e),this.applyMatrix4(dT),this}translate(e,t,n){return dT.makeTranslation(e,t,n),this.applyMatrix4(dT),this}scale(e,t,n){return dT.makeScale(e,t,n),this.applyMatrix4(dT),this}lookAt(e){return fT.lookAt(e),fT.updateMatrix(),this.applyMatrix4(fT.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(pT).negate(),this.translate(pT.x,pT.y,pT.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new aT(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&q(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Rw);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){J(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new X(-1/0,-1/0,-1/0),new X(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];mT.setFromBufferAttribute(n),this.morphTargetsRelative?(gT.addVectors(this.boundingBox.min,mT.min),this.boundingBox.expandByPoint(gT),gT.addVectors(this.boundingBox.max,mT.max),this.boundingBox.expandByPoint(gT)):(this.boundingBox.expandByPoint(mT.min),this.boundingBox.expandByPoint(mT.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&J(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new lT);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){J(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new X,1/0);return}if(e){let n=this.boundingSphere.center;if(mT.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];hT.setFromBufferAttribute(n),this.morphTargetsRelative?(gT.addVectors(mT.min,hT.min),mT.expandByPoint(gT),gT.addVectors(mT.max,hT.max),mT.expandByPoint(gT)):(mT.expandByPoint(hT.min),mT.expandByPoint(hT.max))}mT.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)gT.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(gT));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)gT.fromBufferAttribute(a,t),o&&(pT.fromBufferAttribute(e,t),gT.add(pT)),r=Math.max(r,n.distanceToSquared(gT))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&J(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){J(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv,a=this.getAttribute(`tangent`);(a===void 0||a.count!==n.count)&&(a=new nT(new Float32Array(4*n.count),4),this.setAttribute(`tangent`,a));let o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new X,s[e]=new X;let c=new X,l=new X,u=new X,d=new Y,f=new Y,p=new Y,m=new X,h=new X;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new X,y=new X,b=new X,x=new X;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0||n.count!==t.count)n=new nT(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new X,i=new X,a=new X,o=new X,s=new X,c=new X,l=new X,u=new X;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)gT.fromBufferAttribute(e,t),gT.normalize(),e.setXYZ(t,gT.x,gT.y,gT.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new nT(a,r,i)}if(this.index===null)return q(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?`BufferGeometry`:this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:`dispose`})}},vT=/*@__PURE__*/ new X,yT=/*@__PURE__*/ new X,bT=/*@__PURE__*/ new Z,xT=class{constructor(e=new X(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=vT.subVectors(n,t).cross(yT.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(vT),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||bT.getNormalMatrix(e),r=this.coplanarPoint(vT).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}},ST=0,CT=class extends sC{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:ST++}),this.uuid=dC(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new xw(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=qS,this.stencilZFail=qS,this.stencilZPass=qS,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){q(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){q(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new xw().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(e=>new xT().fromJSON(e))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new Y().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new Y().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},wT=/*@__PURE__*/ new X,TT=/*@__PURE__*/ new X,ET=/*@__PURE__*/ new X,DT=/*@__PURE__*/ new X,OT=class{constructor(e=new X,t=new X(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,wT)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=wT.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(wT.copy(this.origin).addScaledVector(this.direction,t),wT.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){TT.copy(e).add(t).multiplyScalar(.5),ET.copy(t).sub(e).normalize(),DT.copy(this.origin).sub(TT);let i=e.distanceTo(t)*.5,a=-this.direction.dot(ET),o=DT.dot(this.direction),s=-DT.dot(ET),c=DT.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(TT).addScaledVector(ET,d),f}intersectSphere(e,t){if(e.radius<0)return null;wT.subVectors(e.center,this.origin);let n=wT.dot(this.direction),r=wT.dot(wT)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,wT)!==null}intersectTriangle(e,t,n,r,i){let a=this.origin,o=this.direction,s=o.x,c=o.y,l=o.z,u=e.x-a.x,d=e.y-a.y,f=e.z-a.z,p=t.x-a.x,m=t.y-a.y,h=t.z-a.z,g=n.x-a.x,_=n.y-a.y,v=n.z-a.z,y=Math.abs(s),b=Math.abs(c),x=Math.abs(l),S,C,w,T,E,D,O,k,A,ee,te,j;if(y>=b&&y>=x?(w=s,D=u,A=p,j=g,s>=0?(S=c,C=l,T=d,E=f,O=m,k=h,ee=_,te=v):(S=l,C=c,T=f,E=d,O=h,k=m,ee=v,te=_)):b>=x?(w=c,D=d,A=m,j=_,c>=0?(S=l,C=s,T=f,E=u,O=h,k=p,ee=v,te=g):(S=s,C=l,T=u,E=f,O=p,k=h,ee=g,te=v)):(w=l,D=f,A=h,j=v,l>=0?(S=s,C=c,T=u,E=d,O=p,k=m,ee=g,te=_):(S=c,C=s,T=d,E=u,O=m,k=p,ee=_,te=g)),w===0)return null;let ne=S/w,re=C/w,M=1/w,ie=T-ne*D,N=E-re*D,ae=O-ne*A,oe=k-re*A,se=ee-ne*j,ce=te-re*j,le=se*oe-ce*ae,ue=ie*ce-N*se,de=ae*N-oe*ie;if(r){if(le<0||ue<0||de<0)return null}else if((le<0||ue<0||de<0)&&(le>0||ue>0||de>0))return null;let fe=le+ue+de;if(fe===0)return null;let pe=M*(le*D+ue*A+de*j);return(fe>0?pe<0:pe>0)?null:this.at(pe/fe,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},kT=class extends CT{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new xw(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new XC,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},AT=/*@__PURE__*/ new BC,jT=/*@__PURE__*/ new OT,MT=/*@__PURE__*/ new lT,NT=/*@__PURE__*/ new X,PT=/*@__PURE__*/ new X,FT=/*@__PURE__*/ new X,IT=/*@__PURE__*/ new X,LT=/*@__PURE__*/ new X,RT=/*@__PURE__*/ new X,zT=/*@__PURE__*/ new X,BT=/*@__PURE__*/ new X,VT=class extends pw{constructor(e=new _T,t=new kT){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){RT.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(LT.fromBufferAttribute(s,e),a?RT.addScaledVector(LT,r):RT.addScaledVector(LT.sub(t),r))}t.add(RT)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),MT.copy(n.boundingSphere),MT.applyMatrix4(i),jT.copy(e.ray).recast(e.near),!(MT.containsPoint(jT.origin)===!1&&(jT.intersectSphere(MT,NT)===null||jT.origin.distanceToSquared(NT)>(e.far-e.near)**2))&&(AT.copy(i).invert(),jT.copy(e.ray).applyMatrix4(AT),(n.boundingBox===null||jT.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,jT)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=UT(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=UT(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}}else if(s!==void 0){if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=UT(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=UT(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}}};function HT(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;BT.copy(s),BT.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(BT);return l<n.near||l>n.far?null:{distance:l,point:BT.clone(),object:e}}function UT(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,PT),e.getVertexPosition(c,FT),e.getVertexPosition(l,IT);let u=HT(e,t,n,r,PT,FT,IT,zT);if(u){let e=new X;Lw.getBarycoord(zT,PT,FT,IT,e),i&&(u.uv=Lw.getInterpolatedAttribute(i,s,c,l,e,new Y)),a&&(u.uv1=Lw.getInterpolatedAttribute(a,s,c,l,e,new Y)),o&&(u.normal=Lw.getInterpolatedAttribute(o,s,c,l,e,new X),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new X,materialIndex:0};Lw.getNormal(PT,FT,IT,t.normal),u.face=t,u.barycoord=e}return u}var WT=class extends PC{constructor(e=null,t=1,n=1,r,i,a,o,s,c=wx,l=wx,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},GT=/*@__PURE__*/ new lT,KT=/*@__PURE__*/ new Y(.5,.5),qT=/*@__PURE__*/ new X,JT=class{constructor(e=new xT,t=new xT,n=new xT,r=new xT,i=new xT,a=new xT){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=XS,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),GT.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),GT.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(GT)}intersectsSprite(e){return GT.center.set(0,0,0),GT.radius=.7071067811865476+KT.distanceTo(e.center),GT.applyMatrix4(e.matrixWorld),this.intersectsSphere(GT)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(qT.x=r.normal.x>0?e.max.x:e.min.x,qT.y=r.normal.y>0?e.max.y:e.min.y,qT.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(qT)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},YT=class extends PC{constructor(e,t,n,r,i=Dx,a=Dx,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;let l=this;function u(){l.needsUpdate=!0,l._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u)}`requestVideoFrameCallback`in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u))}clone(){return new this.constructor(this.image).copy(this)}update(){let e=this.image;!(`requestVideoFrameCallback`in e)&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}},XT=class extends YT{constructor(e,t,n,r,i,a,o,s){super({},e,t,n,r,i,a,o,s),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}},ZT=class extends PC{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},QT=class extends PC{constructor(e,t,n=Fx,r,i,a,o=wx,s=wx,c,l=Kx,u=1){if(l!==1026&&l!==1027)throw Error(`THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new AC(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},$T=class extends QT{constructor(e,t=Fx,n=301,r,i,a=wx,o=wx,s,c=Kx){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},eE=class extends PC{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},tE=class e extends _T{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new aT(c,3)),this.setAttribute(`normal`,new aT(l,3)),this.setAttribute(`uv`,new aT(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new X;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}},nE=class e extends _T{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new aT(p,3)),this.setAttribute(`normal`,new aT(m,3)),this.setAttribute(`uv`,new aT(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}};function rE(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(aE(i))i.isRenderTargetTexture?(q(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone();else if(Array.isArray(i)){if(aE(i[0])){let e=[];for(let t=0,n=i.length;t<n;t++)e[t]=i[t].clone();t[n][r]=e}else t[n][r]=i.slice()}else t[n][r]=i}}return t}function iE(e){let t={};for(let n=0;n<e.length;n++){let r=rE(e[n]);for(let e in r)t[e]=r[e]}return t}function aE(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function oE(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function sE(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:wC.workingColorSpace}var cE={clone:rE,merge:iE},lE=`void main() {
|
|
5
4
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
6
|
-
}
|
|
5
|
+
}`,uE=`void main() {
|
|
7
6
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
8
|
-
}`,ek=class extends fO{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=QO,this.fragmentShader=$O,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=KO(e.uniforms),this.uniformsGroups=YO(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case`t`:this.uniforms[n].value=t[r.value]||null;break;case`c`:this.uniforms[n].value=new uD().setHex(r.value);break;case`v2`:this.uniforms[n].value=new aE().fromArray(r.value);break;case`v3`:this.uniforms[n].value=new X().fromArray(r.value);break;case`v4`:this.uniforms[n].value=new wE().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new Z().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new kE().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)this.extensions[t]=e.extensions[t];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},tk=class extends ek{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},nk=class extends fO{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=AT,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},rk=class extends fO{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function ik(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function ak(e){return e!==void 0&&e.inTangents!==void 0&&e.outTangents!==void 0}var ok=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`THREE.Interpolant: Call to abstract method.`)}intervalChanged_(){}},sk=class extends ok{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:DT,endingEnd:DT}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case OT:i=e,o=2*t-n;break;case kT:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case OT:a=e,s=2*n-t;break;case kT:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},ck=class extends ok{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},lk=class extends ok{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},uk=class extends ok{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let d=o*2,f=e-1;for(let p=0;p!==o;++p){let o=a[c+p],m=a[s+p],h=f*d+p*2,g=u[h],_=u[h+1],v=e*d+p*2,y=l[v],b=l[v+1],x=pk(n,t,g,y,r);i[p]=dk(x,o,_,b,m)}return i}};function dk(e,t,n,r,i){let a=1-e;return a*a*a*t+3*a*a*e*n+3*a*e*e*r+e*e*e*i}function fk(e,t,n,r,i){let a=1-e;return 3*a*a*(n-t)+6*a*e*(r-n)+3*e*e*(i-r)}function pk(e,t,n,r,i){let a=(e-t)/(i-t);for(let o=0;o<8;o++){let o=dk(a,t,n,r,i)-e;if(Math.abs(o)<1e-10)break;let s=fk(a,t,n,r,i);if(Math.abs(s)<1e-10)break;a=Math.max(0,Math.min(1,a-o/s))}return a}var mk=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=ik(t,this.TimeBufferType),this.values=ik(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:ik(e.times,Array),values:ik(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t),ak(e.settings)&&(n.settings={inTangents:ik(e.settings.inTangents,Array),outTangents:ik(e.settings.outTangents,Array)})}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new lk(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new ck(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new sk(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new uk(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents),t}setInterpolation(e){let t;switch(e){case CT:t=this.InterpolantFactoryMethodDiscrete;break;case wT:t=this.InterpolantFactoryMethodLinear;break;case TT:t=this.InterpolantFactoryMethodSmooth;break;case ET:t=this.InterpolantFactoryMethodBezier}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0){if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t)}return J(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return CT;case this.InterpolantFactoryMethodLinear:return wT;case this.InterpolantFactoryMethodSmooth:return TT;case this.InterpolantFactoryMethodBezier:return ET}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e;ak(this.settings)&&(hk(this.settings.inTangents,e),hk(this.settings.outTangents,e))}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(Y(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(Y(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){Y(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){Y(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&BT(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){Y(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===TT,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0])){if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,ak(this.settings)&&(r.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),r}};function hk(e,t){for(let n=0,r=e.length;n!==r;n+=2)e[n]*=t}mk.prototype.ValueTypeName=``,mk.prototype.TimeBufferType=Float32Array,mk.prototype.ValueBufferType=Float32Array,mk.prototype.DefaultInterpolation=wT;var gk=class extends mk{constructor(e,t,n){super(e,t,n)}};gk.prototype.ValueTypeName=`bool`,gk.prototype.ValueBufferType=Array,gk.prototype.DefaultInterpolation=CT,gk.prototype.InterpolantFactoryMethodLinear=void 0,gk.prototype.InterpolantFactoryMethodSmooth=void 0;var _k=class extends mk{constructor(e,t,n,r){super(e,t,n,r)}};_k.prototype.ValueTypeName=`color`;var vk=class extends mk{constructor(e,t,n,r){super(e,t,n,r)}};vk.prototype.ValueTypeName=`number`;var yk=class extends ok{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)oE.slerpFlat(i,0,a,c-o,a,c,s);return i}},bk=class extends mk{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new yk(this.times,this.values,this.getValueSize(),e)}};bk.prototype.ValueTypeName=`quaternion`,bk.prototype.InterpolantFactoryMethodSmooth=void 0;var xk=class extends mk{constructor(e,t,n){super(e,t,n)}};xk.prototype.ValueTypeName=`string`,xk.prototype.ValueBufferType=Array,xk.prototype.DefaultInterpolation=CT,xk.prototype.InterpolantFactoryMethodLinear=void 0,xk.prototype.InterpolantFactoryMethodSmooth=void 0;var Sk=class extends mk{constructor(e,t,n,r){super(e,t,n,r)}};Sk.prototype.ValueTypeName=`vector`;var Ck=/*@__PURE__*/ new X,wk=/*@__PURE__*/ new oE,Tk=/*@__PURE__*/ new X,Ek=class extends nD{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new kE,this.projectionMatrix=new kE,this.projectionMatrixInverse=new kE,this.coordinateSystem=RT,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(Ck,wk,Tk),Tk.x===1&&Tk.y===1&&Tk.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Ck,wk,Tk.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(Ck,wk,Tk),Tk.x===1&&Tk.y===1&&Tk.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Ck,wk,Tk.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},Dk=/*@__PURE__*/ new X,Ok=/*@__PURE__*/ new aE,kk=/*@__PURE__*/ new aE,Ak=class extends Ek{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=QT*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(ZT*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return QT*2*Math.atan(Math.tan(ZT*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Dk.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Dk.x,Dk.y).multiplyScalar(-e/Dk.z),Dk.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Dk.x,Dk.y).multiplyScalar(-e/Dk.z)}getViewSize(e,t){return this.getViewBounds(e,Ok,kk),t.subVectors(kk,Ok)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(ZT*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},jk=class extends Ek{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},Mk=-90,Nk=1,Pk=class extends nD{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new Ak(Mk,Nk,e,t);r.layers=this.layers,this.add(r);let i=new Ak(Mk,Nk,e,t);i.layers=this.layers,this.add(i);let a=new Ak(Mk,Nk,e,t);a.layers=this.layers,this.add(a);let o=new Ak(Mk,Nk,e,t);o.layers=this.layers,this.add(o);let s=new Ak(Mk,Nk,e,t);s.layers=this.layers,this.add(s);let c=new Ak(Mk,Nk,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},Fk=class extends Ak{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},Ik=`\\[\\]\\.:\\/`,Lk=/* @__PURE__ */ RegExp(`[\\[\\]\\.:\\/]`,`g`),Rk=`[^\\[\\]\\.:\\/]`,zk=`[^`+Ik.replace(`\\.`,``)+`]`,Bk=/*@__PURE__*/ `((?:WC+[\\/:])*)`.replace(`WC`,Rk),Vk=/*@__PURE__*/ `(WCOD+)?`.replace(`WCOD`,zk),Hk=/*@__PURE__*/ `(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Rk),Uk=/*@__PURE__*/ `\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Rk),Wk=RegExp(`^`+Bk+Vk+Hk+Uk+`$`),Gk=[`material`,`materials`,`bones`,`map`],Kk=class{constructor(e,t,n){let r=n||qk.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},qk=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Lk,``)}static parseTrackName(e){let t=Wk.exec(e);if(t===null)throw Error(`THREE.PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);Gk.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`THREE.PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){J(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){Y(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){Y(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){Y(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){Y(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){Y(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){Y(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){Y(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;Y(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){Y(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){Y(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};qk.Composite=Kk,qk.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},qk.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},qk.prototype.GetterByBindingType=[qk.prototype._getValue_direct,qk.prototype._getValue_array,qk.prototype._getValue_arrayElement,qk.prototype._getValue_toArray],qk.prototype.SetterByBindingTypeAndVersioning=[[qk.prototype._setValue_direct,qk.prototype._setValue_direct_setNeedsUpdate,qk.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[qk.prototype._setValue_array,qk.prototype._setValue_array_setNeedsUpdate,qk.prototype._setValue_array_setMatrixWorldNeedsUpdate],[qk.prototype._setValue_arrayElement,qk.prototype._setValue_arrayElement_setNeedsUpdate,qk.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[qk.prototype._setValue_fromArray,qk.prototype._setValue_fromArray_setNeedsUpdate,qk.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]],class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}};function Jk(e,t,n,r){let i=Yk(r);switch(n){case jw:return e*t;case Iw:return e*t/i.components*i.byteLength;case Lw:return e*t/i.components*i.byteLength;case Rw:return e*t*2/i.components*i.byteLength;case zw:return e*t*2/i.components*i.byteLength;case Mw:return e*t*3/i.components*i.byteLength;case Nw:return e*t*4/i.components*i.byteLength;case Bw:return e*t*4/i.components*i.byteLength;case Vw:case Hw:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Uw:case Ww:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Kw:case Jw:return Math.max(e,16)*Math.max(t,8)/4;case Gw:case qw:return Math.max(e,8)*Math.max(t,8)/2;case Yw:case Xw:case Qw:case $w:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Zw:case eT:case tT:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case nT:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case rT:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case iT:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case aT:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case oT:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case sT:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case cT:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case lT:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case uT:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case dT:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case fT:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case pT:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case mT:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case hT:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case gT:case _T:case vT:return Math.ceil(e/4)*Math.ceil(t/4)*16;case yT:case bT:return Math.ceil(e/4)*Math.ceil(t/4)*8;case xT:case ST:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function Yk(e){switch(e){case vw:case yw:return{byteLength:1,components:1};case xw:case bw:case Tw:return{byteLength:2,components:1};case Ew:case Dw:return{byteLength:2,components:4};case Cw:case Sw:case ww:return{byteLength:4,components:1};case kw:case Aw:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`186`}})),typeof window<`u`&&(window.__THREE__?J(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`186`);function Xk(){let e=null,t=!1,n=null,r=null;function i(t,a){r=e.requestAnimationFrame(i),n(t,a)}return{start:function(){t!==!0&&n!==null&&e!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e!==null&&e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Zk(e){let t=/* @__PURE__ */ new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var Q={alphahash_fragment:`#ifdef USE_ALPHAHASH
|
|
7
|
+
}`,dE=class extends CT{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=lE,this.fragmentShader=uE,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=rE(e.uniforms),this.uniformsGroups=oE(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case`t`:this.uniforms[n].value=t[r.value]||null;break;case`c`:this.uniforms[n].value=new xw().setHex(r.value);break;case`v2`:this.uniforms[n].value=new Y().fromArray(r.value);break;case`v3`:this.uniforms[n].value=new X().fromArray(r.value);break;case`v4`:this.uniforms[n].value=new FC().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new Z().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new BC().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)this.extensions[t]=e.extensions[t];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},fE=class extends dE{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},pE=class extends CT{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=HS,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},mE=class extends CT{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function hE(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function gE(e){return e!==void 0&&e.inTangents!==void 0&&e.outTangents!==void 0}var _E=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`THREE.Interpolant: Call to abstract method.`)}intervalChanged_(){}},vE=class extends _E{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:zS,endingEnd:zS}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case BS:i=e,o=2*t-n;break;case VS:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case BS:a=e,s=2*n-t;break;case VS:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},yE=class extends _E{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},bE=class extends _E{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},xE=class extends _E{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let d=o*2,f=e-1;for(let p=0;p!==o;++p){let o=a[c+p],m=a[s+p],h=f*d+p*2,g=u[h],_=u[h+1],v=e*d+p*2,y=l[v],b=l[v+1],x=wE(n,t,g,y,r);i[p]=SE(x,o,_,b,m)}return i}};function SE(e,t,n,r,i){let a=1-e;return a*a*a*t+3*a*a*e*n+3*a*e*e*r+e*e*e*i}function CE(e,t,n,r,i){let a=1-e;return 3*a*a*(n-t)+6*a*e*(r-n)+3*e*e*(i-r)}function wE(e,t,n,r,i){let a=(e-t)/(i-t);for(let o=0;o<8;o++){let o=SE(a,t,n,r,i)-e;if(Math.abs(o)<1e-10)break;let s=CE(a,t,n,r,i);if(Math.abs(s)<1e-10)break;a=Math.max(0,Math.min(1,a-o/s))}return a}var TE=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=hE(t,this.TimeBufferType),this.values=hE(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:hE(e.times,Array),values:hE(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t),gE(e.settings)&&(n.settings={inTangents:hE(e.settings.inTangents,Array),outTangents:hE(e.settings.outTangents,Array)})}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new bE(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new yE(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new vE(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new xE(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents),t}setInterpolation(e){let t;switch(e){case FS:t=this.InterpolantFactoryMethodDiscrete;break;case IS:t=this.InterpolantFactoryMethodLinear;break;case LS:t=this.InterpolantFactoryMethodSmooth;break;case RS:t=this.InterpolantFactoryMethodBezier}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0){if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t)}return q(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return FS;case this.InterpolantFactoryMethodLinear:return IS;case this.InterpolantFactoryMethodSmooth:return LS;case this.InterpolantFactoryMethodBezier:return RS}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e;gE(this.settings)&&(EE(this.settings.inTangents,e),EE(this.settings.outTangents,e))}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(J(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(J(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){J(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){J(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&QS(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){J(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===LS,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0])){if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,gE(this.settings)&&(r.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),r}};function EE(e,t){for(let n=0,r=e.length;n!==r;n+=2)e[n]*=t}TE.prototype.ValueTypeName=``,TE.prototype.TimeBufferType=Float32Array,TE.prototype.ValueBufferType=Float32Array,TE.prototype.DefaultInterpolation=IS;var DE=class extends TE{constructor(e,t,n){super(e,t,n)}};DE.prototype.ValueTypeName=`bool`,DE.prototype.ValueBufferType=Array,DE.prototype.DefaultInterpolation=FS,DE.prototype.InterpolantFactoryMethodLinear=void 0,DE.prototype.InterpolantFactoryMethodSmooth=void 0;var OE=class extends TE{constructor(e,t,n,r){super(e,t,n,r)}};OE.prototype.ValueTypeName=`color`;var kE=class extends TE{constructor(e,t,n,r){super(e,t,n,r)}};kE.prototype.ValueTypeName=`number`;var AE=class extends _E{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)_C.slerpFlat(i,0,a,c-o,a,c,s);return i}},jE=class extends TE{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new AE(this.times,this.values,this.getValueSize(),e)}};jE.prototype.ValueTypeName=`quaternion`,jE.prototype.InterpolantFactoryMethodSmooth=void 0;var ME=class extends TE{constructor(e,t,n){super(e,t,n)}};ME.prototype.ValueTypeName=`string`,ME.prototype.ValueBufferType=Array,ME.prototype.DefaultInterpolation=FS,ME.prototype.InterpolantFactoryMethodLinear=void 0,ME.prototype.InterpolantFactoryMethodSmooth=void 0;var NE=class extends TE{constructor(e,t,n,r){super(e,t,n,r)}};NE.prototype.ValueTypeName=`vector`;var PE=/*@__PURE__*/ new X,FE=/*@__PURE__*/ new _C,IE=/*@__PURE__*/ new X,LE=class extends pw{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new BC,this.projectionMatrix=new BC,this.projectionMatrixInverse=new BC,this.coordinateSystem=XS,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(PE,FE,IE),IE.x===1&&IE.y===1&&IE.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(PE,FE,IE.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(PE,FE,IE),IE.x===1&&IE.y===1&&IE.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(PE,FE,IE.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},RE=/*@__PURE__*/ new X,zE=/*@__PURE__*/ new Y,BE=/*@__PURE__*/ new Y,VE=class extends LE{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=uC*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(lC*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return uC*2*Math.atan(Math.tan(lC*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){RE.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(RE.x,RE.y).multiplyScalar(-e/RE.z),RE.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(RE.x,RE.y).multiplyScalar(-e/RE.z)}getViewSize(e,t){return this.getViewBounds(e,zE,BE),t.subVectors(BE,zE)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(lC*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},HE=class extends LE{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},UE=-90,WE=1,GE=class extends pw{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new VE(UE,WE,e,t);r.layers=this.layers,this.add(r);let i=new VE(UE,WE,e,t);i.layers=this.layers,this.add(i);let a=new VE(UE,WE,e,t);a.layers=this.layers,this.add(a);let o=new VE(UE,WE,e,t);o.layers=this.layers,this.add(o);let s=new VE(UE,WE,e,t);s.layers=this.layers,this.add(s);let c=new VE(UE,WE,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},KE=class extends VE{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},qE=`\\[\\]\\.:\\/`,JE=/* @__PURE__ */ RegExp(`[\\[\\]\\.:\\/]`,`g`),YE=`[^\\[\\]\\.:\\/]`,XE=`[^`+qE.replace(`\\.`,``)+`]`,ZE=/*@__PURE__*/ `((?:WC+[\\/:])*)`.replace(`WC`,YE),QE=/*@__PURE__*/ `(WCOD+)?`.replace(`WCOD`,XE),$E=/*@__PURE__*/ `(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,YE),eD=/*@__PURE__*/ `\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,YE),tD=RegExp(`^`+ZE+QE+$E+eD+`$`),nD=[`material`,`materials`,`bones`,`map`],rD=class{constructor(e,t,n){let r=n||iD.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},iD=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(JE,``)}static parseTrackName(e){let t=tD.exec(e);if(t===null)throw Error(`THREE.PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);nD.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`THREE.PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){q(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){J(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){J(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){J(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){J(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){J(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){J(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){J(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;J(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){J(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){J(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};iD.Composite=rD,iD.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},iD.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},iD.prototype.GetterByBindingType=[iD.prototype._getValue_direct,iD.prototype._getValue_array,iD.prototype._getValue_arrayElement,iD.prototype._getValue_toArray],iD.prototype.SetterByBindingTypeAndVersioning=[[iD.prototype._setValue_direct,iD.prototype._setValue_direct_setNeedsUpdate,iD.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[iD.prototype._setValue_array,iD.prototype._setValue_array_setNeedsUpdate,iD.prototype._setValue_array_setMatrixWorldNeedsUpdate],[iD.prototype._setValue_arrayElement,iD.prototype._setValue_arrayElement_setNeedsUpdate,iD.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[iD.prototype._setValue_fromArray,iD.prototype._setValue_fromArray_setNeedsUpdate,iD.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]],class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}};function aD(e,t,n,r){let i=oD(r);switch(n){case Ux:return e*t;case Jx:return e*t/i.components*i.byteLength;case Yx:return e*t/i.components*i.byteLength;case Xx:return e*t*2/i.components*i.byteLength;case Zx:return e*t*2/i.components*i.byteLength;case Wx:return e*t*3/i.components*i.byteLength;case Gx:return e*t*4/i.components*i.byteLength;case Qx:return e*t*4/i.components*i.byteLength;case $x:case eS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case tS:case nS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case iS:case oS:return Math.max(e,16)*Math.max(t,8)/4;case rS:case aS:return Math.max(e,8)*Math.max(t,8)/2;case sS:case cS:case uS:case dS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case lS:case fS:case pS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case mS:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case hS:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case gS:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case _S:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case vS:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case yS:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case bS:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case xS:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case SS:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case CS:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case wS:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case TS:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ES:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case DS:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case OS:case kS:case AS:return Math.ceil(e/4)*Math.ceil(t/4)*16;case jS:case MS:return Math.ceil(e/4)*Math.ceil(t/4)*8;case NS:case PS:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function oD(e){switch(e){case Ax:case jx:return{byteLength:1,components:1};case Nx:case Mx:case Lx:return{byteLength:2,components:1};case Rx:case zx:return{byteLength:2,components:4};case Fx:case Px:case Ix:return{byteLength:4,components:1};case Vx:case Hx:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`186`}})),typeof window<`u`&&(window.__THREE__?q(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`186`);function sD(){let e=null,t=!1,n=null,r=null;function i(t,a){r=e.requestAnimationFrame(i),n(t,a)}return{start:function(){t!==!0&&n!==null&&e!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e!==null&&e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function cD(e){let t=/* @__PURE__ */ new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var Q={alphahash_fragment:`#ifdef USE_ALPHAHASH
|
|
9
8
|
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
|
|
10
9
|
#endif`,alphahash_pars_fragment:`#ifdef USE_ALPHAHASH
|
|
11
10
|
const float ALPHA_HASH_SCALE = 0.05;
|
|
@@ -3823,7 +3822,7 @@ void main() {
|
|
|
3823
3822
|
#include <tonemapping_fragment>
|
|
3824
3823
|
#include <colorspace_fragment>
|
|
3825
3824
|
#include <fog_fragment>
|
|
3826
|
-
}`},$={common:{diffuse:{value:/*@__PURE__*/ new uD(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:/*@__PURE__*/ new Z},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:/*@__PURE__*/ new Z}},envmap:{envMap:{value:null},envMapRotation:{value:/*@__PURE__*/ new Z},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:/*@__PURE__*/ new Z}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:/*@__PURE__*/ new Z}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:/*@__PURE__*/ new Z},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:/*@__PURE__*/ new Z},normalScale:{value:/*@__PURE__*/ new aE(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:/*@__PURE__*/ new Z},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:/*@__PURE__*/ new Z}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:/*@__PURE__*/ new Z}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:/*@__PURE__*/ new Z}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:/*@__PURE__*/ new uD(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:/*@__PURE__*/ new X},probesMax:{value:/*@__PURE__*/ new X},probesResolution:{value:/*@__PURE__*/ new X}},points:{diffuse:{value:/*@__PURE__*/ new uD(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0},uvTransform:{value:/*@__PURE__*/ new Z}},sprite:{diffuse:{value:/*@__PURE__*/ new uD(16777215)},opacity:{value:1},center:{value:/*@__PURE__*/ new aE(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:/*@__PURE__*/ new Z},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0}}},Qk={basic:{uniforms:/*@__PURE__*/ qO([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.fog]),vertexShader:Q.meshbasic_vert,fragmentShader:Q.meshbasic_frag},lambert:{uniforms:/*@__PURE__*/ qO([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new uD(0)},envMapIntensity:{value:1}}]),vertexShader:Q.meshlambert_vert,fragmentShader:Q.meshlambert_frag},phong:{uniforms:/*@__PURE__*/ qO([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new uD(0)},specular:{value:/*@__PURE__*/ new uD(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Q.meshphong_vert,fragmentShader:Q.meshphong_frag},standard:{uniforms:/*@__PURE__*/ qO([$.common,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.roughnessmap,$.metalnessmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new uD(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag},toon:{uniforms:/*@__PURE__*/ qO([$.common,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.gradientmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new uD(0)}}]),vertexShader:Q.meshtoon_vert,fragmentShader:Q.meshtoon_frag},matcap:{uniforms:/*@__PURE__*/ qO([$.common,$.bumpmap,$.normalmap,$.displacementmap,$.fog,{matcap:{value:null}}]),vertexShader:Q.meshmatcap_vert,fragmentShader:Q.meshmatcap_frag},points:{uniforms:/*@__PURE__*/ qO([$.points,$.fog]),vertexShader:Q.points_vert,fragmentShader:Q.points_frag},dashed:{uniforms:/*@__PURE__*/ qO([$.common,$.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Q.linedashed_vert,fragmentShader:Q.linedashed_frag},depth:{uniforms:/*@__PURE__*/ qO([$.common,$.displacementmap]),vertexShader:Q.depth_vert,fragmentShader:Q.depth_frag},normal:{uniforms:/*@__PURE__*/ qO([$.common,$.bumpmap,$.normalmap,$.displacementmap,{opacity:{value:1}}]),vertexShader:Q.meshnormal_vert,fragmentShader:Q.meshnormal_frag},sprite:{uniforms:/*@__PURE__*/ qO([$.sprite,$.fog]),vertexShader:Q.sprite_vert,fragmentShader:Q.sprite_frag},background:{uniforms:{uvTransform:{value:/*@__PURE__*/ new Z},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Q.background_vert,fragmentShader:Q.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:/*@__PURE__*/ new Z}},vertexShader:Q.backgroundCube_vert,fragmentShader:Q.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Q.cube_vert,fragmentShader:Q.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Q.equirect_vert,fragmentShader:Q.equirect_frag},distance:{uniforms:/*@__PURE__*/ qO([$.common,$.displacementmap,{referencePosition:{value:/*@__PURE__*/ new X},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Q.distance_vert,fragmentShader:Q.distance_frag},shadow:{uniforms:/*@__PURE__*/ qO([$.lights,$.fog,{color:{value:/*@__PURE__*/ new uD(0)},opacity:{value:1}}]),vertexShader:Q.shadow_vert,fragmentShader:Q.shadow_frag}};Qk.physical={uniforms:/*@__PURE__*/ qO([Qk.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:/*@__PURE__*/ new Z},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:/*@__PURE__*/ new Z},clearcoatNormalScale:{value:/*@__PURE__*/ new aE(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:/*@__PURE__*/ new Z},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:/*@__PURE__*/ new Z},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:/*@__PURE__*/ new Z},sheen:{value:0},sheenColor:{value:/*@__PURE__*/ new uD(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:/*@__PURE__*/ new Z},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:/*@__PURE__*/ new Z},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:/*@__PURE__*/ new Z},transmissionSamplerSize:{value:/*@__PURE__*/ new aE},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:/*@__PURE__*/ new Z},attenuationDistance:{value:0},attenuationColor:{value:/*@__PURE__*/ new uD(0)},specularColor:{value:/*@__PURE__*/ new uD(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:/*@__PURE__*/ new Z},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:/*@__PURE__*/ new Z},anisotropyVector:{value:/*@__PURE__*/ new aE},anisotropyMap:{value:null},anisotropyMapTransform:{value:/*@__PURE__*/ new Z}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag};var $k={r:0,b:0,g:0},eA=/*@__PURE__*/ new kE,tA=/*@__PURE__*/ new Z;tA.set(-1,0,0,0,1,0,0,0,1);function nA(e,t,n,r,i,a){let o=new uD(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new AO(new WO(1,1,1),new ek({name:`BackgroundCubeMaterial`,uniforms:KO(Qk.backgroundCube.uniforms),vertexShader:Qk.backgroundCube.vertexShader,fragmentShader:Qk.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),l.material.uniforms.envMap.value=i,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(eA.makeRotationFromEuler(n.backgroundRotation)).transpose(),i.isCubeTexture&&i.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(tA),l.material.toneMapped=pE.getTransfer(i.colorSpace)!==PT,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new AO(new GO(2,2),new ek({name:`BackgroundMaterial`,uniforms:KO(Qk.background.uniforms),vertexShader:Qk.background.vertexShader,fragmentShader:Qk.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=pE.getTransfer(i.colorSpace)!==PT,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB($k,XO(e)),n.buffers.color.setClear($k.r,$k.g,$k.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function rA(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){T();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e.id]}function C(e){for(let t in r){let n=r[t];for(let t in n){let r=n[t];if(r[e.id]===void 0)continue;let i=r[e.id];for(let e in i)u(i[e].object),delete i[e];delete r[e.id]}}}function w(e){for(let t in r){let n=r[t],i=e.isInstancedMesh===!0?e.id:0,a=n[i];if(a!==void 0){for(let e in a){let t=a[e];for(let e in t)u(t[e].object),delete t[e];delete a[e]}delete n[i],Object.keys(n).length===0&&delete r[t]}}}function T(){E(),o=!0,a!==i&&(a=i,l(a.object))}function E(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:T,resetDefaultState:E,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfObject:w,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function iA(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s}function aA(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return t===1023||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&n!==1015&&!i&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(J(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`);n.reversedDepthBuffer===!0&&f===!1&&J(`WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.`);let p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function oA(e){let t=this,n=null,r=0,i=!1,a=!1,o=new uO,s=new Z,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}var sA=4,cA=6,lA=20,uA=256,dA=/*@__PURE__*/ new jk,fA=/*@__PURE__*/ new uD,pA=null,mA=0,hA=0,gA=!1,_A=/*@__PURE__*/ new X,vA=/*@__PURE__*/ new X,yA=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=_A}=i;pA=this._renderer.getRenderTarget(),mA=this._renderer.getActiveCubeFace(),hA=this._renderer.getActiveMipmapLevel(),gA=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=EA(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=TA(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(pA,mA,hA),this._renderer.xr.enabled=gA,e.scissorTest=!1,SA(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),pA=this._renderer.getRenderTarget(),mA=this._renderer.getActiveCubeFace(),hA=this._renderer.getActiveMipmapLevel(),gA=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:hw,minFilter:hw,generateMipmaps:!1,type:Tw,format:Nw,colorSpace:MT,depthBuffer:!1},r=xA(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=xA(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=bA(r)),this._blurMaterial=wA(r,e,t),this._ggxMaterial=CA(r,e,t)}return r}_compileMaterial(e){let t=new AO(new oO,e);this._renderer.compile(t,dA)}_sceneToCubeUV(e,t,n,r,i){let a=new Ak(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(fA),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new AO(new WO,new vO({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,f=d.material,p=!1,m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,p=!0):(f.color.copy(fA),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;SA(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=EA()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=TA());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;SA(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,dA)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t<r;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,i=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=a.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(c*1.25),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-sA?n-d+sA:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,SA(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,dA),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,SA(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,dA)}_blur(e,t,n,r){let i=this._pingPongRenderTarget,a=Math.min(r,Math.PI)/Math.SQRT2;this._blurPass(e,i,t,n,a),this._blurPass(i,e,n,n,a)}_blurPass(e,t,n,r,i){let a=this._renderer,o=this._blurMaterial,s=this._lodMeshes[r];s.material=o;let c=o.uniforms;c.envMap.value=e.texture,c.sigma.value=i,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[r];SA(t,3*l*(r>this._lodMax-sA?r-this._lodMax+sA:0),4*(this._cubeSize-l),3*l,2*l),a.setRenderTarget(t),a.render(s,dA)}};function bA(e){let t=[],n=[],r=e,i=e-sA+1+cA;for(let e=0;e<i;e++){let e=2**r;t.push(e);let i=1/(e-2),a=-i,o=1+i,s=[a,a,o,a,o,o,a,a,o,o,a,o],c=/* @__PURE__ */ new Float32Array(108),l=/* @__PURE__ */ new Float32Array(108);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];c.set(r,18*e);for(let t=0;t<6;t++){let n=s[t*2]*2-1,r=s[t*2+1]*2-1;e===0?vA.set(1,r,n):e===1?vA.set(-n,1,-r):e===2?vA.set(-n,r,1):e===3?vA.set(-1,r,-n):e===4?vA.set(-n,-1,r):vA.set(n,r,-1),vA.toArray(l,(e*6+t)*3)}}let u=new oO;u.setAttribute(`position`,new GD(c,3)),u.setAttribute(`outputDirection`,new GD(l,3)),n.push(new AO(u,null)),r>sA&&r--}return{lodMeshes:n,sizeLods:t}}function xA(e,t,n){let r=new EE(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function SA(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function CA(e,t,n){return new ek({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:uA,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:DA(),fragmentShader:`
|
|
3825
|
+
}`},$={common:{diffuse:{value:/*@__PURE__*/ new xw(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:/*@__PURE__*/ new Z},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:/*@__PURE__*/ new Z}},envmap:{envMap:{value:null},envMapRotation:{value:/*@__PURE__*/ new Z},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:/*@__PURE__*/ new Z}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:/*@__PURE__*/ new Z}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:/*@__PURE__*/ new Z},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:/*@__PURE__*/ new Z},normalScale:{value:/*@__PURE__*/ new Y(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:/*@__PURE__*/ new Z},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:/*@__PURE__*/ new Z}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:/*@__PURE__*/ new Z}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:/*@__PURE__*/ new Z}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:/*@__PURE__*/ new xw(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:/*@__PURE__*/ new X},probesMax:{value:/*@__PURE__*/ new X},probesResolution:{value:/*@__PURE__*/ new X}},points:{diffuse:{value:/*@__PURE__*/ new xw(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0},uvTransform:{value:/*@__PURE__*/ new Z}},sprite:{diffuse:{value:/*@__PURE__*/ new xw(16777215)},opacity:{value:1},center:{value:/*@__PURE__*/ new Y(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:/*@__PURE__*/ new Z},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/ new Z},alphaTest:{value:0}}},lD={basic:{uniforms:/*@__PURE__*/ iE([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.fog]),vertexShader:Q.meshbasic_vert,fragmentShader:Q.meshbasic_frag},lambert:{uniforms:/*@__PURE__*/ iE([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new xw(0)},envMapIntensity:{value:1}}]),vertexShader:Q.meshlambert_vert,fragmentShader:Q.meshlambert_frag},phong:{uniforms:/*@__PURE__*/ iE([$.common,$.specularmap,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new xw(0)},specular:{value:/*@__PURE__*/ new xw(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Q.meshphong_vert,fragmentShader:Q.meshphong_frag},standard:{uniforms:/*@__PURE__*/ iE([$.common,$.envmap,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.roughnessmap,$.metalnessmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new xw(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag},toon:{uniforms:/*@__PURE__*/ iE([$.common,$.aomap,$.lightmap,$.emissivemap,$.bumpmap,$.normalmap,$.displacementmap,$.gradientmap,$.fog,$.lights,{emissive:{value:/*@__PURE__*/ new xw(0)}}]),vertexShader:Q.meshtoon_vert,fragmentShader:Q.meshtoon_frag},matcap:{uniforms:/*@__PURE__*/ iE([$.common,$.bumpmap,$.normalmap,$.displacementmap,$.fog,{matcap:{value:null}}]),vertexShader:Q.meshmatcap_vert,fragmentShader:Q.meshmatcap_frag},points:{uniforms:/*@__PURE__*/ iE([$.points,$.fog]),vertexShader:Q.points_vert,fragmentShader:Q.points_frag},dashed:{uniforms:/*@__PURE__*/ iE([$.common,$.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Q.linedashed_vert,fragmentShader:Q.linedashed_frag},depth:{uniforms:/*@__PURE__*/ iE([$.common,$.displacementmap]),vertexShader:Q.depth_vert,fragmentShader:Q.depth_frag},normal:{uniforms:/*@__PURE__*/ iE([$.common,$.bumpmap,$.normalmap,$.displacementmap,{opacity:{value:1}}]),vertexShader:Q.meshnormal_vert,fragmentShader:Q.meshnormal_frag},sprite:{uniforms:/*@__PURE__*/ iE([$.sprite,$.fog]),vertexShader:Q.sprite_vert,fragmentShader:Q.sprite_frag},background:{uniforms:{uvTransform:{value:/*@__PURE__*/ new Z},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Q.background_vert,fragmentShader:Q.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:/*@__PURE__*/ new Z}},vertexShader:Q.backgroundCube_vert,fragmentShader:Q.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Q.cube_vert,fragmentShader:Q.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Q.equirect_vert,fragmentShader:Q.equirect_frag},distance:{uniforms:/*@__PURE__*/ iE([$.common,$.displacementmap,{referencePosition:{value:/*@__PURE__*/ new X},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Q.distance_vert,fragmentShader:Q.distance_frag},shadow:{uniforms:/*@__PURE__*/ iE([$.lights,$.fog,{color:{value:/*@__PURE__*/ new xw(0)},opacity:{value:1}}]),vertexShader:Q.shadow_vert,fragmentShader:Q.shadow_frag}};lD.physical={uniforms:/*@__PURE__*/ iE([lD.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:/*@__PURE__*/ new Z},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:/*@__PURE__*/ new Z},clearcoatNormalScale:{value:/*@__PURE__*/ new Y(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:/*@__PURE__*/ new Z},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:/*@__PURE__*/ new Z},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:/*@__PURE__*/ new Z},sheen:{value:0},sheenColor:{value:/*@__PURE__*/ new xw(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:/*@__PURE__*/ new Z},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:/*@__PURE__*/ new Z},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:/*@__PURE__*/ new Z},transmissionSamplerSize:{value:/*@__PURE__*/ new Y},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:/*@__PURE__*/ new Z},attenuationDistance:{value:0},attenuationColor:{value:/*@__PURE__*/ new xw(0)},specularColor:{value:/*@__PURE__*/ new xw(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:/*@__PURE__*/ new Z},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:/*@__PURE__*/ new Z},anisotropyVector:{value:/*@__PURE__*/ new Y},anisotropyMap:{value:null},anisotropyMapTransform:{value:/*@__PURE__*/ new Z}}]),vertexShader:Q.meshphysical_vert,fragmentShader:Q.meshphysical_frag};var uD={r:0,b:0,g:0},dD=/*@__PURE__*/ new BC,fD=/*@__PURE__*/ new Z;fD.set(-1,0,0,0,1,0,0,0,1);function pD(e,t,n,r,i,a){let o=new xw(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new VT(new tE(1,1,1),new dE({name:`BackgroundCubeMaterial`,uniforms:rE(lD.backgroundCube.uniforms),vertexShader:lD.backgroundCube.vertexShader,fragmentShader:lD.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),l.material.uniforms.envMap.value=i,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(dD.makeRotationFromEuler(n.backgroundRotation)).transpose(),i.isCubeTexture&&i.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(fD),l.material.toneMapped=wC.getTransfer(i.colorSpace)!==KS,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new VT(new nE(2,2),new dE({name:`BackgroundMaterial`,uniforms:rE(lD.background.uniforms),vertexShader:lD.background.vertexShader,fragmentShader:lD.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=wC.getTransfer(i.colorSpace)!==KS,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB(uD,sE(e)),n.buffers.color.setClear(uD.r,uD.g,uD.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function mD(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){T();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e.id]}function C(e){for(let t in r){let n=r[t];for(let t in n){let r=n[t];if(r[e.id]===void 0)continue;let i=r[e.id];for(let e in i)u(i[e].object),delete i[e];delete r[e.id]}}}function w(e){for(let t in r){let n=r[t],i=e.isInstancedMesh===!0?e.id:0,a=n[i];if(a!==void 0){for(let e in a){let t=a[e];for(let e in t)u(t[e].object),delete t[e];delete a[e]}delete n[i],Object.keys(n).length===0&&delete r[t]}}}function T(){E(),o=!0,a!==i&&(a=i,l(a.object))}function E(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:T,resetDefaultState:E,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfObject:w,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function hD(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s}function gD(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return t===1023||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&n!==1015&&!i&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(q(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`);n.reversedDepthBuffer===!0&&f===!1&&q(`WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.`);let p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function _D(e){let t=this,n=null,r=0,i=!1,a=!1,o=new xT,s=new Z,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}var vD=4,yD=6,bD=20,xD=256,SD=/*@__PURE__*/ new HE,CD=/*@__PURE__*/ new xw,wD=null,TD=0,ED=0,DD=!1,OD=/*@__PURE__*/ new X,kD=/*@__PURE__*/ new X,AD=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=OD}=i;wD=this._renderer.getRenderTarget(),TD=this._renderer.getActiveCubeFace(),ED=this._renderer.getActiveMipmapLevel(),DD=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=LD(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=ID(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(wD,TD,ED),this._renderer.xr.enabled=DD,e.scissorTest=!1,ND(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),wD=this._renderer.getRenderTarget(),TD=this._renderer.getActiveCubeFace(),ED=this._renderer.getActiveMipmapLevel(),DD=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Dx,minFilter:Dx,generateMipmaps:!1,type:Lx,format:Gx,colorSpace:WS,depthBuffer:!1},r=MD(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=MD(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=jD(r)),this._blurMaterial=FD(r,e,t),this._ggxMaterial=PD(r,e,t)}return r}_compileMaterial(e){let t=new VT(new _T,e);this._renderer.compile(t,SD)}_sceneToCubeUV(e,t,n,r,i){let a=new VE(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(CD),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new VT(new tE,new kT({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,f=d.material,p=!1,m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,p=!0):(f.color.copy(CD),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;ND(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=LD()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=ID());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;ND(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,SD)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t<r;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,i=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=a.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(c*1.25),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-vD?n-d+vD:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,ND(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,SD),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,ND(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,SD)}_blur(e,t,n,r){let i=this._pingPongRenderTarget,a=Math.min(r,Math.PI)/Math.SQRT2;this._blurPass(e,i,t,n,a),this._blurPass(i,e,n,n,a)}_blurPass(e,t,n,r,i){let a=this._renderer,o=this._blurMaterial,s=this._lodMeshes[r];s.material=o;let c=o.uniforms;c.envMap.value=e.texture,c.sigma.value=i,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[r];ND(t,3*l*(r>this._lodMax-vD?r-this._lodMax+vD:0),4*(this._cubeSize-l),3*l,2*l),a.setRenderTarget(t),a.render(s,SD)}};function jD(e){let t=[],n=[],r=e,i=e-vD+1+yD;for(let e=0;e<i;e++){let e=2**r;t.push(e);let i=1/(e-2),a=-i,o=1+i,s=[a,a,o,a,o,o,a,a,o,o,a,o],c=/* @__PURE__ */ new Float32Array(108),l=/* @__PURE__ */ new Float32Array(108);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];c.set(r,18*e);for(let t=0;t<6;t++){let n=s[t*2]*2-1,r=s[t*2+1]*2-1;e===0?kD.set(1,r,n):e===1?kD.set(-n,1,-r):e===2?kD.set(-n,r,1):e===3?kD.set(-1,r,-n):e===4?kD.set(-n,-1,r):kD.set(n,r,-1),kD.toArray(l,(e*6+t)*3)}}let u=new _T;u.setAttribute(`position`,new nT(c,3)),u.setAttribute(`outputDirection`,new nT(l,3)),n.push(new VT(u,null)),r>vD&&r--}return{lodMeshes:n,sizeLods:t}}function MD(e,t,n){let r=new LC(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function ND(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function PD(e,t,n){return new dE({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:xD,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:RD(),fragmentShader:`
|
|
3827
3826
|
|
|
3828
3827
|
precision highp float;
|
|
3829
3828
|
precision highp int;
|
|
@@ -3927,7 +3926,7 @@ void main() {
|
|
|
3927
3926
|
|
|
3928
3927
|
gl_FragColor = vec4(prefilteredColor, 1.0);
|
|
3929
3928
|
}
|
|
3930
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
3929
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function FD(e,t,n){return new dE({name:`SphericalGaussianBlur`,defines:{SAMPLES:bD,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:RD(),fragmentShader:`
|
|
3931
3930
|
|
|
3932
3931
|
precision highp float;
|
|
3933
3932
|
precision highp int;
|
|
@@ -3987,7 +3986,7 @@ void main() {
|
|
|
3987
3986
|
gl_FragColor = vec4( accumColor / accumWeight, 1.0 );
|
|
3988
3987
|
|
|
3989
3988
|
}
|
|
3990
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
3989
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function ID(){return new dE({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:RD(),fragmentShader:`
|
|
3991
3990
|
|
|
3992
3991
|
precision mediump float;
|
|
3993
3992
|
precision mediump int;
|
|
@@ -4006,7 +4005,7 @@ void main() {
|
|
|
4006
4005
|
gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
|
|
4007
4006
|
|
|
4008
4007
|
}
|
|
4009
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
4008
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function LD(){return new dE({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:RD(),fragmentShader:`
|
|
4010
4009
|
|
|
4011
4010
|
precision mediump float;
|
|
4012
4011
|
precision mediump int;
|
|
@@ -4022,7 +4021,7 @@ void main() {
|
|
|
4022
4021
|
gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
|
|
4023
4022
|
|
|
4024
4023
|
}
|
|
4025
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
4024
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function RD(){return`
|
|
4026
4025
|
|
|
4027
4026
|
precision mediump float;
|
|
4028
4027
|
precision mediump int;
|
|
@@ -4037,7 +4036,7 @@ void main() {
|
|
|
4037
4036
|
gl_Position = vec4( position, 1.0 );
|
|
4038
4037
|
|
|
4039
4038
|
}
|
|
4040
|
-
`}var
|
|
4039
|
+
`}var zD=class extends LC{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new ZT(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:`
|
|
4041
4040
|
|
|
4042
4041
|
varying vec3 vWorldDirection;
|
|
4043
4042
|
|
|
@@ -4072,7 +4071,7 @@ void main() {
|
|
|
4072
4071
|
gl_FragColor = texture2D( tEquirect, sampleUV );
|
|
4073
4072
|
|
|
4074
4073
|
}
|
|
4075
|
-
`},r=new
|
|
4074
|
+
`},r=new tE(5,5,5),i=new dE({name:`CubemapFromEquirect`,uniforms:rE(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new VT(r,i),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=Dx),new GE(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}};function BD(e){let t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakMap,r=null;function i(e,t=!1){return e==null?null:t?o(e):a(e)}function a(n){if(n&&n.isTexture){let r=n.mapping;if(r===303||r===304){if(t.has(n)){let e=t.get(n).texture;return s(e,n.mapping)}{let r=n.image;if(r&&r.height>0){let i=new zD(r.height);return i.fromEquirectangularTexture(e,n),t.set(n,i),n.addEventListener(`dispose`,l),s(i.texture,n.mapping)}return null}}}return n}function o(t){if(t&&t.isTexture){let i=t.mapping,a=i===303||i===304,o=i===301||i===302;if(a||o){let i=n.get(t),s=i===void 0?0:i.texture.pmremVersion;if(t.isRenderTargetTexture&&t.pmremVersion!==s)return r===null&&(r=new AD(e)),i=a?r.fromEquirectangular(t,i):r.fromCubemap(t,i),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),i.texture;if(i!==void 0)return i.texture;{let s=t.image;return a&&s&&s.height>0||o&&s&&c(s)?(r===null&&(r=new AD(e)),i=a?r.fromEquirectangular(t):r.fromCubemap(t),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),t.addEventListener(`dispose`,u),i.texture):null}}}return t}function s(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function c(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function l(e){let n=e.target;n.removeEventListener(`dispose`,l);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function u(e){let t=e.target;t.removeEventListener(`dispose`,u);let r=n.get(t);r!==void 0&&(n.delete(t),r.dispose())}function d(){t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakMap,r!==null&&(r.dispose(),r=null)}return{get:i,dispose:d}}function VD(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r=e.getExtension(n);return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&iC(`WebGLRenderer: `+e+` extension not supported.`),t}}}function HD(e,t,n,r){let i={},a=/* @__PURE__ */ new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(i===void 0)return;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t<r;t+=3){let r=e[t+0],i=e[t+1],a=e[t+2];n.push(r,i,i,a,a,r)}}else{let e=i.array;o=i.version;for(let t=0,r=e.length/3-1;t<r;t+=3){let e=t+0,r=t+1,i=t+2;n.push(e,r,r,i,i,e)}}let s=new(i.count>=65535?iT:rT)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.version<n.version&&l(e)}else l(e);return a.get(e)}return{get:s,update:c,getWireframeAttribute:u}}function UD(e,t,n){let r;function i(e){r=e}let a,o;function s(e){a=e.type,o=e.bytesPerElement}function c(t,i){e.drawElements(r,i,a,t*o),n.update(i,r,1)}function l(t,i,s){s!==0&&(e.drawElementsInstanced(r,i,a,t*o,s),n.update(i,r,s))}function u(e,i,o){if(o===0)return;t.get(`WEBGL_multi_draw`).multiDrawElementsWEBGL(r,i,0,a,e,0,o);let s=0;for(let e=0;e<o;e++)s+=i[e];n.update(s,r,1)}this.setMode=i,this.setIndex=s,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function WD(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(t,r,i){switch(n.calls++,r){case e.TRIANGLES:n.triangles+=t/3*i;break;case e.LINES:n.lines+=t/2*i;break;case e.LINE_STRIP:n.lines+=i*(t-1);break;case e.LINE_LOOP:n.lines+=i*t;break;case e.POINTS:n.points+=i*t;break;default:J(`WebGLInfo: Unknown draw mode:`,r)}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:i,update:r}}function GD(e,t,n){let r=/* @__PURE__ */ new WeakMap,i=new FC;function a(a,o,s){let c=a.morphTargetInfluences,l=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=l===void 0?0:l.length,d=r.get(o);if(d===void 0||d.count!==u){d!==void 0&&d.texture.dispose();let e=o.morphAttributes.position!==void 0,n=o.morphAttributes.normal!==void 0,a=o.morphAttributes.color!==void 0,s=o.morphAttributes.position||[],c=o.morphAttributes.normal||[],l=o.morphAttributes.color||[],f=0;e===!0&&(f=1),n===!0&&(f=2),a===!0&&(f=3);let p=o.attributes.position.count*f,m=1;p>t.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let h=new Float32Array(p*m*4*u),g=new RC(h,p,m,u);g.type=Ix,g.needsUpdate=!0;let _=f*4;for(let t=0;t<u;t++){let r=s[t],o=c[t],u=l[t],d=p*m*4*t;for(let t=0;t<r.count;t++){let s=t*_;e===!0&&(i.fromBufferAttribute(r,t),h[d+s+0]=i.x,h[d+s+1]=i.y,h[d+s+2]=i.z,h[d+s+3]=0),n===!0&&(i.fromBufferAttribute(o,t),h[d+s+4]=i.x,h[d+s+5]=i.y,h[d+s+6]=i.z,h[d+s+7]=0),a===!0&&(i.fromBufferAttribute(u,t),h[d+s+8]=i.x,h[d+s+9]=i.y,h[d+s+10]=i.z,h[d+s+11]=u.itemSize===4?i.w:1)}}d={count:u,texture:g,size:new Y(p,m)},r.set(o,d);function v(){g.dispose(),r.delete(o),o.removeEventListener(`dispose`,v)}o.addEventListener(`dispose`,v)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)s.getUniforms().setValue(e,`morphTexture`,a.morphTexture,n);else{let t=0;for(let e=0;e<c.length;e++)t+=c[e];let n=o.morphTargetsRelative?1:1-t;s.getUniforms().setValue(e,`morphTargetBaseInfluence`,n),s.getUniforms().setValue(e,`morphTargetInfluences`,c)}s.getUniforms().setValue(e,`morphTargetsTexture`,d.texture,n),s.getUniforms().setValue(e,`morphTargetsTextureSize`,d.size)}return{update:a}}function KD(e,t,n,r,i){let a=/* @__PURE__ */ new WeakMap;function o(r){let o=i.render.frame,s=r.geometry,l=t.get(r,s);if(a.get(l)!==o&&(t.update(l),a.set(l,o)),r.isInstancedMesh&&(r.hasEventListener(`dispose`,c)===!1&&r.addEventListener(`dispose`,c),a.get(r)!==o&&(n.update(r.instanceMatrix,e.ARRAY_BUFFER),r.instanceColor!==null&&n.update(r.instanceColor,e.ARRAY_BUFFER),a.set(r,o))),r.isSkinnedMesh){let e=r.skeleton;a.get(e)!==o&&(e.update(),a.set(e,o))}return l}function s(){a=/* @__PURE__ */ new WeakMap}function c(e){let t=e.target;t.removeEventListener(`dispose`,c),r.releaseStatesOfObject(t),n.remove(t.instanceMatrix),t.instanceColor!==null&&n.remove(t.instanceColor)}return{update:o,dispose:s}}var qD={1:`LINEAR_TONE_MAPPING`,2:`REINHARD_TONE_MAPPING`,3:`CINEON_TONE_MAPPING`,4:`ACES_FILMIC_TONE_MAPPING`,6:`AGX_TONE_MAPPING`,7:`NEUTRAL_TONE_MAPPING`,5:`CUSTOM_TONE_MAPPING`};function JD(e,t,n,r,i,a){let o=new LC(t,n,{type:e,depthBuffer:i,stencilBuffer:a,samples:r?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),s=null,c=null,l=new _T;l.setAttribute(`position`,new aT([-1,3,0,-1,-1,0,3,-1,0],3)),l.setAttribute(`uv`,new aT([0,2,0,0,2,0],2));let u=new fE({uniforms:{tDiffuse:{value:null}},vertexShader:`
|
|
4076
4075
|
precision highp float;
|
|
4077
4076
|
|
|
4078
4077
|
uniform mat4 modelViewMatrix;
|
|
@@ -4118,17 +4117,17 @@ void main() {
|
|
|
4118
4117
|
#ifdef SRGB_TRANSFER
|
|
4119
4118
|
gl_FragColor = sRGBTransferOETF( gl_FragColor );
|
|
4120
4119
|
#endif
|
|
4121
|
-
}`,depthTest:!1,depthWrite:!1}),d=new
|
|
4120
|
+
}`,depthTest:!1,depthWrite:!1}),d=new VT(l,u),f=new HE(-1,1,1,-1,0,1),p=null,m=null,h=!1,g,_=null,v=[],y=!1;this.setSize=function(e,t){o.setSize(e,t),s!==null&&s.setSize(e,t),c!==null&&c.setSize(e,t);for(let n=0;n<v.length;n++){let r=v[n];r.setSize&&r.setSize(e,t)}},this.setEffects=function(e){v=e,y=v.length>0&&v[0].isRenderPass===!0;let t=o.width,n=o.height;v.length>0&&s===null&&(s=new LC(t,n,{type:Lx,depthBuffer:!1,stencilBuffer:!1}),c=new LC(t,n,{type:Lx,depthBuffer:!1,stencilBuffer:!1}));for(let e=0;e<v.length;e++){let r=v[e];r.setSize&&r.setSize(t,n)}},this.begin=function(e,t){if(h||e.toneMapping===0&&v.length===0)return!1;if(_=t,t!==null){let e=t.width,n=t.height;(o.width!==e||o.height!==n)&&this.setSize(e,n)}return y===!1&&e.setRenderTarget(o),g=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return y},this.end=function(e,t){e.toneMapping=g,h=!0;let n=o,r=s;for(let i=0;i<v.length;i++){let a=v[i];a.enabled!==!1&&(a.render(e,r,n,t),a.needsSwap!==!1&&(n=r,r=r===s?c:s))}if(p!==e.outputColorSpace||m!==e.toneMapping){p=e.outputColorSpace,m=e.toneMapping,u.defines={},wC.getTransfer(p)===`srgb`&&(u.defines.SRGB_TRANSFER=``);let t=qD[m];t&&(u.defines[t]=``),u.needsUpdate=!0}u.uniforms.tDiffuse.value=n.texture,e.setRenderTarget(_),e.render(d,f),_=null,h=!1},this.isCompositing=function(){return h},this.dispose=function(){o.dispose(),s!==null&&s.dispose(),c!==null&&c.dispose(),l.dispose(),u.dispose()}}var YD=/*@__PURE__*/ new PC,XD=/*@__PURE__*/ new QT(1,1),ZD=/*@__PURE__*/ new RC,QD=/*@__PURE__*/ new zC,$D=/*@__PURE__*/ new ZT,eO=[],tO=[],nO=/* @__PURE__ */ new Float32Array(16),rO=/* @__PURE__ */ new Float32Array(9),iO=/* @__PURE__ */ new Float32Array(4);function aO(e,t,n){let r=e[0];if(r<=0||r>0)return e;let i=t*n,a=eO[i];if(a===void 0&&(a=new Float32Array(i),eO[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function oO(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function sO(e,t){for(let n=0,r=t.length;n<r;n++)e[n]=t[n]}function cO(e,t){let n=tO[t];n===void 0&&(n=new Int32Array(t),tO[t]=n);for(let r=0;r!==t;++r)n[r]=e.allocateTextureUnit();return n}function lO(e,t){let n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function uO(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(oO(n,t))return;e.uniform2fv(this.addr,t),sO(n,t)}}function dO(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(t.r!==void 0)(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(oO(n,t))return;e.uniform3fv(this.addr,t),sO(n,t)}}function fO(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(oO(n,t))return;e.uniform4fv(this.addr,t),sO(n,t)}}function pO(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(oO(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),sO(n,t)}else{if(oO(n,r))return;iO.set(r),e.uniformMatrix2fv(this.addr,!1,iO),sO(n,r)}}function mO(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(oO(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),sO(n,t)}else{if(oO(n,r))return;rO.set(r),e.uniformMatrix3fv(this.addr,!1,rO),sO(n,r)}}function hO(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(oO(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),sO(n,t)}else{if(oO(n,r))return;nO.set(r),e.uniformMatrix4fv(this.addr,!1,nO),sO(n,r)}}function gO(e,t){let n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function _O(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(oO(n,t))return;e.uniform2iv(this.addr,t),sO(n,t)}}function vO(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(oO(n,t))return;e.uniform3iv(this.addr,t),sO(n,t)}}function yO(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(oO(n,t))return;e.uniform4iv(this.addr,t),sO(n,t)}}function bO(e,t){let n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function xO(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(oO(n,t))return;e.uniform2uiv(this.addr,t),sO(n,t)}}function SO(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(oO(n,t))return;e.uniform3uiv(this.addr,t),sO(n,t)}}function CO(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(oO(n,t))return;e.uniform4uiv(this.addr,t),sO(n,t)}}function wO(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i);let a;this.type===e.SAMPLER_2D_SHADOW?(XD.compareFunction=n.isReversedDepthBuffer()?518:515,a=XD):a=YD,n.setTexture2D(t||a,i)}function TO(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(t||QD,i)}function EO(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(t||$D,i)}function DO(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(t||ZD,i)}function OO(e){switch(e){case 5126:return lO;case 35664:return uO;case 35665:return dO;case 35666:return fO;case 35674:return pO;case 35675:return mO;case 35676:return hO;case 5124:case 35670:return gO;case 35667:case 35671:return _O;case 35668:case 35672:return vO;case 35669:case 35673:return yO;case 5125:return bO;case 36294:return xO;case 36295:return SO;case 36296:return CO;case 35678:case 36198:case 36298:case 36306:case 35682:return wO;case 35679:case 36299:case 36307:return TO;case 35680:case 36300:case 36308:case 36293:return EO;case 36289:case 36303:case 36311:case 36292:return DO}}function kO(e,t){e.uniform1fv(this.addr,t)}function AO(e,t){let n=aO(t,this.size,2);e.uniform2fv(this.addr,n)}function jO(e,t){let n=aO(t,this.size,3);e.uniform3fv(this.addr,n)}function MO(e,t){let n=aO(t,this.size,4);e.uniform4fv(this.addr,n)}function NO(e,t){let n=aO(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function PO(e,t){let n=aO(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function FO(e,t){let n=aO(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function IO(e,t){e.uniform1iv(this.addr,t)}function LO(e,t){e.uniform2iv(this.addr,t)}function RO(e,t){e.uniform3iv(this.addr,t)}function zO(e,t){e.uniform4iv(this.addr,t)}function BO(e,t){e.uniform1uiv(this.addr,t)}function VO(e,t){e.uniform2uiv(this.addr,t)}function HO(e,t){e.uniform3uiv(this.addr,t)}function UO(e,t){e.uniform4uiv(this.addr,t)}function WO(e,t,n){let r=this.cache,i=t.length,a=cO(n,i);oO(r,a)||(e.uniform1iv(this.addr,a),sO(r,a));let o;o=this.type===e.SAMPLER_2D_SHADOW?XD:YD;for(let e=0;e!==i;++e)n.setTexture2D(t[e]||o,a[e])}function GO(e,t,n){let r=this.cache,i=t.length,a=cO(n,i);oO(r,a)||(e.uniform1iv(this.addr,a),sO(r,a));for(let e=0;e!==i;++e)n.setTexture3D(t[e]||QD,a[e])}function KO(e,t,n){let r=this.cache,i=t.length,a=cO(n,i);oO(r,a)||(e.uniform1iv(this.addr,a),sO(r,a));for(let e=0;e!==i;++e)n.setTextureCube(t[e]||$D,a[e])}function qO(e,t,n){let r=this.cache,i=t.length,a=cO(n,i);oO(r,a)||(e.uniform1iv(this.addr,a),sO(r,a));for(let e=0;e!==i;++e)n.setTexture2DArray(t[e]||ZD,a[e])}function JO(e){switch(e){case 5126:return kO;case 35664:return AO;case 35665:return jO;case 35666:return MO;case 35674:return NO;case 35675:return PO;case 35676:return FO;case 5124:case 35670:return IO;case 35667:case 35671:return LO;case 35668:case 35672:return RO;case 35669:case 35673:return zO;case 5125:return BO;case 36294:return VO;case 36295:return HO;case 36296:return UO;case 35678:case 36198:case 36298:case 36306:case 35682:return WO;case 35679:case 36299:case 36307:return GO;case 35680:case 36300:case 36308:case 36293:return KO;case 36289:case 36303:case 36311:case 36292:return qO}}var YO=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=OO(t.type)}},XO=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=JO(t.type)}},ZO=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let r=this.seq;for(let i=0,a=r.length;i!==a;++i){let a=r[i];a.setValue(e,t[a.id],n)}}},QO=/(\w+)(\])?(\[|\.)?/g;function $O(e,t){e.seq.push(t),e.map[t.id]=t}function ek(e,t,n){let r=e.name,i=r.length;for(QO.lastIndex=0;;){let a=QO.exec(r),o=QO.lastIndex,s=a[1],c=a[2]===`]`,l=a[3];if(c&&(s|=0),l===void 0||l===`[`&&o+2===i){$O(n,l===void 0?new YO(s,e,t):new XO(s,e,t));break}{let e=n.map[s];e===void 0&&(e=new ZO(s),$O(n,e)),n=e}}}var tk=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){let n=e.getActiveUniform(t,r);ek(n,e.getUniformLocation(t,n.name),this)}let r=[],i=[];for(let t of this.seq)t.type===e.SAMPLER_2D_SHADOW||t.type===e.SAMPLER_CUBE_SHADOW||t.type===e.SAMPLER_2D_ARRAY_SHADOW?r.push(t):i.push(t);r.length>0&&(this.seq=r.concat(i))}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function nk(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var rk=37297,ik=0;function ak(e,t){let n=e.split(`
|
|
4122
4121
|
`),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e<a;e++){let i=e+1;r.push(`${i===t?`>`:` `} ${i}: ${n[e]}`)}return r.join(`
|
|
4123
|
-
`)}var
|
|
4122
|
+
`)}var ok=/*@__PURE__*/ new Z;function sk(e){wC._getMatrix(ok,wC.workingColorSpace,e);let t=`mat3( ${ok.elements.map(e=>e.toFixed(4))} )`;switch(wC.getTransfer(e)){case GS:return[t,`LinearTransferOETF`];case KS:return[t,`sRGBTransferOETF`];default:return q(`WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function ck(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+`
|
|
4124
4123
|
|
|
4125
4124
|
`+i+`
|
|
4126
4125
|
|
|
4127
|
-
`+
|
|
4128
|
-
`)}var
|
|
4129
|
-
`)}function
|
|
4130
|
-
`)}function
|
|
4131
|
-
`)}function
|
|
4126
|
+
`+ak(e.getShaderSource(t),r)}return i}function lk(e,t){let n=sk(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(`
|
|
4127
|
+
`)}var uk={1:`Linear`,2:`Reinhard`,3:`Cineon`,4:`ACESFilmic`,6:`AgX`,7:`Neutral`,5:`Custom`};function dk(e,t){let n=uk[t];return n===void 0?(q(`WebGLProgram: Unsupported toneMapping:`,t),`vec3 `+e+`( vec3 color ) { return LinearToneMapping( color ); }`):`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var fk=/*@__PURE__*/ new X;function pk(){return wC.getLuminanceCoefficients(fk),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${fk.x.toFixed(4)}, ${fk.y.toFixed(4)}, ${fk.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(`
|
|
4128
|
+
`)}function mk(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(_k).join(`
|
|
4129
|
+
`)}function hk(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(`
|
|
4130
|
+
`)}function gk(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){let r=e.getActiveAttrib(t,i),a=r.name,o=1;r.type===e.FLOAT_MAT2&&(o=2),r.type===e.FLOAT_MAT3&&(o=3),r.type===e.FLOAT_MAT4&&(o=4),n[a]={type:r.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function _k(e){return e!==``}function vk(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_SUN_LIGHTS/g,t.numSunLights).replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_SUN_LIGHT_SHADOWS/g,t.numSunLightShadows).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function yk(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var bk=/^[ \t]*#include +<([\w\d./]+)>/gm;function xk(e){return e.replace(bk,Ck)}var Sk=/* @__PURE__ */ new Map;function Ck(e,t){let n=Q[t];if(n===void 0){let e=Sk.get(t);if(e!==void 0)n=Q[e],q(`WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`THREE.WebGLProgram: Can not resolve #include <`+t+`>`)}return xk(n)}var wk=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Tk(e){return e.replace(wk,Ek)}function Ek(e,t,n,r){let i=``;for(let e=parseInt(t);e<parseInt(n);e++)i+=r.replace(/\[\s*i\s*\]/g,`[ `+e+` ]`).replace(/UNROLLED_LOOP_INDEX/g,e);return i}function Dk(e){let t=`precision ${e.precision} float;
|
|
4132
4131
|
precision ${e.precision} int;
|
|
4133
4132
|
precision ${e.precision} sampler2D;
|
|
4134
4133
|
precision ${e.precision} samplerCube;
|
|
@@ -4148,30 +4147,30 @@ void main() {
|
|
|
4148
4147
|
`;return e.precision===`highp`?t+=`
|
|
4149
4148
|
#define HIGH_PRECISION`:e.precision===`mediump`?t+=`
|
|
4150
4149
|
#define MEDIUM_PRECISION`:e.precision===`lowp`&&(t+=`
|
|
4151
|
-
#define LOW_PRECISION`),t}var
|
|
4152
|
-
`:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(
|
|
4150
|
+
#define LOW_PRECISION`),t}var Ok={1:`SHADOWMAP_TYPE_PCF`,3:`SHADOWMAP_TYPE_VSM`};function kk(e){return Ok[e.shadowMapType]||`SHADOWMAP_TYPE_BASIC`}var Ak={301:`ENVMAP_TYPE_CUBE`,302:`ENVMAP_TYPE_CUBE`,306:`ENVMAP_TYPE_CUBE_UV`};function jk(e){return e.envMap===!1?`ENVMAP_TYPE_CUBE`:Ak[e.envMapMode]||`ENVMAP_TYPE_CUBE`}var Mk={302:`ENVMAP_MODE_REFRACTION`};function Nk(e){return e.envMap===!1?`ENVMAP_MODE_REFLECTION`:Mk[e.envMapMode]||`ENVMAP_MODE_REFLECTION`}var Pk={0:`ENVMAP_BLENDING_MULTIPLY`,1:`ENVMAP_BLENDING_MIX`,2:`ENVMAP_BLENDING_ADD`};function Fk(e){return e.envMap===!1?`ENVMAP_BLENDING_NONE`:Pk[e.combine]||`ENVMAP_BLENDING_NONE`}function Ik(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(2**n,112)),texelHeight:r,maxMip:n}}function Lk(e,t,n,r){let i=e.getContext(),a=n.defines,o=n.vertexShader,s=n.fragmentShader,c=kk(n),l=jk(n),u=Nk(n),d=Fk(n),f=Ik(n),p=mk(n),m=hk(a),h=i.createProgram(),g,_,v=n.glslVersion?`#version `+n.glslVersion+`
|
|
4151
|
+
`:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(_k).join(`
|
|
4153
4152
|
`),g.length>0&&(g+=`
|
|
4154
|
-
`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(
|
|
4153
|
+
`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(_k).join(`
|
|
4155
4154
|
`),_.length>0&&(_+=`
|
|
4156
|
-
`)):(g=[
|
|
4157
|
-
`].filter(
|
|
4158
|
-
`),_=[
|
|
4159
|
-
`].filter(
|
|
4160
|
-
`)),o=
|
|
4155
|
+
`)):(g=[Dk(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexNormals?`#define HAS_NORMAL`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` attribute mat4 instanceMatrix;`,`#endif`,`#ifdef USE_INSTANCING_COLOR`,` attribute vec3 instanceColor;`,`#endif`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#endif`,`attribute vec3 position;`,`attribute vec3 normal;`,`attribute vec2 uv;`,`#ifdef USE_UV1`,` attribute vec2 uv1;`,`#endif`,`#ifdef USE_UV2`,` attribute vec2 uv2;`,`#endif`,`#ifdef USE_UV3`,` attribute vec2 uv3;`,`#endif`,`#ifdef USE_TANGENT`,` attribute vec4 tangent;`,`#endif`,`#if defined( USE_COLOR_ALPHA )`,` attribute vec4 color;`,`#elif defined( USE_COLOR )`,` attribute vec3 color;`,`#endif`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,`
|
|
4156
|
+
`].filter(_k).join(`
|
|
4157
|
+
`),_=[Dk(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.packedNormalMap?`#define USE_PACKED_NORMALMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.retroreflection?`#define USE_RETROREFLECTION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor?`#define USE_COLOR`:``,n.vertexAlphas||n.batchingColor?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.numLightProbeGrids>0?`#define USE_LIGHT_PROBES_GRID`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:Q.tonemapping_pars_fragment,n.toneMapping===0?``:dk(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,Q.colorspace_pars_fragment,lk(`linearToOutputTexel`,n.outputColorSpace),pk(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,`
|
|
4158
|
+
`].filter(_k).join(`
|
|
4159
|
+
`)),o=xk(o),o=vk(o,n),o=yk(o,n),s=xk(s),s=vk(s,n),s=yk(s,n),o=Tk(o),s=Tk(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es
|
|
4161
4160
|
`,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(`
|
|
4162
4161
|
`)+`
|
|
4163
4162
|
`+g,_=[`#define varying in`,n.glslVersion===`300 es`?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===`300 es`?``:`#define gl_FragColor pc_fragColor`,`#define gl_FragDepthEXT gl_FragDepth`,`#define texture2D texture`,`#define textureCube texture`,`#define texture2DProj textureProj`,`#define texture2DLodEXT textureLod`,`#define texture2DProjLodEXT textureProjLod`,`#define textureCubeLodEXT textureLod`,`#define texture2DGradEXT textureGrad`,`#define texture2DProjGradEXT textureProjGrad`,`#define textureCubeGradEXT textureGrad`].join(`
|
|
4164
4163
|
`)+`
|
|
4165
|
-
`+_);let y=v+g+o,b=v+_+s,x=
|
|
4164
|
+
`+_);let y=v+g+o,b=v+_+s,x=nk(i,i.VERTEX_SHADER,y),S=nk(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.hasPositionAttribute===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1){if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=ck(i,x,`vertex`),n=ck(i,S,`fragment`);J(`WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+`
|
|
4166
4165
|
|
|
4167
4166
|
Material Name: `+t.name+`
|
|
4168
4167
|
Material Type: `+t.type+`
|
|
4169
4168
|
|
|
4170
4169
|
Program Info Log: `+o+`
|
|
4171
4170
|
`+e+`
|
|
4172
|
-
`+n)}}else o===``?(s===``||c===``)&&(u=!1):J(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new Wj(i,h),T=aM(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,Kj)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=qj++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var DM=0,OM=class{constructor(){this.shaderCache=/* @__PURE__ */ new Map,this.materialCache=/* @__PURE__ */ new Map}update(e,t,n){let r=this._getShaderCacheForMaterial(e);return r.has(t)===!1&&(r.add(t),t.usedTimes++),r.has(n)===!1&&(r.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=/* @__PURE__ */ new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new kM(e),t.set(e,n)),n}},kM=class{constructor(e){this.id=DM++,this.code=e,this.usedTimes=0}};function AM(e){return e===1030||e===37490||e===36285}function jM(e,t,n,r,i,a){let o=new BE,s=new OM,c=/* @__PURE__ */ new Set,l=[],u=/* @__PURE__ */ new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&J(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,ee,k;if(C){let e=Qk[C];D=e.vertexShader,O=e.fragmentShader}else{D=i.vertexShader,O=i.fragmentShader;let e=s.getVertexShaderStage(i),t=s.getFragmentShaderStage(i);s.update(i,e,t),ee=e.id,k=t.id}let te=e.getRenderTarget(),ne=e.state.buffers.depth.getReversed(),A=h.isInstancedMesh===!0,re=h.isBatchedMesh===!0,ie=!!i.map,ae=!!i.matcap,oe=!!x,j=!!i.aoMap,se=!!i.lightMap,ce=!!i.bumpMap&&i.wireframe===!1,le=!!i.normalMap,ue=!!i.displacementMap,de=!!i.emissiveMap,fe=!!i.metalnessMap,pe=!!i.roughnessMap,me=i.anisotropy>0,he=i.clearcoat>0,ge=i.dispersion>0,_e=i.retroreflectivity>0,ve=i.iridescence>0,ye=i.sheen>0,be=i.transmission>0,xe=me&&!!i.anisotropyMap,Se=he&&!!i.clearcoatMap,Ce=he&&!!i.clearcoatNormalMap,we=he&&!!i.clearcoatRoughnessMap,Te=ve&&!!i.iridescenceMap,M=ve&&!!i.iridescenceThicknessMap,Ee=ye&&!!i.sheenColorMap,De=ye&&!!i.sheenRoughnessMap,Oe=!!i.specularMap,N=!!i.specularColorMap,ke=!!i.specularIntensityMap,P=be&&!!i.transmissionMap,Ae=be&&!!i.thicknessMap,je=!!i.gradientMap,Me=!!i.alphaMap,Ne=i.alphaTest>0,Pe=!!i.alphaHash,Fe=!!i.extensions,Ie=0;i.toneMapped&&(te===null||te.isXRRenderTarget===!0)&&(Ie=e.toneMapping);let Le={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:ee,customFragmentShaderID:k,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:re,batchingColor:re&&h._colorsTexture!==null,instancing:A,instancingColor:A&&h.instanceColor!==null,instancingMorph:A&&h.morphTexture!==null,outputColorSpace:te===null?e.outputColorSpace:te.isXRRenderTarget===!0?te.texture.colorSpace:pE.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:ie,matcap:ae,envMap:oe,envMapMode:oe&&x.mapping,envMapCubeUVHeight:S,aoMap:j,lightMap:se,bumpMap:ce,normalMap:le,displacementMap:ue,emissiveMap:de,normalMapObjectSpace:le&&i.normalMapType===1,normalMapTangentSpace:le&&i.normalMapType===0,packedNormalMap:le&&i.normalMapType===0&&AM(i.normalMap.format),metalnessMap:fe,roughnessMap:pe,anisotropy:me,anisotropyMap:xe,clearcoat:he,clearcoatMap:Se,clearcoatNormalMap:Ce,clearcoatRoughnessMap:we,dispersion:ge,retroreflection:_e,iridescence:ve,iridescenceMap:Te,iridescenceThicknessMap:M,sheen:ye,sheenColorMap:Ee,sheenRoughnessMap:De,specularMap:Oe,specularColorMap:N,specularIntensityMap:ke,transmission:be,transmissionMap:P,thicknessMap:Ae,gradientMap:je,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:Me,alphaTest:Ne,alphaHash:Pe,combine:i.combine,mapUv:ie&&m(i.map.channel),aoMapUv:j&&m(i.aoMap.channel),lightMapUv:se&&m(i.lightMap.channel),bumpMapUv:ce&&m(i.bumpMap.channel),normalMapUv:le&&m(i.normalMap.channel),displacementMapUv:ue&&m(i.displacementMap.channel),emissiveMapUv:de&&m(i.emissiveMap.channel),metalnessMapUv:fe&&m(i.metalnessMap.channel),roughnessMapUv:pe&&m(i.roughnessMap.channel),anisotropyMapUv:xe&&m(i.anisotropyMap.channel),clearcoatMapUv:Se&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:Ce&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:we&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:Te&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:M&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:Ee&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:De&&m(i.sheenRoughnessMap.channel),specularMapUv:Oe&&m(i.specularMap.channel),specularColorMapUv:N&&m(i.specularColorMap.channel),specularIntensityMapUv:ke&&m(i.specularIntensityMap.channel),transmissionMapUv:P&&m(i.transmissionMap.channel),thicknessMapUv:Ae&&m(i.thicknessMap.channel),alphaMapUv:Me&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(le||me),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(ie||Me),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&le===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ne,skinning:h.isSkinnedMesh===!0,hasPositionAttribute:v.attributes.position!==void 0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numSunLights:o.sun.length,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numSunLightShadows:o.sunShadowMap.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Ie,decodeVideoTexture:ie&&i.map.isVideoTexture===!0&&pE.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:de&&i.emissiveMap.isVideoTexture===!0&&pE.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:Fe&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Fe&&i.extensions.multiDraw===!0||re)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Le.vertexUv1s=c.has(1),Le.vertexUv2s=c.has(2),Le.vertexUv3s=c.has(3),c.clear(),Le}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numSunLights),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numSunLightShadows),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.retroreflection&&o.enable(24),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),t.hasPositionAttribute&&o.enable(23),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=Qk[t];n=ZO.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new EM(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function MM(){let e=/* @__PURE__ */ new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=/* @__PURE__ */ new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function NM(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function PM(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function FM(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l,u){u.reversedDepth===!0&&(c=-c);let d=s(e,t,a,o,c,l);a.transmission>0?r.push(d):a.transparent===!0?i.push(d):n.push(d)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||NM),r.length>1&&r.sort(t||PM),i.length>1&&i.sort(t||PM)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function IM(){let e=/* @__PURE__ */ new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new FM,e.set(t,[i])):n>=r.length?(i=new FM,r.push(i)):i=r[n],i}function n(){e=/* @__PURE__ */ new WeakMap}return{get:t,dispose:n}}function LM(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={direction:new X,color:new uD};break;case`SpotLight`:n={position:new X,direction:new X,color:new uD,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new X,color:new uD,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new X,skyColor:new uD,groundColor:new uD};break;case`RectAreaLight`:n={color:new uD,position:new X,halfWidth:new X,halfHeight:new X}}return e[t.id]=n,n}}}function RM(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new aE};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new aE};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new aE,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}var zM=0;function BM(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function VM(e){let t=new LM,n=RM(),r={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new X);let i=new X,a=new kE,o=new kE;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0;i.sort(BM);for(let e=0,S=i.length;e<S;e++){let S=i[e],C=S.color,w=S.intensity,T=S.distance,E=null;if(S.shadow&&S.shadow.map&&(E=S.shadow.map.texture.format===1030?S.shadow.map.texture:S.shadow.map.depthTexture||S.shadow.map.texture),S.isAmbientLight)a+=C.r*w,o+=C.g*w,s+=C.b*w;else if(S.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(S.sh.coefficients[e],w);x++}else if(S.isSunLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize.copy(e.mapSize).multiply(e.getFrameExtents()),r.sunShadow[l]=t,r.sunShadowMap[l]=E;let i=e.getViewportCount();for(let t=0;t<i;t++)r.sunShadowMatrix[u+t]=e.getMatrix(t),r.sunShadowCascade[u+t]=e._cascadeData[t];u+=i,l++}r.sun[c]=e,c++}else if(S.isDirectionalLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[d]=t,r.directionalShadowMap[d]=E,r.directionalShadowMatrix[d]=S.shadow.matrix,g++}r.directional[d]=e,d++}else if(S.isSpotLight){let e=t.get(S);e.position.setFromMatrixPosition(S.matrixWorld),e.color.copy(C).multiplyScalar(w),e.distance=T,e.coneCos=Math.cos(S.angle),e.penumbraCos=Math.cos(S.angle*(1-S.penumbra)),e.decay=S.decay,r.spot[p]=e;let i=S.shadow;if(S.map&&(r.spotLightMap[y]=S.map,y++,i.updateMatrices(S),S.castShadow&&b++),r.spotLightMatrix[p]=i.matrix,S.castShadow){let e=n.get(S);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[p]=e,r.spotShadowMap[p]=E,v++}p++}else if(S.isRectAreaLight){let e=t.get(S);e.color.copy(C).multiplyScalar(w),e.halfWidth.set(S.width*.5,0,0),e.halfHeight.set(0,S.height*.5,0),r.rectArea[m]=e,m++}else if(S.isPointLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),e.distance=S.distance,e.decay=S.decay,S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[f]=t,r.pointShadowMap[f]=E,r.pointShadowMatrix[f]=S.shadow.matrix,_++}r.point[f]=e,f++}else if(S.isHemisphereLight){let e=t.get(S);e.skyColor.copy(S.color).multiplyScalar(w),e.groundColor.copy(S.groundColor).multiplyScalar(w),r.hemi[h]=e,h++}}m>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=$.LTC_FLOAT_1,r.rectAreaLTC2=$.LTC_FLOAT_2):(r.rectAreaLTC1=$.LTC_HALF_1,r.rectAreaLTC2=$.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let S=r.hash;(S.sunLength!==c||S.directionalLength!==d||S.pointLength!==f||S.spotLength!==p||S.rectAreaLength!==m||S.hemiLength!==h||S.numSunShadows!==l||S.numDirectionalShadows!==g||S.numPointShadows!==_||S.numSpotShadows!==v||S.numSpotMaps!==y||S.numLightProbes!==x)&&(r.sun.length=c,r.directional.length=d,r.spot.length=p,r.rectArea.length=m,r.point.length=f,r.hemi.length=h,r.sunShadow.length=l,r.sunShadowMap.length=l,r.sunShadowMatrix.length=u,r.sunShadowCascade.length=u,r.directionalShadow.length=g,r.directionalShadowMap.length=g,r.directionalShadowMatrix.length=g,r.pointShadow.length=_,r.pointShadowMap.length=_,r.pointShadowMatrix.length=_,r.spotShadow.length=v,r.spotShadowMap.length=v,r.spotLightMatrix.length=v+y-b,r.spotLightMap.length=y,r.numSpotLightShadowsWithMaps=b,r.numLightProbes=x,S.sunLength=c,S.directionalLength=d,S.pointLength=f,S.spotLength=p,S.rectAreaLength=m,S.hemiLength=h,S.numSunShadows=l,S.numDirectionalShadows=g,S.numPointShadows=_,S.numSpotShadows=v,S.numSpotMaps=y,S.numLightProbes=x,r.version=zM++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=0,f=t.matrixWorldInverse;for(let t=0,p=e.length;t<p;t++){let p=e[t];if(p.isSunLight){let e=r.sun[n];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),n++}else if(p.isDirectionalLight){let e=r.directional[s];e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),s++}else if(p.isSpotLight){let e=r.spot[l];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),l++}else if(p.isRectAreaLight){let e=r.rectArea[u];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),o.identity(),a.copy(p.matrixWorld),a.premultiply(f),o.extractRotation(a),e.halfWidth.set(p.width*.5,0,0),e.halfHeight.set(0,p.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),u++}else if(p.isPointLight){let e=r.point[c];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),c++}else if(p.isHemisphereLight){let e=r.hemi[d];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),d++}}}return{setup:s,setupView:c,state:r}}function HM(e){let t=new VM(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function UM(e){let t=/* @__PURE__ */ new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new HM(e),t.set(n,[a])):r>=i.length?(a=new HM(e),i.push(a)):a=i[r],a}function r(){t=/* @__PURE__ */ new WeakMap}return{get:n,dispose:r}}var WM=`void main() {
|
|
4171
|
+
`+n)}}else o===``?(s===``||c===``)&&(u=!1):q(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new tk(i,h),T=gk(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,rk)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=ik++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Rk=0,zk=class{constructor(){this.shaderCache=/* @__PURE__ */ new Map,this.materialCache=/* @__PURE__ */ new Map}update(e,t,n){let r=this._getShaderCacheForMaterial(e);return r.has(t)===!1&&(r.add(t),t.usedTimes++),r.has(n)===!1&&(r.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=/* @__PURE__ */ new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Bk(e),t.set(e,n)),n}},Bk=class{constructor(e){this.id=Rk++,this.code=e,this.usedTimes=0}};function Vk(e){return e===1030||e===37490||e===36285}function Hk(e,t,n,r,i,a){let o=new ZC,s=new zk,c=/* @__PURE__ */ new Set,l=[],u=/* @__PURE__ */ new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&q(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,k,A;if(C){let e=lD[C];D=e.vertexShader,O=e.fragmentShader}else{D=i.vertexShader,O=i.fragmentShader;let e=s.getVertexShaderStage(i),t=s.getFragmentShaderStage(i);s.update(i,e,t),k=e.id,A=t.id}let ee=e.getRenderTarget(),te=e.state.buffers.depth.getReversed(),j=h.isInstancedMesh===!0,ne=h.isBatchedMesh===!0,re=!!i.map,M=!!i.matcap,ie=!!x,N=!!i.aoMap,ae=!!i.lightMap,oe=!!i.bumpMap&&i.wireframe===!1,se=!!i.normalMap,ce=!!i.displacementMap,le=!!i.emissiveMap,ue=!!i.metalnessMap,de=!!i.roughnessMap,fe=i.anisotropy>0,pe=i.clearcoat>0,me=i.dispersion>0,he=i.retroreflectivity>0,ge=i.iridescence>0,_e=i.sheen>0,ve=i.transmission>0,ye=fe&&!!i.anisotropyMap,be=pe&&!!i.clearcoatMap,xe=pe&&!!i.clearcoatNormalMap,Se=pe&&!!i.clearcoatRoughnessMap,Ce=ge&&!!i.iridescenceMap,P=ge&&!!i.iridescenceThicknessMap,we=_e&&!!i.sheenColorMap,Te=_e&&!!i.sheenRoughnessMap,Ee=!!i.specularMap,F=!!i.specularColorMap,De=!!i.specularIntensityMap,I=ve&&!!i.transmissionMap,L=ve&&!!i.thicknessMap,Oe=!!i.gradientMap,ke=!!i.alphaMap,Ae=i.alphaTest>0,je=!!i.alphaHash,Me=!!i.extensions,Ne=0;i.toneMapped&&(ee===null||ee.isXRRenderTarget===!0)&&(Ne=e.toneMapping);let Pe={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:k,customFragmentShaderID:A,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:ne,batchingColor:ne&&h._colorsTexture!==null,instancing:j,instancingColor:j&&h.instanceColor!==null,instancingMorph:j&&h.morphTexture!==null,outputColorSpace:ee===null?e.outputColorSpace:ee.isXRRenderTarget===!0?ee.texture.colorSpace:wC.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:re,matcap:M,envMap:ie,envMapMode:ie&&x.mapping,envMapCubeUVHeight:S,aoMap:N,lightMap:ae,bumpMap:oe,normalMap:se,displacementMap:ce,emissiveMap:le,normalMapObjectSpace:se&&i.normalMapType===1,normalMapTangentSpace:se&&i.normalMapType===0,packedNormalMap:se&&i.normalMapType===0&&Vk(i.normalMap.format),metalnessMap:ue,roughnessMap:de,anisotropy:fe,anisotropyMap:ye,clearcoat:pe,clearcoatMap:be,clearcoatNormalMap:xe,clearcoatRoughnessMap:Se,dispersion:me,retroreflection:he,iridescence:ge,iridescenceMap:Ce,iridescenceThicknessMap:P,sheen:_e,sheenColorMap:we,sheenRoughnessMap:Te,specularMap:Ee,specularColorMap:F,specularIntensityMap:De,transmission:ve,transmissionMap:I,thicknessMap:L,gradientMap:Oe,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:ke,alphaTest:Ae,alphaHash:je,combine:i.combine,mapUv:re&&m(i.map.channel),aoMapUv:N&&m(i.aoMap.channel),lightMapUv:ae&&m(i.lightMap.channel),bumpMapUv:oe&&m(i.bumpMap.channel),normalMapUv:se&&m(i.normalMap.channel),displacementMapUv:ce&&m(i.displacementMap.channel),emissiveMapUv:le&&m(i.emissiveMap.channel),metalnessMapUv:ue&&m(i.metalnessMap.channel),roughnessMapUv:de&&m(i.roughnessMap.channel),anisotropyMapUv:ye&&m(i.anisotropyMap.channel),clearcoatMapUv:be&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:xe&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Se&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:Ce&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:P&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:we&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:Te&&m(i.sheenRoughnessMap.channel),specularMapUv:Ee&&m(i.specularMap.channel),specularColorMapUv:F&&m(i.specularColorMap.channel),specularIntensityMapUv:De&&m(i.specularIntensityMap.channel),transmissionMapUv:I&&m(i.transmissionMap.channel),thicknessMapUv:L&&m(i.thicknessMap.channel),alphaMapUv:ke&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(se||fe),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(re||ke),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&se===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:te,skinning:h.isSkinnedMesh===!0,hasPositionAttribute:v.attributes.position!==void 0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numSunLights:o.sun.length,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numSunLightShadows:o.sunShadowMap.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Ne,decodeVideoTexture:re&&i.map.isVideoTexture===!0&&wC.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:le&&i.emissiveMap.isVideoTexture===!0&&wC.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:Me&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Me&&i.extensions.multiDraw===!0||ne)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Pe.vertexUv1s=c.has(1),Pe.vertexUv2s=c.has(2),Pe.vertexUv3s=c.has(3),c.clear(),Pe}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numSunLights),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numSunLightShadows),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.retroreflection&&o.enable(24),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),t.hasPositionAttribute&&o.enable(23),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=lD[t];n=cE.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new Lk(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function Uk(){let e=/* @__PURE__ */ new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=/* @__PURE__ */ new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function Wk(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Gk(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Kk(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l,u){u.reversedDepth===!0&&(c=-c);let d=s(e,t,a,o,c,l);a.transmission>0?r.push(d):a.transparent===!0?i.push(d):n.push(d)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||Wk),r.length>1&&r.sort(t||Gk),i.length>1&&i.sort(t||Gk)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function qk(){let e=/* @__PURE__ */ new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new Kk,e.set(t,[i])):n>=r.length?(i=new Kk,r.push(i)):i=r[n],i}function n(){e=/* @__PURE__ */ new WeakMap}return{get:t,dispose:n}}function Jk(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={direction:new X,color:new xw};break;case`SpotLight`:n={position:new X,direction:new X,color:new xw,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new X,color:new xw,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new X,skyColor:new xw,groundColor:new xw};break;case`RectAreaLight`:n={color:new xw,position:new X,halfWidth:new X,halfHeight:new X}}return e[t.id]=n,n}}}function Yk(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}var Xk=0;function Zk(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function Qk(e){let t=new Jk,n=Yk(),r={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new X);let i=new X,a=new BC,o=new BC;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0;i.sort(Zk);for(let e=0,S=i.length;e<S;e++){let S=i[e],C=S.color,w=S.intensity,T=S.distance,E=null;if(S.shadow&&S.shadow.map&&(E=S.shadow.map.texture.format===1030?S.shadow.map.texture:S.shadow.map.depthTexture||S.shadow.map.texture),S.isAmbientLight)a+=C.r*w,o+=C.g*w,s+=C.b*w;else if(S.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(S.sh.coefficients[e],w);x++}else if(S.isSunLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize.copy(e.mapSize).multiply(e.getFrameExtents()),r.sunShadow[l]=t,r.sunShadowMap[l]=E;let i=e.getViewportCount();for(let t=0;t<i;t++)r.sunShadowMatrix[u+t]=e.getMatrix(t),r.sunShadowCascade[u+t]=e._cascadeData[t];u+=i,l++}r.sun[c]=e,c++}else if(S.isDirectionalLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[d]=t,r.directionalShadowMap[d]=E,r.directionalShadowMatrix[d]=S.shadow.matrix,g++}r.directional[d]=e,d++}else if(S.isSpotLight){let e=t.get(S);e.position.setFromMatrixPosition(S.matrixWorld),e.color.copy(C).multiplyScalar(w),e.distance=T,e.coneCos=Math.cos(S.angle),e.penumbraCos=Math.cos(S.angle*(1-S.penumbra)),e.decay=S.decay,r.spot[p]=e;let i=S.shadow;if(S.map&&(r.spotLightMap[y]=S.map,y++,i.updateMatrices(S),S.castShadow&&b++),r.spotLightMatrix[p]=i.matrix,S.castShadow){let e=n.get(S);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[p]=e,r.spotShadowMap[p]=E,v++}p++}else if(S.isRectAreaLight){let e=t.get(S);e.color.copy(C).multiplyScalar(w),e.halfWidth.set(S.width*.5,0,0),e.halfHeight.set(0,S.height*.5,0),r.rectArea[m]=e,m++}else if(S.isPointLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),e.distance=S.distance,e.decay=S.decay,S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[f]=t,r.pointShadowMap[f]=E,r.pointShadowMatrix[f]=S.shadow.matrix,_++}r.point[f]=e,f++}else if(S.isHemisphereLight){let e=t.get(S);e.skyColor.copy(S.color).multiplyScalar(w),e.groundColor.copy(S.groundColor).multiplyScalar(w),r.hemi[h]=e,h++}}m>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=$.LTC_FLOAT_1,r.rectAreaLTC2=$.LTC_FLOAT_2):(r.rectAreaLTC1=$.LTC_HALF_1,r.rectAreaLTC2=$.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let S=r.hash;(S.sunLength!==c||S.directionalLength!==d||S.pointLength!==f||S.spotLength!==p||S.rectAreaLength!==m||S.hemiLength!==h||S.numSunShadows!==l||S.numDirectionalShadows!==g||S.numPointShadows!==_||S.numSpotShadows!==v||S.numSpotMaps!==y||S.numLightProbes!==x)&&(r.sun.length=c,r.directional.length=d,r.spot.length=p,r.rectArea.length=m,r.point.length=f,r.hemi.length=h,r.sunShadow.length=l,r.sunShadowMap.length=l,r.sunShadowMatrix.length=u,r.sunShadowCascade.length=u,r.directionalShadow.length=g,r.directionalShadowMap.length=g,r.directionalShadowMatrix.length=g,r.pointShadow.length=_,r.pointShadowMap.length=_,r.pointShadowMatrix.length=_,r.spotShadow.length=v,r.spotShadowMap.length=v,r.spotLightMatrix.length=v+y-b,r.spotLightMap.length=y,r.numSpotLightShadowsWithMaps=b,r.numLightProbes=x,S.sunLength=c,S.directionalLength=d,S.pointLength=f,S.spotLength=p,S.rectAreaLength=m,S.hemiLength=h,S.numSunShadows=l,S.numDirectionalShadows=g,S.numPointShadows=_,S.numSpotShadows=v,S.numSpotMaps=y,S.numLightProbes=x,r.version=Xk++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=0,f=t.matrixWorldInverse;for(let t=0,p=e.length;t<p;t++){let p=e[t];if(p.isSunLight){let e=r.sun[n];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),n++}else if(p.isDirectionalLight){let e=r.directional[s];e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),s++}else if(p.isSpotLight){let e=r.spot[l];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),l++}else if(p.isRectAreaLight){let e=r.rectArea[u];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),o.identity(),a.copy(p.matrixWorld),a.premultiply(f),o.extractRotation(a),e.halfWidth.set(p.width*.5,0,0),e.halfHeight.set(0,p.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),u++}else if(p.isPointLight){let e=r.point[c];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),c++}else if(p.isHemisphereLight){let e=r.hemi[d];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),d++}}}return{setup:s,setupView:c,state:r}}function $k(e){let t=new Qk(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function eA(e){let t=/* @__PURE__ */ new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new $k(e),t.set(n,[a])):r>=i.length?(a=new $k(e),i.push(a)):a=i[r],a}function r(){t=/* @__PURE__ */ new WeakMap}return{get:n,dispose:r}}var tA=`void main() {
|
|
4173
4172
|
gl_Position = vec4( position, 1.0 );
|
|
4174
|
-
}`,
|
|
4173
|
+
}`,nA=`uniform sampler2D shadow_pass;
|
|
4175
4174
|
uniform vec2 resolution;
|
|
4176
4175
|
uniform float radius;
|
|
4177
4176
|
void main() {
|
|
@@ -4196,12 +4195,12 @@ void main() {
|
|
|
4196
4195
|
squared_mean = squared_mean / samples;
|
|
4197
4196
|
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
|
|
4198
4197
|
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
|
|
4199
|
-
}`,KM=[/*@__PURE__*/ new X(1,0,0),/*@__PURE__*/ new X(-1,0,0),/*@__PURE__*/ new X(0,1,0),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,0,1),/*@__PURE__*/ new X(0,0,-1)],qM=[/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,0,1),/*@__PURE__*/ new X(0,0,-1),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,-1,0)],JM=/*@__PURE__*/ new kE,YM=/*@__PURE__*/ new X,XM=/*@__PURE__*/ new X;function ZM(e,t,n){let r=new LO,i=new aE,a=new aE,o=new wE,s=new nk,c=new rk,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new ek({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new aE},radius:{value:4}},vertexShader:WM,fragmentShader:GM}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new oO;m.setAttribute(`position`,new GD(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new AO(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(J(`WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){J(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){J(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new EE(i.x,i.y,{format:Rw,type:Tw,minFilter:hw,magFilter:hw,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new VO(i.x,i.y,ww),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=Pw,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=fw,d.map.depthTexture.magFilter=fw}else l.isPointLight?(d.map=new OA(i.x),d.map.depthTexture=new HO(i.x,Cw)):(d.map=new EE(i.x,i.y),d.map.depthTexture=new VO(i.x,i.y,Cw)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=Pw,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=hw,d.map.depthTexture.magFilter=hw):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=fw,d.map.depthTexture.magFilter=fw);d.camera.updateProjectionMatrix()}d.map.isWebGLCubeRenderTarget!==!0&&(d.map.width!==i.x||d.map.height!==i.y)&&d.map.setSize(i.x,i.y);let g=d.map.isWebGLCubeRenderTarget?6:d.getViewportCount();l.isPointLight!==!0&&d.updateMatrices(l,s);for(let t=0;t<g;t++){let i=d.getCamera(t);if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),YM.setFromMatrixPosition(l.matrixWorld),e.position.copy(YM),XM.copy(e.position),XM.add(KM[t]),e.up.copy(qM[t]),e.lookAt(XM),e.updateMatrixWorld(),n.makeTranslation(-YM.x,-YM.y,-YM.z),JM.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(JM,e.coordinateSystem,e.reversedDepth)}if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}r=d.getFrustum(t),b(n,s,i,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null?n.mapPass=new EE(i.x,i.y,{format:Rw,type:Tw}):(n.mapPass.width!==n.map.width||n.mapPass.height!==n.map.height)&&n.mapPass.setSize(n.map.width,n.map.height),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value.set(n.map.width,n.map.height),f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value.set(n.map.width,n.map.height),p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||n.intersectsFrustum(r))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function QM(e,t){function n(){let t=!1,n=new wE,r=null,i=new wE(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?fe(e.DEPTH_TEST):pe(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=JT[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?fe(e.STENCIL_TEST):pe(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=/* @__PURE__ */ new WeakMap,l=/* @__PURE__ */ new WeakMap,u={},d={},f={},p=/* @__PURE__ */ new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new uD(0,0,0),T=0,E=!1,D=null,O=null,ee=null,k=null,te=null,ne=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),A=!1,re=0,ie=e.getParameter(e.VERSION);ie.indexOf(`WebGL`)===-1?ie.indexOf(`OpenGL ES`)!==-1&&(re=parseFloat(/^OpenGL ES (\d)/.exec(ie)[1]),A=re>=2):(re=parseFloat(/^WebGL (\d)/.exec(ie)[1]),A=re>=1);let ae=null,oe={},j=e.getParameter(e.SCISSOR_BOX),se=e.getParameter(e.VIEWPORT),ce=new wE().fromArray(j),le=new wE().fromArray(se);function ue(t,n,r,i){let a=/* @__PURE__ */ new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let de={};de[e.TEXTURE_2D]=ue(e.TEXTURE_2D,e.TEXTURE_2D,1),de[e.TEXTURE_CUBE_MAP]=ue(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),de[e.TEXTURE_2D_ARRAY]=ue(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),de[e.TEXTURE_3D]=ue(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),fe(e.DEPTH_TEST),o.setFunc(3),xe(!1),Se(1),fe(e.CULL_FACE),ye(0);function fe(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function pe(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function me(t,n){return f[t]!==n&&(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function he(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function ge(t){return h!==t&&(e.useProgram(t),h=t,!0)}let _e={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};_e[103]=e.MIN,_e[104]=e.MAX;let ve={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function ye(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(pe(e.BLEND),g=!1);return}if(g===!1&&(fe(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:Y(`WebGLState: Invalid blending: `,t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:Y(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:Y(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:Y(`WebGLState: Invalid blending: `,t)}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(_e[n],_e[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(ve[r],ve[i],ve[o],ve[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function be(t,n){t.side===2?pe(e.CULL_FACE):fe(e.CULL_FACE);let r=t.side===1;n&&(r=!r),xe(r),t.blending===1&&t.transparent===!1?ye(0):ye(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),we(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?fe(e.SAMPLE_ALPHA_TO_COVERAGE):pe(e.SAMPLE_ALPHA_TO_COVERAGE)}function xe(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function Se(t){t===0?pe(e.CULL_FACE):(fe(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function Ce(t){t!==ee&&(A&&e.lineWidth(t),ee=t)}function we(t,n,r){t?(fe(e.POLYGON_OFFSET_FILL),(k!==n||te!==r)&&(k=n,te=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):pe(e.POLYGON_OFFSET_FILL)}function Te(t){t?fe(e.SCISSOR_TEST):pe(e.SCISSOR_TEST)}function M(t){t===void 0&&(t=e.TEXTURE0+ne-1),ae!==t&&(e.activeTexture(t),ae=t)}function Ee(t,n,r){r===void 0&&(r=ae===null?e.TEXTURE0+ne-1:ae);let i=oe[r];i===void 0&&(i={type:void 0,texture:void 0},oe[r]=i),(i.type!==t||i.texture!==n)&&(ae!==r&&(e.activeTexture(r),ae=r),e.bindTexture(t,n||de[t]),i.type=t,i.texture=n)}function De(){let t=oe[ae];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function Oe(){try{e.compressedTexImage2D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function N(){try{e.compressedTexImage3D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function ke(){try{e.texSubImage2D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function P(){try{e.texSubImage3D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function Ae(){try{e.compressedTexSubImage2D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function je(){try{e.compressedTexSubImage3D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function Me(){try{e.texStorage2D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function Ne(){try{e.texStorage3D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function Pe(){try{e.texImage2D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function Fe(){try{e.texImage3D(...arguments)}catch(e){Y(`WebGLState:`,e)}}function Ie(t){return d[t]===void 0?e.getParameter(t):d[t]}function Le(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function Re(t){ce.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),ce.copy(t))}function ze(t){le.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),le.copy(t))}function Be(t,n){let r=l.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Ve(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function He(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},ae=null,oe={},f={},p=/* @__PURE__ */ new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new uD(0,0,0),T=0,E=!1,D=null,O=null,ee=null,k=null,te=null,ce.set(0,0,e.canvas.width,e.canvas.height),le.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:fe,disable:pe,bindFramebuffer:me,drawBuffers:he,useProgram:ge,setBlending:ye,setMaterial:be,setFlipSided:xe,setCullFace:Se,setLineWidth:Ce,setPolygonOffset:we,setScissorTest:Te,activeTexture:M,bindTexture:Ee,unbindTexture:De,compressedTexImage2D:Oe,compressedTexImage3D:N,texImage2D:Pe,texImage3D:Fe,pixelStorei:Le,getParameter:Ie,updateUBOMapping:Be,uniformBlockBinding:Ve,texStorage2D:Me,texStorage3D:Ne,texSubImage2D:ke,texSubImage3D:P,compressedTexSubImage2D:Ae,compressedTexSubImage3D:je,scissor:Re,viewport:ze,reset:He}}function $M(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new aE,u=/* @__PURE__ */ new WeakMap,d=/* @__PURE__ */ new Set,f,p=/* @__PURE__ */ new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):VT(`canvas`)}function g(e,t,n){let r=1,i=Oe(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),J(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}return`data`in e&&J(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e}return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];J(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||J(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?NT:pE.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,J(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function S(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),T(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function w(e){let t=e.target;t.removeEventListener(`dispose`,w),D(t)}function T(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&E(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function E(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function D(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let O=0;function ee(){O=0}function k(){return O}function te(e){O=e}function ne(){let e=O;return e>=i.maxTextures&&J(`WebGLTextures: Trying to use `+(e+1)+` texture units while this GPU supports only `+i.maxTextures),O+=1,e}function A(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function re(t,i){let a=r.get(t);if(t.isVideoTexture&&Ee(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)J(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)J(`WebGLRenderer: Texture marked for update but image is incomplete`);else{pe(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function ie(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){pe(a,t,i);return}t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function ae(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){pe(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function oe(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){me(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let j={[lw]:e.REPEAT,[uw]:e.CLAMP_TO_EDGE,[dw]:e.MIRRORED_REPEAT},se={[fw]:e.NEAREST,[pw]:e.NEAREST_MIPMAP_NEAREST,[mw]:e.NEAREST_MIPMAP_LINEAR,[hw]:e.LINEAR,[gw]:e.LINEAR_MIPMAP_NEAREST,[_w]:e.LINEAR_MIPMAP_LINEAR},ce={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function le(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&J(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,j[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,j[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,j[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,se[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,se[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,ce[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function ue(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,C));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=A(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&E(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function de(e,t,n){return Math.floor(Math.floor(e/n)/t)}function fe(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=de(n.start,r.width,4),c=de(t.start,r.width,4);n.start<=i+1&&a===c&&de(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function pe(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=ue(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=pE.getPrimaries(pE.workingColorSpace),r=o.colorSpace===``?null:pE.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=De(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);le(c,o);let h,y=o.mipmaps,C=o.isVideoTexture!==!0,w=f.__version===void 0||l===!0,T=u.dataReady,E=S(o,t);if(o.isDepthTexture)m=x(o.format===Fw,o.type),w&&(C?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture){if(y.length>0){C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else C?(w&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),T&&fe(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data)}else if(o.isCompressedTexture){if(o.isCompressedArrayTexture){C&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023){if(r!==null){if(C){if(T){if(o.layerUpdates.size>0){let t=Jk(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0)}else J(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`)}else C?T&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data);o.layerUpdates.size>0&&o.clearLayerUpdates()}else{C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?J(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}}else if(o.isDataArrayTexture){if(C){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),T){if(o.layerUpdates.size>0){let i=Jk(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data)}else if(o.isData3DTexture)C?(w&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),T&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(w){if(C)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,t);else{let n=e.RGBA,r=e.RGBA,i=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,n,r,i,t)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(C&&w){let t=Oe(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(C){if(w){let r=Oe(t);n.texStorage2D(e.TEXTURE_2D,E,m,r.width,r.height)}T&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function me(t,o,s){if(o.image.length!==6)return;let c=ue(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=pE.getPrimaries(pE.workingColorSpace),r=o.colorSpace===``?null:pE.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=De(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),C=b(o.internalFormat,y,x,o.normalized,o.colorSpace),w=o.isVideoTexture!==!0,T=u.__version===void 0||c===!0,E=l.dataReady,D=S(o,h);le(e.TEXTURE_CUBE_MAP,o);let O;if(f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,h.width,h.height);for(let t=0;t<6;t++){O=m[t].mipmaps;for(let r=0;r<O.length;r++){let i=O[r];o.format===1023?w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,y,x,i.data):y===null?J(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):w?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,i.data)}}}else{if(O=o.mipmaps,w&&T){O.length>0&&D++;let t=Oe(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<O.length;r++){let i=O[r].image[t].image;w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,i.width,i.height,0,y,x,i.data)}}else{w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,y,x,m[t]);for(let r=0;r<O.length;r++){let i=O[r];w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function he(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),M(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Te(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function ge(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;M(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Te(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Te(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);M(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Te(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Te(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function _e(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,C)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),le(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else re(i.depthTexture,0);let u=l.__webglTexture,d=Te(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)M(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)M(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`THREE.WebGLTextures: Unknown depthTexture format.`)}function ve(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer){if(a)for(let e=0;e<6;e++)_e(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?_e(i.__webglFramebuffer[0],t,0):_e(i.__webglFramebuffer,t,0)}}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),ge(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),ge(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function ye(t,n,i){let a=r.get(t);n!==void 0&&he(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&ve(t)}function be(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,w);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&M(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=Te(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),ge(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),le(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)he(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else he(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),le(c,a),he(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),le(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)he(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else he(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&ve(t)}function xe(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let Se=[],Ce=[];function we(t){if(t.samples>0){if(M(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(Se.length=0,Ce.length=0,Se.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&(Se.push(l),Ce.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,Ce)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,Se))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function Te(e){return Math.min(i.maxSamples,e.samples)}function M(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function Ee(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function De(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(pE.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&J(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):Y(`WebGLTextures: Unsupported texture color space:`,n)),t}function Oe(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=ne,this.resetTextureUnits=ee,this.getTextureUnits=k,this.setTextureUnits=te,this.setTexture2D=re,this.setTexture2DArray=ie,this.setTexture3D=ae,this.setTextureCube=oe,this.rebindTextures=ye,this.setupRenderTarget=be,this.updateRenderTargetMipmap=xe,this.updateMultisampleRenderTarget=we,this.setupDepthRenderbuffer=ve,this.setupFrameBufferTexture=he,this.useMultisampledRTT=M,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function eN(e,t){function n(n,r=``){let i,a=pE.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779){if(a===`srgb`){if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null}else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null}if(n===35840||n===35841||n===35842||n===35843){if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null}if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491){if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null}if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821){if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null}if(n===36492||n===36494||n===36495){if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null}if(n===36283||n===36284||n===36285||n===36286){if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null}return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var tN=`
|
|
4198
|
+
}`,rA=[/*@__PURE__*/ new X(1,0,0),/*@__PURE__*/ new X(-1,0,0),/*@__PURE__*/ new X(0,1,0),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,0,1),/*@__PURE__*/ new X(0,0,-1)],iA=[/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,0,1),/*@__PURE__*/ new X(0,0,-1),/*@__PURE__*/ new X(0,-1,0),/*@__PURE__*/ new X(0,-1,0)],aA=/*@__PURE__*/ new BC,oA=/*@__PURE__*/ new X,sA=/*@__PURE__*/ new X;function cA(e,t,n){let r=new JT,i=new Y,a=new Y,o=new FC,s=new pE,c=new mE,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new dE({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Y},radius:{value:4}},vertexShader:tA,fragmentShader:nA}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new _T;m.setAttribute(`position`,new nT(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new VT(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(q(`WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){q(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){q(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new LC(i.x,i.y,{format:Xx,type:Lx,minFilter:Dx,magFilter:Dx,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new QT(i.x,i.y,Ix),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=Kx,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=wx,d.map.depthTexture.magFilter=wx}else l.isPointLight?(d.map=new zD(i.x),d.map.depthTexture=new $T(i.x,Fx)):(d.map=new LC(i.x,i.y),d.map.depthTexture=new QT(i.x,i.y,Fx)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=Kx,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=Dx,d.map.depthTexture.magFilter=Dx):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=wx,d.map.depthTexture.magFilter=wx);d.camera.updateProjectionMatrix()}d.map.isWebGLCubeRenderTarget!==!0&&(d.map.width!==i.x||d.map.height!==i.y)&&d.map.setSize(i.x,i.y);let g=d.map.isWebGLCubeRenderTarget?6:d.getViewportCount();l.isPointLight!==!0&&d.updateMatrices(l,s);for(let t=0;t<g;t++){let i=d.getCamera(t);if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),oA.setFromMatrixPosition(l.matrixWorld),e.position.copy(oA),sA.copy(e.position),sA.add(rA[t]),e.up.copy(iA[t]),e.lookAt(sA),e.updateMatrixWorld(),n.makeTranslation(-oA.x,-oA.y,-oA.z),aA.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(aA,e.coordinateSystem,e.reversedDepth)}if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}r=d.getFrustum(t),b(n,s,i,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null?n.mapPass=new LC(i.x,i.y,{format:Xx,type:Lx}):(n.mapPass.width!==n.map.width||n.mapPass.height!==n.map.height)&&n.mapPass.setSize(n.map.width,n.map.height),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value.set(n.map.width,n.map.height),f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value.set(n.map.width,n.map.height),p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||n.intersectsFrustum(r))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function lA(e,t){function n(){let t=!1,n=new FC,r=null,i=new FC(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?ue(e.DEPTH_TEST):de(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=oC[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?ue(e.STENCIL_TEST):de(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=/* @__PURE__ */ new WeakMap,l=/* @__PURE__ */ new WeakMap,u={},d={},f={},p=/* @__PURE__ */ new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new xw(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),j=!1,ne=0,re=e.getParameter(e.VERSION);re.indexOf(`WebGL`)===-1?re.indexOf(`OpenGL ES`)!==-1&&(ne=parseFloat(/^OpenGL ES (\d)/.exec(re)[1]),j=ne>=2):(ne=parseFloat(/^WebGL (\d)/.exec(re)[1]),j=ne>=1);let M=null,ie={},N=e.getParameter(e.SCISSOR_BOX),ae=e.getParameter(e.VIEWPORT),oe=new FC().fromArray(N),se=new FC().fromArray(ae);function ce(t,n,r,i){let a=/* @__PURE__ */ new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let le={};le[e.TEXTURE_2D]=ce(e.TEXTURE_2D,e.TEXTURE_2D,1),le[e.TEXTURE_CUBE_MAP]=ce(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),le[e.TEXTURE_2D_ARRAY]=ce(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),le[e.TEXTURE_3D]=ce(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),ue(e.DEPTH_TEST),o.setFunc(3),ye(!1),be(1),ue(e.CULL_FACE),_e(0);function ue(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function de(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function fe(t,n){return f[t]!==n&&(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function pe(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function me(t){return h!==t&&(e.useProgram(t),h=t,!0)}let he={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};he[103]=e.MIN,he[104]=e.MAX;let ge={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function _e(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(de(e.BLEND),g=!1);return}if(g===!1&&(ue(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:J(`WebGLState: Invalid blending: `,t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:J(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:J(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:J(`WebGLState: Invalid blending: `,t)}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(he[n],he[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(ge[r],ge[i],ge[o],ge[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function ve(t,n){t.side===2?de(e.CULL_FACE):ue(e.CULL_FACE);let r=t.side===1;n&&(r=!r),ye(r),t.blending===1&&t.transparent===!1?_e(0):_e(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Se(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?ue(e.SAMPLE_ALPHA_TO_COVERAGE):de(e.SAMPLE_ALPHA_TO_COVERAGE)}function ye(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function be(t){t===0?de(e.CULL_FACE):(ue(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function xe(t){t!==k&&(j&&e.lineWidth(t),k=t)}function Se(t,n,r){t?(ue(e.POLYGON_OFFSET_FILL),(A!==n||ee!==r)&&(A=n,ee=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):de(e.POLYGON_OFFSET_FILL)}function Ce(t){t?ue(e.SCISSOR_TEST):de(e.SCISSOR_TEST)}function P(t){t===void 0&&(t=e.TEXTURE0+te-1),M!==t&&(e.activeTexture(t),M=t)}function we(t,n,r){r===void 0&&(r=M===null?e.TEXTURE0+te-1:M);let i=ie[r];i===void 0&&(i={type:void 0,texture:void 0},ie[r]=i),(i.type!==t||i.texture!==n)&&(M!==r&&(e.activeTexture(r),M=r),e.bindTexture(t,n||le[t]),i.type=t,i.texture=n)}function Te(){let t=ie[M];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function Ee(){try{e.compressedTexImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function F(){try{e.compressedTexImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function De(){try{e.texSubImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function I(){try{e.texSubImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function L(){try{e.compressedTexSubImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Oe(){try{e.compressedTexSubImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function ke(){try{e.texStorage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Ae(){try{e.texStorage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function je(){try{e.texImage2D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Me(){try{e.texImage3D(...arguments)}catch(e){J(`WebGLState:`,e)}}function Ne(t){return d[t]===void 0?e.getParameter(t):d[t]}function Pe(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function Fe(t){oe.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),oe.copy(t))}function Ie(t){se.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),se.copy(t))}function Le(t,n){let r=l.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Re(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function ze(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},M=null,ie={},f={},p=/* @__PURE__ */ new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new xw(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,oe.set(0,0,e.canvas.width,e.canvas.height),se.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:ue,disable:de,bindFramebuffer:fe,drawBuffers:pe,useProgram:me,setBlending:_e,setMaterial:ve,setFlipSided:ye,setCullFace:be,setLineWidth:xe,setPolygonOffset:Se,setScissorTest:Ce,activeTexture:P,bindTexture:we,unbindTexture:Te,compressedTexImage2D:Ee,compressedTexImage3D:F,texImage2D:je,texImage3D:Me,pixelStorei:Pe,getParameter:Ne,updateUBOMapping:Le,uniformBlockBinding:Re,texStorage2D:ke,texStorage3D:Ae,texSubImage2D:De,texSubImage3D:I,compressedTexSubImage2D:L,compressedTexSubImage3D:Oe,scissor:Fe,viewport:Ie,reset:ze}}function uA(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Y,u=/* @__PURE__ */ new WeakMap,d=/* @__PURE__ */ new Set,f,p=/* @__PURE__ */ new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):$S(`canvas`)}function g(e,t,n){let r=1,i=Ee(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),q(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}return`data`in e&&q(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e}return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];q(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||q(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?GS:wC.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,q(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function S(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),T(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function w(e){let t=e.target;t.removeEventListener(`dispose`,w),D(t)}function T(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&E(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function E(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function D(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let O=0;function k(){O=0}function A(){return O}function ee(e){O=e}function te(){let e=O;return e>=i.maxTextures&&q(`WebGLTextures: Trying to use `+(e+1)+` texture units while this GPU supports only `+i.maxTextures),O+=1,e}function j(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function ne(t,i){let a=r.get(t);if(t.isVideoTexture&&we(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)q(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)q(`WebGLRenderer: Texture marked for update but image is incomplete`);else{de(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function re(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){de(a,t,i);return}t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function M(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){de(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function ie(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){fe(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let N={[xx]:e.REPEAT,[Sx]:e.CLAMP_TO_EDGE,[Cx]:e.MIRRORED_REPEAT},ae={[wx]:e.NEAREST,[Tx]:e.NEAREST_MIPMAP_NEAREST,[Ex]:e.NEAREST_MIPMAP_LINEAR,[Dx]:e.LINEAR,[Ox]:e.LINEAR_MIPMAP_NEAREST,[kx]:e.LINEAR_MIPMAP_LINEAR},oe={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function se(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&q(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,N[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,N[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,N[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,ae[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,ae[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,oe[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function ce(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,C));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=j(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&E(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function le(e,t,n){return Math.floor(Math.floor(e/n)/t)}function ue(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=le(n.start,r.width,4),c=le(t.start,r.width,4);n.start<=i+1&&a===c&&le(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function de(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=ce(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=wC.getPrimaries(wC.workingColorSpace),r=o.colorSpace===``?null:wC.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=Te(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);se(c,o);let h,y=o.mipmaps,C=o.isVideoTexture!==!0,w=f.__version===void 0||l===!0,T=u.dataReady,E=S(o,t);if(o.isDepthTexture)m=x(o.format===qx,o.type),w&&(C?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture){if(y.length>0){C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else C?(w&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),T&&ue(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data)}else if(o.isCompressedTexture){if(o.isCompressedArrayTexture){C&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023){if(r!==null){if(C){if(T){if(o.layerUpdates.size>0){let t=aD(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0)}else q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`)}else C?T&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data);o.layerUpdates.size>0&&o.clearLayerUpdates()}else{C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}}else if(o.isDataArrayTexture){if(C){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),T){if(o.layerUpdates.size>0){let i=aD(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data)}else if(o.isData3DTexture)C?(w&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),T&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(w){if(C)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,t);else{let n=e.RGBA,r=e.RGBA,i=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,n,r,i,t)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(C&&w){let t=Ee(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(C){if(w){let r=Ee(t);n.texStorage2D(e.TEXTURE_2D,E,m,r.width,r.height)}T&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function fe(t,o,s){if(o.image.length!==6)return;let c=ce(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=wC.getPrimaries(wC.workingColorSpace),r=o.colorSpace===``?null:wC.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=Te(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),C=b(o.internalFormat,y,x,o.normalized,o.colorSpace),w=o.isVideoTexture!==!0,T=u.__version===void 0||c===!0,E=l.dataReady,D=S(o,h);se(e.TEXTURE_CUBE_MAP,o);let O;if(f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,h.width,h.height);for(let t=0;t<6;t++){O=m[t].mipmaps;for(let r=0;r<O.length;r++){let i=O[r];o.format===1023?w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,y,x,i.data):y===null?q(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):w?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,i.data)}}}else{if(O=o.mipmaps,w&&T){O.length>0&&D++;let t=Ee(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<O.length;r++){let i=O[r].image[t].image;w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,i.width,i.height,0,y,x,i.data)}}else{w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,y,x,m[t]);for(let r=0;r<O.length;r++){let i=O[r];w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function pe(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Ce(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function me(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;P(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);P(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function he(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,C)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),se(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else ne(i.depthTexture,0);let u=l.__webglTexture,d=Ce(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)P(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`THREE.WebGLTextures: Unknown depthTexture format.`)}function ge(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer){if(a)for(let e=0;e<6;e++)he(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?he(i.__webglFramebuffer[0],t,0):he(i.__webglFramebuffer,t,0)}}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),me(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),me(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function _e(t,n,i){let a=r.get(t);n!==void 0&&pe(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&ge(t)}function ve(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,w);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&P(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=Ce(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),me(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),se(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)pe(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else pe(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),se(c,a),pe(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),se(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)pe(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else pe(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&ge(t)}function ye(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let be=[],xe=[];function Se(t){if(t.samples>0){if(P(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(be.length=0,xe.length=0,be.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&(be.push(l),xe.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,xe)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,be))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function Ce(e){return Math.min(i.maxSamples,e.samples)}function P(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function we(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function Te(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(wC.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&q(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):J(`WebGLTextures: Unsupported texture color space:`,n)),t}function Ee(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=te,this.resetTextureUnits=k,this.getTextureUnits=A,this.setTextureUnits=ee,this.setTexture2D=ne,this.setTexture2DArray=re,this.setTexture3D=M,this.setTextureCube=ie,this.rebindTextures=_e,this.setupRenderTarget=ve,this.updateRenderTargetMipmap=ye,this.updateMultisampleRenderTarget=Se,this.setupDepthRenderbuffer=ge,this.setupFrameBufferTexture=pe,this.useMultisampledRTT=P,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function dA(e,t){function n(n,r=``){let i,a=wC.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779){if(a===`srgb`){if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null}else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null}if(n===35840||n===35841||n===35842||n===35843){if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null}if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491){if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null}if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821){if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null}if(n===36492||n===36494||n===36495){if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null}if(n===36283||n===36284||n===36285||n===36286){if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null}return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var fA=`
|
|
4200
4199
|
void main() {
|
|
4201
4200
|
|
|
4202
4201
|
gl_Position = vec4( position, 1.0 );
|
|
4203
4202
|
|
|
4204
|
-
}`,
|
|
4203
|
+
}`,pA=`
|
|
4205
4204
|
uniform sampler2DArray depthColor;
|
|
4206
4205
|
uniform float depthWidth;
|
|
4207
4206
|
uniform float depthHeight;
|
|
@@ -4220,7 +4219,7 @@ void main() {
|
|
|
4220
4219
|
|
|
4221
4220
|
}
|
|
4222
4221
|
|
|
4223
|
-
}`,rN=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new UO(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new ek({vertexShader:tN,fragmentShader:nN,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new AO(new GO(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},iN=class extends YT{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new rN,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new aE,C=null,w=null,T=new Ak;T.viewport=new wE;let E=new Ak;E.viewport=new wE;let D=[T,E],O=new Fk,ee=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new aD,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new aD,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new aD,b[e]=t),t.getHandSpace()};function te(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function ne(){r.removeEventListener(`select`,te),r.removeEventListener(`selectstart`,te),r.removeEventListener(`selectend`,te),r.removeEventListener(`squeeze`,te),r.removeEventListener(`squeezestart`,te),r.removeEventListener(`squeezeend`,te),r.removeEventListener(`end`,ne),r.removeEventListener(`inputsourceschange`,A);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}ee=null,k=null,h.reset();for(let e in g)delete g[e];if(e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,le.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),w!==null){let e=w.camera;e.fov=w.fov,e.zoom=w.zoom,e.updateProjectionMatrix(),w=null}n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&J(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&J(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,te),r.addEventListener(`selectstart`,te),r.addEventListener(`selectend`,te),r.addEventListener(`squeeze`,te),r.addEventListener(`squeezestart`,te),r.addEventListener(`squeezeend`,te),r.addEventListener(`end`,ne),r.addEventListener(`inputsourceschange`,A),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?Fw:Pw,a=_.stencil?Ow:Cw);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new EE(d.textureWidth,d.textureHeight,{format:Nw,type:vw,depthTexture:new VO(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new EE(f.framebufferWidth,f.framebufferHeight,{format:Nw,type:vw,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),le.setContext(r),le.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function A(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let re=new X,ie=new X;function ae(e,t,n){re.setFromMatrixPosition(t.matrixWorld),ie.setFromMatrixPosition(n.matrixWorld);let r=re.distanceTo(ie),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function oe(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),O.near=E.near=T.near=t,O.far=E.far=T.far=n,(ee!==O.near||k!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),ee=O.near,k=O.far),O.layers.mask=e.layers.mask|6,T.layers.mask=O.layers.mask&-5,E.layers.mask=O.layers.mask&-3;let i=e.parent,a=O.cameras;oe(O,i);for(let e=0;e<a.length;e++)oe(a[e],i);a.length===2?ae(O,T,E):O.projectionMatrix.copy(T.projectionMatrix),w===null&&e.isPerspectiveCamera&&(w={camera:e,fov:e.fov,zoom:e.zoom}),j(e,O,i)};function j(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=QT*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(d!==null||f!==null)return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(O)},this.getCameraTexture=function(e){return g[e]};let se=null;function ce(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==O.cameras.length&&(O.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=D[n];o===void 0&&(o=new Ak,o.layers.enable(n),o.viewport=new wE,D[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(O.matrix.copy(o.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),i===!0&&O.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new UO,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}se&&se(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let le=new Xk;le.setAnimationLoop(ce),this.setAnimationLoop=function(e){se=e},this.dispose=function(){}}},aN=/*@__PURE__*/ new kE,oN=/*@__PURE__*/ new Z;oN.set(-1,0,0,0,1,0,0,0,1);function sN(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,XO(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(aN.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(oN),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.retroreflectivity>0&&(e.retroreflectivity.value=t.retroreflectivity),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function cN(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(g(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,v));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return Y(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let e=0,t=r.length;e<t;e++){let t=r[e];if(Array.isArray(t))for(let n=0,r=t.length;n<r;n++)p(t[n],e,n,a);else p(t,e,0,a)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(t,n,r,i){if(h(t,n,r,i)===!0){let n=t.__offset,r=t.value;if(Array.isArray(r)){let e=0;for(let n=0;n<r.length;n++){let i=r[n],a=_(i);m(i,t.__data,e),typeof i!=`number`&&typeof i!=`boolean`&&!i.isMatrix3&&!ArrayBuffer.isView(i)&&(e+=a.storage/Float32Array.BYTES_PER_ELEMENT)}}else m(r,t.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,n,t.__data)}}function m(e,t,n){typeof e==`number`||typeof e==`boolean`?t[0]=e:e.isMatrix3?(t[0]=e.elements[0],t[1]=e.elements[1],t[2]=e.elements[2],t[3]=0,t[4]=e.elements[3],t[5]=e.elements[4],t[6]=e.elements[5],t[7]=0,t[8]=e.elements[6],t[9]=e.elements[7],t[10]=e.elements[8],t[11]=0):ArrayBuffer.isView(e)?t.set(new e.constructor(e.buffer,e.byteOffset,t.length)):e.toArray(t,n)}function h(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return r[a]=typeof i==`number`||typeof i==`boolean`?i:ArrayBuffer.isView(i)?i.slice():i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function g(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=_(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function _(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?J(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):J(`WebGLRenderer: Unsupported uniform value type.`,e),t}function v(t){let n=t.target;n.removeEventListener(`dispose`,v);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function y(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:y}}var lN=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),uN=null;function dN(){return uN===null&&(uN=new NO(lN,16,16,Rw,Tw),uN.name=`DFG_LUT`,uN.minFilter=hw,uN.magFilter=hw,uN.wrapS=uw,uN.wrapT=uw,uN.generateMipmaps=!1,uN.needsUpdate=!0),uN}var fN=class{constructor(e={}){let{canvas:t=HT(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=vw}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=/* @__PURE__ */ new Set([Bw,zw,Lw]),g=/* @__PURE__ */ new Set([vw,Cw,xw,Ow,Ew,Dw]),_=/* @__PURE__ */ new Uint32Array(4),v=/* @__PURE__ */ new Int32Array(4),y=new X,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null,O=null,ee=null,k=null;this._outputColorSpace=jT;let te=0,ne=0,A=null,re=-1,ie=null,ae=new wE,oe=new wE,j=null,se=new uD(0),ce=0,le=t.width,ue=t.height,de=1,fe=null,pe=null,me=new wE(0,0,le,ue),he=new wE(0,0,le,ue),ge=!1,_e=new LO,ve=!1,ye=!1,be=new kE,xe=new X,Se=new wE,Ce={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},we=!1;function Te(){return A===null?de:1}let M=n;function Ee(e,n){return t.getContext(e,n)}let De,Oe,N,ke,P,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe;try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r186`),t.addEventListener(`webglcontextlost`,Xe,!1),t.addEventListener(`webglcontextrestored`,Ze,!1),t.addEventListener(`webglcontextcreationerror`,Qe,!1),M===null){let t=`webgl2`;if(M=Ee(t,e),M===null)throw Ee(t)?Error(`THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.`):Error(`THREE.WebGLRenderer: Error creating WebGL context.`)}Je()}catch(e){throw t.removeEventListener(`webglcontextlost`,Xe,!1),t.removeEventListener(`webglcontextrestored`,Ze,!1),t.removeEventListener(`webglcontextcreationerror`,Qe,!1),Y(`WebGLRenderer: `+e.message),e}function Je(){De=new AA(M),De.init(),Ge=new eN(M,De),Oe=new aA(M,De,e,Ge),N=new QM(M,De),Oe.reversedDepthBuffer&&d&&N.buffers.depth.setReversed(!0),O=M.createFramebuffer(),ee=M.createFramebuffer(),k=M.createFramebuffer(),ke=new NA(M),P=new MM,Ae=new $M(M,De,N,P,Oe,Ge,ke),je=new kA(T),Me=new Zk(M),Ke=new rA(M,Me),Ne=new jA(M,Me,ke,Ke),Pe=new FA(M,Ne,Me,Ke,ke),He=new PA(M,Oe,Ae),ze=new oA(P),Fe=new jM(T,je,De,Oe,Ke,ze),Ie=new sN(T,P),Le=new IM,Re=new UM(De),Ve=new nA(T,je,N,Pe,p,s),Be=new ZM(T,Pe,Oe),qe=new cN(M,ke,Oe,N),Ue=new iA(M,De,ke),We=new MA(M,De,ke),ke.programs=Fe.programs,T.capabilities=Oe,T.extensions=De,T.properties=P,T.renderLists=Le,T.shadowMap=Be,T.state=N,T.info=ke}m!==1009&&(w=new LA(m,t.width,t.height,o,r,i));let Ye=new iN(T,M);this.xr=Ye,this.getContext=function(){return M},this.getContextAttributes=function(){return M.getContextAttributes()},this.forceContextLoss=function(){let e=De.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=De.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return de},this.setPixelRatio=function(e){e!==void 0&&(de=e,this.setSize(le,ue,!1))},this.getSize=function(e){return e.set(le,ue)},this.setSize=function(e,n,r=!0){if(Ye.isPresenting){J(`WebGLRenderer: Can't change size while VR device is presenting.`);return}le=e,ue=n,t.width=Math.floor(e*de),t.height=Math.floor(n*de),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(le*de,ue*de).floor()},this.setDrawingBufferSize=function(e,n,r){le=e,ue=n,de=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){Y(`WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){J(`WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(ae)},this.getViewport=function(e){return e.copy(me)},this.setViewport=function(e,t,n,r){e.isVector4?me.set(e.x,e.y,e.z,e.w):me.set(e,t,n,r),N.viewport(ae.copy(me).multiplyScalar(de).round())},this.getScissor=function(e){return e.copy(he)},this.setScissor=function(e,t,n,r){e.isVector4?he.set(e.x,e.y,e.z,e.w):he.set(e,t,n,r),N.scissor(oe.copy(he).multiplyScalar(de).round())},this.getScissorTest=function(){return ge},this.setScissorTest=function(e){N.setScissorTest(ge=e)},this.setOpaqueSort=function(e){fe=e},this.setTransparentSort=function(e){pe=e},this.getClearColor=function(e){return e.copy(Ve.getClearColor())},this.setClearColor=function(){Ve.setClearColor(...arguments)},this.getClearAlpha=function(){return Ve.getClearAlpha()},this.setClearAlpha=function(){Ve.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(A!==null){let t=A.texture.format;e=h.has(t)}if(e){let e=A.texture.type,t=g.has(e),n=Ve.getClearColor(),r=Ve.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,M.clearBufferuiv(M.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,M.clearBufferiv(M.COLOR,0,v))}else r|=M.COLOR_BUFFER_BIT}t&&(r|=M.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=M.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&M.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,Xe,!1),t.removeEventListener(`webglcontextrestored`,Ze,!1),t.removeEventListener(`webglcontextcreationerror`,Qe,!1),Ve.dispose(),Le.dispose(),Re.dispose(),P.dispose(),je.dispose(),Pe.dispose(),Ke.dispose(),qe.dispose(),Fe.dispose(),Ye.dispose(),Ye.removeEventListener(`sessionstart`,at),Ye.removeEventListener(`sessionend`,ot),st.stop()};function Xe(e){e.preventDefault(),WT(`WebGLRenderer: Context Lost.`),E=!0}function Ze(){WT(`WebGLRenderer: Context Restored.`),E=!1;let e=ke.autoReset,t=Be.enabled,n=Be.autoUpdate,r=Be.needsUpdate,i=Be.type;Je(),ke.autoReset=e,Be.enabled=t,Be.autoUpdate=n,Be.needsUpdate=r,Be.type=i}function Qe(e){Y(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function $e(e){let t=e.target;t.removeEventListener(`dispose`,$e),et(t)}function et(e){tt(e),P.remove(e)}function tt(e){let t=P.get(e).programs;t!==void 0&&(t.forEach(function(e){Fe.releaseProgram(e)}),e.isShaderMaterial&&Fe.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=Ce);let o=i.isMesh&&i.matrixWorld.determinantAffine()<0,s=gt(e,t,n,r,i);N.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=Ne.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Ke.setup(i,r,s,n,c);let h,g=Ue;if(c!==null&&(h=Me.get(c),g=We,g.setIndex(h)),i.isMesh)r.wireframe===!0?(N.setLineWidth(r.wireframeLinewidth*Te()),g.setMode(M.LINES)):g.setMode(M.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),N.setLineWidth(e*Te()),i.isLineSegments?g.setMode(M.LINES):i.isLineLoop?g.setMode(M.LINE_LOOP):g.setMode(M.LINE_STRIP)}else i.isPoints?g.setMode(M.POINTS):i.isSprite&&g.setMode(M.TRIANGLES);if(i.isBatchedMesh){if(De.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?Me.get(c).bytesPerElement:1,o=P.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(M,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function nt(e,t,n,r){D!==null&&e.isNodeMaterial&&D.setObject(r,e),ve===!0&&ze.setState(e,n,!1),e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,pt(e,t,r),e.side=0,e.needsUpdate=!0,pt(e,t,r),e.side=2):pt(e,t,r)}this.compile=function(e,t,n=null){n===null&&(n=e),D!==null&&D.renderStart(e,t,n),x=Re.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights(),D!==null&&D.updateLights(x.state.lightsArray),ye=this.localClippingEnabled,ve=ze.init(this.clippingPlanes,ye),ve===!0&&ze.setGlobalState(this.clippingPlanes,t),D!==null&&Be.render(x.state.shadowsArray,n,t);let r=/* @__PURE__ */ new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let i=e.material;if(i){if(Array.isArray(i))for(let a=0;a<i.length;a++){let o=i[a];nt(o,n,t,e),r.add(o)}else nt(i,n,t,e),r.add(i)}}),x=C.pop(),D!==null&&D.renderEnd(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){let t=P.get(e).currentProgram;(t===void 0||t.isReady())&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}De.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let rt=null;function it(e){rt&&rt(e)}function at(){st.stop()}function ot(){st.start()}let st=new Xk;st.setAnimationLoop(it),typeof self<`u`&&st.setContext(self),this.setAnimationLoop=function(e){rt=e,Ye.setAnimationLoop(e),e===null?st.stop():st.start()},Ye.addEventListener(`sessionstart`,at),Ye.addEventListener(`sessionend`,ot),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){Y(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=Ye.enabled===!0&&Ye.isPresenting===!0,r=w!==null&&(A===null||n)&&w.begin(T,A);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ye.enabled===!0&&Ye.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(Ye.cameraAutoUpdate===!0&&Ye.updateCamera(t),t=Ye.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,A),x=Re.get(e,C.length),x.init(t),x.state.textureUnits=Ae.getTextureUnits(),C.push(x),be.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),_e.setFromProjectionMatrix(be,RT,t.reversedDepth),ye=this.localClippingEnabled,ve=ze.init(this.clippingPlanes,ye),b=Le.get(e,S.length),b.init(),S.push(b),Ye.enabled===!0&&Ye.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&ct(e,t,-1/0,T.sortObjects)}ct(e,t,0,T.sortObjects),b.finish(),D!==null&&D.updateLights(x.state.lightsArray),T.sortObjects===!0&&b.sort(fe,pe),we=Ye.enabled===!1||Ye.isPresenting===!1||Ye.hasDepthSensing()===!1,we&&Ve.addToRenderList(b,e),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ve===!0&&ze.beginShadows();let i=x.state.shadowsArray;if(Be.render(i,e,t),ve===!0&&ze.endShadows(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];ut(n,r,e,a)}we&&Ve.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];lt(b,e,n,n.viewport)}}else r.length>0&&ut(n,r,e,t),we&&Ve.render(e),lt(b,e,t)}A!==null&&ne===0&&(Ae.updateMultisampleRenderTarget(A),Ae.updateRenderTargetMipmap(A)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),Ke.resetDefaultState(),re=-1,ie=null,C.pop(),C.length>0?(x=C[C.length-1],Ae.setTextureUnits(x.state.textureUnits),ve===!0&&ze.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function ct(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||e.intersectsFrustum(_e)){r&&Se.setFromMatrixPosition(e.matrixWorld).applyMatrix4(be);let i=Pe.update(e),a=e.material;a.visible&&b.push(e,i,a,n,Se.z,null,t)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||e.intersectsFrustum(_e))){let i=Pe.update(e),a=e.material;if(r&&(e.boundingSphere===void 0?(i.boundingSphere===null&&i.computeBoundingSphere(),Se.copy(i.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),Se.copy(e.boundingSphere.center)),Se.applyMatrix4(e.matrixWorld).applyMatrix4(be)),Array.isArray(a)){let r=i.groups;for(let o=0,s=r.length;o<s;o++){let s=r[o],c=a[s.materialIndex];c&&c.visible&&b.push(e,i,c,n,Se.z,s,t)}}else a.visible&&b.push(e,i,a,n,Se.z,null,t)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)ct(i[e],t,n,r)}function lt(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),ve===!0&&ze.setGlobalState(T.clippingPlanes,n),r&&N.viewport(ae.copy(r)),i.length>0&&dt(i,t,n),a.length>0&&dt(a,t,n),o.length>0&&dt(o,t,n),N.buffers.depth.setTest(!0),N.buffers.depth.setMask(!0),N.buffers.color.setMask(!0),N.setPolygonOffset(!1)}function ut(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=De.has(`EXT_color_buffer_half_float`)||De.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new EE(1,1,{generateMipmaps:!0,type:e?Tw:vw,minFilter:_w,samples:Math.max(4,Oe.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:pE.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||ae;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(se),ce=T.getClearAlpha(),ce<1&&T.setClearColor(16777215,.5),T.clear(),we&&Ve.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),ve===!0&&ze.setGlobalState(T.clippingPlanes,r),dt(e,n,r),Ae.updateMultisampleRenderTarget(a),Ae.updateRenderTargetMipmap(a),De.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,ft(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(Ae.updateMultisampleRenderTarget(a),Ae.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(se,ce),d!==void 0&&(r.viewport=d),T.toneMapping=u}function dt(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&ft(o,t,n,s,l,c)}}function ft(e,t,n,r,i,a){D!==null&&i.isNodeMaterial&&D.setObject(e,i),e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function pt(e,t,n){t.isScene!==!0&&(t=Ce);let r=P.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=Fe.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=Fe.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=je.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,$e),l=/* @__PURE__ */ new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return F(e,s),d}else s.uniforms=Fe.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=Fe.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=ze.uniform),F(e,s),r.needsLights=vt(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.sunLights.value=i.state.sun,f.sunLightShadows.value=i.state.sunShadow,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.sunShadowMatrix.value=i.state.sunShadowMatrix,f.sunShadowCascade.value=i.state.sunShadowCascade,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function mt(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=Wj.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function F(e,t){let n=P.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function ht(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function gt(e,t,n,r,i){t.isScene!==!0&&(t=Ce),Ae.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=A===null?T.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:pE.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=je.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=P.get(r),y=x.state.lights;if(ve===!0&&(ye===!0||e!==ie)){let t=e===ie&&r.id===re;ze.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i._colorsTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i._colorsTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==ze.numPlanes||v.numIntersection!==ze.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=pt(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),ee=v.uniforms;if(N.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==re&&(re=r.id,w=!0),v.needsLights){let e=ht(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||ie!==e){N.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(M,`projectionMatrix`,e.projectionMatrix),O.setValue(M,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(M,xe.setFromMatrixPosition(e.matrixWorld)),Oe.logarithmicDepthBuffer&&O.setValue(M,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(M,`isOrthographic`,e.isOrthographicCamera===!0),ie!==e&&(ie=e,w=!0,E=!0)}if(v.needsLights&&(y.state.sunShadowMap.length>0&&O.setValue(M,`sunShadowMap`,y.state.sunShadowMap,Ae),y.state.directionalShadowMap.length>0&&O.setValue(M,`directionalShadowMap`,y.state.directionalShadowMap,Ae),y.state.spotShadowMap.length>0&&O.setValue(M,`spotShadowMap`,y.state.spotShadowMap,Ae),y.state.pointShadowMap.length>0&&O.setValue(M,`pointShadowMap`,y.state.pointShadowMap,Ae)),i.isSkinnedMesh){O.setOptional(M,i,`bindMatrix`),O.setOptional(M,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(M,`boneTexture`,e.boneTexture,Ae))}i.isBatchedMesh&&(O.setOptional(M,i,`batchingTexture`),O.setValue(M,`batchingTexture`,i._matricesTexture,Ae),O.setOptional(M,i,`batchingIdTexture`),O.setValue(M,`batchingIdTexture`,i._indirectTexture,Ae),O.setOptional(M,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(M,`batchingColorTexture`,i._colorsTexture,Ae));let k=n.morphAttributes;if((k.position!==void 0||k.normal!==void 0||k.color!==void 0)&&He.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(M,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(ee.envMapIntensity.value=t.environmentIntensity),ee.dfgLUT!==void 0&&(ee.dfgLUT.value=dN()),w){if(O.setValue(M,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&_t(ee,E),a&&r.fog===!0&&Ie.refreshFogUniforms(ee,a),Ie.refreshMaterialUniforms(ee,r,de,ue,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;ee.probesSH.value=e.texture,ee.probesMin.value.copy(e.boundingBox.min),ee.probesMax.value.copy(e.boundingBox.max),ee.probesResolution.value.copy(e.resolution)}Wj.upload(M,mt(v),ee,Ae)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(Wj.upload(M,mt(v),ee,Ae),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(M,`center`,i.center),O.setValue(M,`modelViewMatrix`,i.modelViewMatrix),O.setValue(M,`normalMatrix`,i.normalMatrix),O.setValue(M,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];qe.update(n,S),qe.bind(n,S)}}return S}function _t(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.sunLights.needsUpdate=t,e.sunLightShadows.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function vt(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return te},this.getActiveMipmapLevel=function(){return ne},this.getRenderTarget=function(){return A},this.setRenderTargetTextures=function(e,t,n){let r=P.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),P.get(e.texture).__webglTexture=t,P.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=P.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0},this.setRenderTarget=function(e,t=0,n=0){A=e,te=t,ne=n;let r=null,i=!1,a=!1;if(e){let o=P.get(e);if(o.__useDefaultFramebuffer!==void 0){N.bindFramebuffer(M.FRAMEBUFFER,o.__webglFramebuffer),ae.copy(e.viewport),oe.copy(e.scissor),j=e.scissorTest,N.viewport(ae),N.scissor(oe),N.setScissorTest(j),re=-1;return}if(o.__webglFramebuffer===void 0)Ae.setupRenderTarget(e);else if(o.__hasExternalTextures)Ae.rebindTextures(e,P.get(e.texture).__webglTexture,P.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&P.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.`);Ae.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=P.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&Ae.useMultisampledRTT(e)===!1?P.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,ae.copy(e.viewport),oe.copy(e.scissor),j=e.scissorTest}else ae.copy(me).multiplyScalar(de).floor(),oe.copy(he).multiplyScalar(de).floor(),j=ge;if(n!==0&&(r=O),N.bindFramebuffer(M.FRAMEBUFFER,r)&&N.drawBuffers(e,r),N.viewport(ae),N.scissor(oe),N.setScissorTest(j),i){let r=P.get(e.texture);M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=P.get(e.textures[t]);M.framebufferTextureLayer(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=P.get(e.texture);M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,t.__webglTexture,n)}re=-1};function yt(e){let t=P.get(e);return(t.__readFormat!==e.format||t.__readType!==e.type)&&(t.__readFormat=e.format,t.__readType=e.type,t.__formatReadable=Oe.textureFormatReadable(e.format),t.__typeReadable=Oe.textureTypeReadable(e.type)),t}this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){Y(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=P.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){N.bindFramebuffer(M.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;e.textures.length>1&&M.readBuffer(M.COLOR_ATTACHMENT0+s);let u=yt(o);if(u.__formatReadable===!1){Y(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(u.__typeReadable===!1){Y(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&M.readPixels(t,n,r,i,Ge.convert(c),Ge.convert(l),a)}finally{let e=A===null?null:P.get(A).__webglFramebuffer;N.bindFramebuffer(M.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=P.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){N.bindFramebuffer(M.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;e.textures.length>1&&M.readBuffer(M.COLOR_ATTACHMENT0+s);let d=yt(o);if(d.__formatReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(d.__typeReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let f=M.createBuffer();M.bindBuffer(M.PIXEL_PACK_BUFFER,f),M.bufferData(M.PIXEL_PACK_BUFFER,a.byteLength,M.STREAM_READ),M.readPixels(t,n,r,i,Ge.convert(l),Ge.convert(u),0),M.bindBuffer(M.PIXEL_PACK_BUFFER,null);let p=A===null?null:P.get(A).__webglFramebuffer;N.bindFramebuffer(M.FRAMEBUFFER,p);let m=M.fenceSync(M.SYNC_GPU_COMMANDS_COMPLETE,0);return M.flush(),await qT(M,m,4),M.bindBuffer(M.PIXEL_PACK_BUFFER,f),M.getBufferSubData(M.PIXEL_PACK_BUFFER,0,a),M.bindBuffer(M.PIXEL_PACK_BUFFER,null),M.deleteBuffer(f),M.deleteSync(m),a}throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)}},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;Ae.setTexture2D(e,0),M.copyTexSubImage2D(M.TEXTURE_2D,n,0,0,o,s,i,a),N.unbindTexture()},this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=Ge.convert(t.format),_=Ge.convert(t.type),v;t.isData3DTexture?(Ae.setTexture3D(t,0),v=M.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(Ae.setTexture2DArray(t,0),v=M.TEXTURE_2D_ARRAY):(Ae.setTexture2D(t,0),v=M.TEXTURE_2D),N.activeTexture(M.TEXTURE0),N.pixelStorei(M.UNPACK_FLIP_Y_WEBGL,t.flipY),N.pixelStorei(M.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),N.pixelStorei(M.UNPACK_ALIGNMENT,t.unpackAlignment);let y=N.getParameter(M.UNPACK_ROW_LENGTH),b=N.getParameter(M.UNPACK_IMAGE_HEIGHT),x=N.getParameter(M.UNPACK_SKIP_PIXELS),S=N.getParameter(M.UNPACK_SKIP_ROWS),C=N.getParameter(M.UNPACK_SKIP_IMAGES);N.pixelStorei(M.UNPACK_ROW_LENGTH,h.width),N.pixelStorei(M.UNPACK_IMAGE_HEIGHT,h.height),N.pixelStorei(M.UNPACK_SKIP_PIXELS,l),N.pixelStorei(M.UNPACK_SKIP_ROWS,u),N.pixelStorei(M.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=P.get(e),r=P.get(t),h=P.get(n.__renderTarget),g=P.get(r.__renderTarget);N.bindFramebuffer(M.READ_FRAMEBUFFER,h.__webglFramebuffer),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(M.framebufferTextureLayer(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,P.get(e).__webglTexture,i,d+n),M.framebufferTextureLayer(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,P.get(t).__webglTexture,a,m+n)),M.blitFramebuffer(l,u,o,s,f,p,o,s,M.DEPTH_BUFFER_BIT,M.NEAREST);N.bindFramebuffer(M.READ_FRAMEBUFFER,null),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||P.has(e)){let n=P.get(e),r=P.get(t);N.bindFramebuffer(M.READ_FRAMEBUFFER,ee),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,k);for(let e=0;e<c;e++)w?M.framebufferTextureLayer(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):M.framebufferTexture2D(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,n.__webglTexture,i),T?M.framebufferTextureLayer(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):M.framebufferTexture2D(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,r.__webglTexture,a),i===0?T?M.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):M.copyTexSubImage2D(v,a,f,p,l,u,o,s):M.blitFramebuffer(l,u,o,s,f,p,o,s,M.COLOR_BUFFER_BIT,M.NEAREST);N.bindFramebuffer(M.READ_FRAMEBUFFER,null),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?M.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?M.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):M.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?M.texSubImage2D(M.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?M.compressedTexSubImage2D(M.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):M.texSubImage2D(M.TEXTURE_2D,a,f,p,o,s,g,_,h);N.pixelStorei(M.UNPACK_ROW_LENGTH,y),N.pixelStorei(M.UNPACK_IMAGE_HEIGHT,b),N.pixelStorei(M.UNPACK_SKIP_PIXELS,x),N.pixelStorei(M.UNPACK_SKIP_ROWS,S),N.pixelStorei(M.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&M.generateMipmap(v),N.unbindTexture()},this.initRenderTarget=function(e){P.get(e).__webglFramebuffer===void 0&&Ae.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?Ae.setTextureCube(e,0):e.isData3DTexture?Ae.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?Ae.setTexture2DArray(e,0):Ae.setTexture2D(e,0),N.unbindTexture()},this.resetState=function(){te=0,ne=0,A=null,N.reset(),Ke.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return RT}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=pE._getDrawingBufferColorSpace(e),t.unpackColorSpace=pE._getUnpackColorSpace()}};function pN(e){return new Z().set(...e)}var mN=class{lenses;uniform;named;constructor(e,t){this.lenses=e,this.uniform=t,this.named=Array.from({length:e.length})}follow(e){for(let[t,n]of this.lenses.entries()){let r=e[n.frameSlot];if(!r)continue;let i=el($c,r.colorSpace.matrix);i!==this.named[t]&&(this.named[t]=i,this.uniform.value[t]=pN(ml(n.displayConversion.matrix,i)))}}};function hN(e){return Number.isSafeInteger(e)?e.toFixed(1):String(e)}var gN=0,_N=1,vN=[[`CONVERSION_HLG_TO_SDR_BT709`,_N],[`HLG_A`,hN(tl.a)],[`HLG_B`,hN(tl.b)],[`HLG_C`,hN(tl.c)],[`HLG_SEGMENT_JOIN`,hN(tl.segmentJoin)],[`HLG_SQUARE_SEGMENT_DIVISOR`,hN(tl.squareSegmentDivisor)],[`HLG_LOG_SEGMENT_DIVISOR`,hN(tl.logSegmentDivisor)],[`BT709_LUMINANCE_RED`,hN(rl[0])],[`BT709_LUMINANCE_GREEN`,hN(rl[1])],[`BT709_LUMINANCE_BLUE`,hN(rl[2])]];function yN(e){let t=e.map(e=>bN(e.displayConversion));return{uLensConversion:{value:t.map(e=>e.kind)},uLensMatrixCorrection:{value:e.map(()=>pN(Nr))},uLensGamut:{value:t.map(e=>e.gamut)},uLensTone:{value:t.map(e=>e.tone)}}}function bN(e){switch(e.kind){case`as-recorded`:return{kind:gN,gamut:pN(Nr),tone:new wE};case`hlg-to-sdr-bt709`:{let{exposure:t,kneeStart:n,ceiling:r,exponent:i}=e.tone;return{kind:_N,gamut:pN(e.gamut),tone:new wE(t,n,r,i)}}}}var xN={fast:{minFilter:hw,generateMipmaps:!1,anisotropy:1,shaderSampling:0},balanced:{minFilter:_w,generateMipmaps:!0,anisotropy:4,shaderSampling:1},high:{minFilter:_w,generateMipmaps:!0,anisotropy:8,shaderSampling:2}},SN=0,CN=1,wN=Object.fromEntries([[`MAX_LENSES`,2],[`LENS_MEI`,SN],[`LENS_RADIAL_POLYNOMIAL`,CN],[`MEI_RADIAL_TERMS`,ce.radial],[`MEI_TANGENTIAL_ORDERS`,ce.tangential],[`MEI_THIN_PRISM_ORDERS`,ce.thinPrism],...vN,[`SAMPLING_BILINEAR`,0],[`SAMPLING_TRILINEAR`,1],[`SAMPLING_SUPERSAMPLED`,2]]);function TN(e,t){let n=VN(e.lenses,`a stitching setup has one or two lenses`);return{...EN(e),...DN(n),...MN(n),...yN(n),uTexture0:{value:t[0]??null},uTexture1:{value:t[1]??null}}}function EN(e){return{uLensCount:{value:e.lenses.length},uViewRotation:{value:new Z},uStabilization:{value:new Z},uPlaneHalfExtent:{value:1},uPictureAspect:{value:1},uScreenArea:{value:Array.from({length:2},()=>new wE(0,0,1,1))},uFeather:{value:new aE(e.feather.start,e.feather.end)}}}function DN(e){let t=e.map(e=>kN(e.projection));return{uLensRotation:{value:e.map(e=>pN(e.rotation))},uLensKind:{value:t.map(e=>e.kind)},uLensPrincipalPoint:{value:e.map(e=>BN(e.projection.principalPoint))},uLensFocal:{value:t.map(e=>e.focal)},uLensXi:{value:t.map(e=>e.xi)},uLensRadial:{value:t.flatMap(e=>e.radial)},uLensTangential:{value:t.flatMap(e=>e.tangential)},uLensThinPrism:{value:t.flatMap(e=>e.thinPrism)},uLensPolynomial:{value:t.map(e=>e.polynomial)},uLensHalfFov:{value:e.map(e=>e.halfFieldOfView)}}}var ON={radial:[],tangential:[],thinPrism:[]};function kN(e){switch(e.kind){case`mei`:return{kind:SN,focal:new aE(...e.focal),xi:e.xi,...AN(e.distortion),polynomial:new wE};case`radial-polynomial`:return{kind:CN,focal:new aE,xi:0,...AN(ON),polynomial:new wE(...e.coefficients)}}}function AN(e){return{radial:jN(e.radial,ce.radial,()=>0),tangential:jN(e.tangential.map(e=>new aE(e.p1,e.p2)),ce.tangential,()=>new aE),thinPrism:jN(e.thinPrism.map(e=>new aE(e.x,e.y)),ce.thinPrism,()=>new aE)}}function jN(e,t,n){return j(e.length<=t,`a Mei lens has ${e.length} terms of a family the shader holds ${t} of`),Array.from({length:t},(t,r)=>e[r]??n())}function MN(e){return{uLensWindow:{value:e.map(e=>new wE(e.window.x,e.window.y,e.window.width,e.window.height))},uLensRegion:{value:e.map(e=>new wE(e.region.x,e.region.y,e.region.width,e.region.height))},uLensTexture:{value:e.map(e=>e.frameSlot)},uLensGain:{value:e.map(()=>new X(1,1,1))},uSampling:{value:0}}}function NN(e,t){e.uSampling.value=t.shaderSampling}function PN(e,t){e.uStabilization.value=pN(t)}function FN(e,t,n){se(t,e.uLensCount.value,`lens`),e.uLensGain.value[t]?.set(...n)}var IN={rotation:Nr,planeHalfExtent:1,pictureAspect:1};function LN(e,t,n){let r=RN(t,n);e.uViewRotation.value=pN(r.rotation),e.uPlaneHalfExtent.value=r.planeHalfExtent,e.uPictureAspect.value=r.pictureAspect,e.uScreenArea.value=VN(r.areas,`a picture fills one area per lens at most`).map(e=>zN(e))}function RN(e,t){switch(e.kind){case`rectilinear`:return{rotation:e.rotation,planeHalfExtent:Hs(e.fieldOfView),pictureAspect:Us(e.area,t),areas:[e.area]};case`equirectangular`:return{...IN,rotation:e.rotation,areas:[e.area]};case`lens-tiles`:return{...IN,areas:e.tiles}}}function zN(e){return new wE(e.x,e.y,e.width,e.height)}function BN(e){return new aE(e.x,e.y)}function VN(e,t){let n=e.at(-1);return j(n!==void 0&&e.length<=2,t),Array.from({length:2},(t,r)=>e[r]??n)}var HN=`// One triangle covering the whole viewport; the fragment shader does all the work.
|
|
4222
|
+
}`,mA=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new eE(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new dE({vertexShader:fA,fragmentShader:pA,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new VT(new nE(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},hA=class extends sC{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new mA,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new Y,C=null,w=null,T=new VE;T.viewport=new FC;let E=new VE;E.viewport=new FC;let D=[T,E],O=new KE,k=null,A=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new gw,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new gw,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new gw,b[e]=t),t.getHandSpace()};function ee(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function te(){r.removeEventListener(`select`,ee),r.removeEventListener(`selectstart`,ee),r.removeEventListener(`selectend`,ee),r.removeEventListener(`squeeze`,ee),r.removeEventListener(`squeezestart`,ee),r.removeEventListener(`squeezeend`,ee),r.removeEventListener(`end`,te),r.removeEventListener(`inputsourceschange`,j);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}k=null,A=null,h.reset();for(let e in g)delete g[e];if(e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,se.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),w!==null){let e=w.camera;e.fov=w.fov,e.zoom=w.zoom,e.updateProjectionMatrix(),w=null}n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&q(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&q(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,ee),r.addEventListener(`selectstart`,ee),r.addEventListener(`selectend`,ee),r.addEventListener(`squeeze`,ee),r.addEventListener(`squeezestart`,ee),r.addEventListener(`squeezeend`,ee),r.addEventListener(`end`,te),r.addEventListener(`inputsourceschange`,j),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?qx:Kx,a=_.stencil?Bx:Fx);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new LC(d.textureWidth,d.textureHeight,{format:Gx,type:Ax,depthTexture:new QT(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new LC(f.framebufferWidth,f.framebufferHeight,{format:Gx,type:Ax,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),se.setContext(r),se.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function j(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let ne=new X,re=new X;function M(e,t,n){ne.setFromMatrixPosition(t.matrixWorld),re.setFromMatrixPosition(n.matrixWorld);let r=ne.distanceTo(re),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function ie(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),O.near=E.near=T.near=t,O.far=E.far=T.far=n,(k!==O.near||A!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),k=O.near,A=O.far),O.layers.mask=e.layers.mask|6,T.layers.mask=O.layers.mask&-5,E.layers.mask=O.layers.mask&-3;let i=e.parent,a=O.cameras;ie(O,i);for(let e=0;e<a.length;e++)ie(a[e],i);a.length===2?M(O,T,E):O.projectionMatrix.copy(T.projectionMatrix),w===null&&e.isPerspectiveCamera&&(w={camera:e,fov:e.fov,zoom:e.zoom}),N(e,O,i)};function N(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=uC*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(d!==null||f!==null)return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(O)},this.getCameraTexture=function(e){return g[e]};let ae=null;function oe(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==O.cameras.length&&(O.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=D[n];o===void 0&&(o=new VE,o.layers.enable(n),o.viewport=new FC,D[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(O.matrix.copy(o.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),i===!0&&O.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new eE,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}ae&&ae(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let se=new sD;se.setAnimationLoop(oe),this.setAnimationLoop=function(e){ae=e},this.dispose=function(){}}},gA=/*@__PURE__*/ new BC,_A=/*@__PURE__*/ new Z;_A.set(-1,0,0,0,1,0,0,0,1);function vA(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,sE(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(gA.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(_A),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.retroreflectivity>0&&(e.retroreflectivity.value=t.retroreflectivity),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function yA(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(g(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,v));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return J(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let e=0,t=r.length;e<t;e++){let t=r[e];if(Array.isArray(t))for(let n=0,r=t.length;n<r;n++)p(t[n],e,n,a);else p(t,e,0,a)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(t,n,r,i){if(h(t,n,r,i)===!0){let n=t.__offset,r=t.value;if(Array.isArray(r)){let e=0;for(let n=0;n<r.length;n++){let i=r[n],a=_(i);m(i,t.__data,e),typeof i!=`number`&&typeof i!=`boolean`&&!i.isMatrix3&&!ArrayBuffer.isView(i)&&(e+=a.storage/Float32Array.BYTES_PER_ELEMENT)}}else m(r,t.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,n,t.__data)}}function m(e,t,n){typeof e==`number`||typeof e==`boolean`?t[0]=e:e.isMatrix3?(t[0]=e.elements[0],t[1]=e.elements[1],t[2]=e.elements[2],t[3]=0,t[4]=e.elements[3],t[5]=e.elements[4],t[6]=e.elements[5],t[7]=0,t[8]=e.elements[6],t[9]=e.elements[7],t[10]=e.elements[8],t[11]=0):ArrayBuffer.isView(e)?t.set(new e.constructor(e.buffer,e.byteOffset,t.length)):e.toArray(t,n)}function h(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return r[a]=typeof i==`number`||typeof i==`boolean`?i:ArrayBuffer.isView(i)?i.slice():i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function g(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=_(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function _(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?q(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):q(`WebGLRenderer: Unsupported uniform value type.`,e),t}function v(t){let n=t.target;n.removeEventListener(`dispose`,v);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function y(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:y}}var bA=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),xA=null;function SA(){return xA===null&&(xA=new WT(bA,16,16,Xx,Lx),xA.name=`DFG_LUT`,xA.minFilter=Dx,xA.magFilter=Dx,xA.wrapS=Sx,xA.wrapT=Sx,xA.generateMipmaps=!1,xA.needsUpdate=!0),xA}var CA=class{constructor(e={}){let{canvas:t=eC(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Ax}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=/* @__PURE__ */ new Set([Qx,Zx,Yx]),g=/* @__PURE__ */ new Set([Ax,Fx,Nx,Bx,Rx,zx]),_=/* @__PURE__ */ new Uint32Array(4),v=/* @__PURE__ */ new Int32Array(4),y=new X,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null,O=null,k=null,A=null;this._outputColorSpace=US;let ee=0,te=0,j=null,ne=-1,re=null,M=new FC,ie=new FC,N=null,ae=new xw(0),oe=0,se=t.width,ce=t.height,le=1,ue=null,de=null,fe=new FC(0,0,se,ce),pe=new FC(0,0,se,ce),me=!1,he=new JT,ge=!1,_e=!1,ve=new BC,ye=new X,be=new FC,xe={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Se=!1;function Ce(){return j===null?le:1}let P=n;function we(e,n){return t.getContext(e,n)}let Te,Ee,F,De,I,L,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue,We;try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r186`),t.addEventListener(`webglcontextlost`,qe,!1),t.addEventListener(`webglcontextrestored`,Je,!1),t.addEventListener(`webglcontextcreationerror`,Ye,!1),P===null){let t=`webgl2`;if(P=we(t,e),P===null)throw we(t)?Error(`THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.`):Error(`THREE.WebGLRenderer: Error creating WebGL context.`)}Ge()}catch(e){throw t.removeEventListener(`webglcontextlost`,qe,!1),t.removeEventListener(`webglcontextrestored`,Je,!1),t.removeEventListener(`webglcontextcreationerror`,Ye,!1),J(`WebGLRenderer: `+e.message),e}function Ge(){Te=new VD(P),Te.init(),He=new dA(P,Te),Ee=new gD(P,Te,e,He),F=new lA(P,Te),Ee.reversedDepthBuffer&&d&&F.buffers.depth.setReversed(!0),O=P.createFramebuffer(),k=P.createFramebuffer(),A=P.createFramebuffer(),De=new WD(P),I=new Uk,L=new uA(P,Te,F,I,Ee,He,De),Oe=new BD(T),ke=new cD(P),Ue=new mD(P,ke),Ae=new HD(P,ke,De,Ue),je=new KD(P,Ae,ke,Ue,De),ze=new GD(P,Ee,L),Ie=new _D(I),Me=new Hk(T,Oe,Te,Ee,Ue,Ie),Ne=new vA(T,I),Pe=new qk,Fe=new eA(Te),Re=new pD(T,Oe,F,je,p,s),Le=new cA(T,je,Ee),We=new yA(P,De,Ee,F),Be=new hD(P,Te,De),Ve=new UD(P,Te,De),De.programs=Me.programs,T.capabilities=Ee,T.extensions=Te,T.properties=I,T.renderLists=Pe,T.shadowMap=Le,T.state=F,T.info=De}m!==1009&&(w=new JD(m,t.width,t.height,o,r,i));let Ke=new hA(T,P);this.xr=Ke,this.getContext=function(){return P},this.getContextAttributes=function(){return P.getContextAttributes()},this.forceContextLoss=function(){let e=Te.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=Te.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return le},this.setPixelRatio=function(e){e!==void 0&&(le=e,this.setSize(se,ce,!1))},this.getSize=function(e){return e.set(se,ce)},this.setSize=function(e,n,r=!0){if(Ke.isPresenting){q(`WebGLRenderer: Can't change size while VR device is presenting.`);return}se=e,ce=n,t.width=Math.floor(e*le),t.height=Math.floor(n*le),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(se*le,ce*le).floor()},this.setDrawingBufferSize=function(e,n,r){se=e,ce=n,le=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){J(`WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){q(`WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(M)},this.getViewport=function(e){return e.copy(fe)},this.setViewport=function(e,t,n,r){e.isVector4?fe.set(e.x,e.y,e.z,e.w):fe.set(e,t,n,r),F.viewport(M.copy(fe).multiplyScalar(le).round())},this.getScissor=function(e){return e.copy(pe)},this.setScissor=function(e,t,n,r){e.isVector4?pe.set(e.x,e.y,e.z,e.w):pe.set(e,t,n,r),F.scissor(ie.copy(pe).multiplyScalar(le).round())},this.getScissorTest=function(){return me},this.setScissorTest=function(e){F.setScissorTest(me=e)},this.setOpaqueSort=function(e){ue=e},this.setTransparentSort=function(e){de=e},this.getClearColor=function(e){return e.copy(Re.getClearColor())},this.setClearColor=function(){Re.setClearColor(...arguments)},this.getClearAlpha=function(){return Re.getClearAlpha()},this.setClearAlpha=function(){Re.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(j!==null){let t=j.texture.format;e=h.has(t)}if(e){let e=j.texture.type,t=g.has(e),n=Re.getClearColor(),r=Re.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,P.clearBufferuiv(P.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,P.clearBufferiv(P.COLOR,0,v))}else r|=P.COLOR_BUFFER_BIT}t&&(r|=P.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=P.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&P.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,qe,!1),t.removeEventListener(`webglcontextrestored`,Je,!1),t.removeEventListener(`webglcontextcreationerror`,Ye,!1),Re.dispose(),Pe.dispose(),Fe.dispose(),I.dispose(),Oe.dispose(),je.dispose(),Ue.dispose(),We.dispose(),Me.dispose(),Ke.dispose(),Ke.removeEventListener(`sessionstart`,nt),Ke.removeEventListener(`sessionend`,rt),it.stop()};function qe(e){e.preventDefault(),nC(`WebGLRenderer: Context Lost.`),E=!0}function Je(){nC(`WebGLRenderer: Context Restored.`),E=!1;let e=De.autoReset,t=Le.enabled,n=Le.autoUpdate,r=Le.needsUpdate,i=Le.type;Ge(),De.autoReset=e,Le.enabled=t,Le.autoUpdate=n,Le.needsUpdate=r,Le.type=i}function Ye(e){J(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function Xe(e){let t=e.target;t.removeEventListener(`dispose`,Xe),Ze(t)}function Ze(e){Qe(e),I.remove(e)}function Qe(e){let t=I.get(e).programs;t!==void 0&&(t.forEach(function(e){Me.releaseProgram(e)}),e.isShaderMaterial&&Me.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=xe);let o=i.isMesh&&i.matrixWorld.determinantAffine()<0,s=R(e,t,n,r,i);F.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=Ae.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Ue.setup(i,r,s,n,c);let h,g=Be;if(c!==null&&(h=ke.get(c),g=Ve,g.setIndex(h)),i.isMesh)r.wireframe===!0?(F.setLineWidth(r.wireframeLinewidth*Ce()),g.setMode(P.LINES)):g.setMode(P.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),F.setLineWidth(e*Ce()),i.isLineSegments?g.setMode(P.LINES):i.isLineLoop?g.setMode(P.LINE_LOOP):g.setMode(P.LINE_STRIP)}else i.isPoints?g.setMode(P.POINTS):i.isSprite&&g.setMode(P.TRIANGLES);if(i.isBatchedMesh){if(Te.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?ke.get(c).bytesPerElement:1,o=I.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(P,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function $e(e,t,n,r){D!==null&&e.isNodeMaterial&&D.setObject(r,e),ge===!0&&Ie.setState(e,n,!1),e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,ut(e,t,r),e.side=0,e.needsUpdate=!0,ut(e,t,r),e.side=2):ut(e,t,r)}this.compile=function(e,t,n=null){n===null&&(n=e),D!==null&&D.renderStart(e,t,n),x=Fe.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights(),D!==null&&D.updateLights(x.state.lightsArray),_e=this.localClippingEnabled,ge=Ie.init(this.clippingPlanes,_e),ge===!0&&Ie.setGlobalState(this.clippingPlanes,t),D!==null&&Le.render(x.state.shadowsArray,n,t);let r=/* @__PURE__ */ new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let i=e.material;if(i){if(Array.isArray(i))for(let a=0;a<i.length;a++){let o=i[a];$e(o,n,t,e),r.add(o)}else $e(i,n,t,e),r.add(i)}}),x=C.pop(),D!==null&&D.renderEnd(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){let t=I.get(e).currentProgram;(t===void 0||t.isReady())&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}Te.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let et=null;function tt(e){et&&et(e)}function nt(){it.stop()}function rt(){it.start()}let it=new sD;it.setAnimationLoop(tt),typeof self<`u`&&it.setContext(self),this.setAnimationLoop=function(e){et=e,Ke.setAnimationLoop(e),e===null?it.stop():it.start()},Ke.addEventListener(`sessionstart`,nt),Ke.addEventListener(`sessionend`,rt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){J(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=Ke.enabled===!0&&Ke.isPresenting===!0,r=w!==null&&(j===null||n)&&w.begin(T,j);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ke.enabled===!0&&Ke.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(Ke.cameraAutoUpdate===!0&&Ke.updateCamera(t),t=Ke.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,j),x=Fe.get(e,C.length),x.init(t),x.state.textureUnits=L.getTextureUnits(),C.push(x),ve.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),he.setFromProjectionMatrix(ve,XS,t.reversedDepth),_e=this.localClippingEnabled,ge=Ie.init(this.clippingPlanes,_e),b=Pe.get(e,S.length),b.init(),S.push(b),Ke.enabled===!0&&Ke.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&at(e,t,-1/0,T.sortObjects)}at(e,t,0,T.sortObjects),b.finish(),D!==null&&D.updateLights(x.state.lightsArray),T.sortObjects===!0&&b.sort(ue,de),Se=Ke.enabled===!1||Ke.isPresenting===!1||Ke.hasDepthSensing()===!1,Se&&Re.addToRenderList(b,e),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ge===!0&&Ie.beginShadows();let i=x.state.shadowsArray;if(Le.render(i,e,t),ge===!0&&Ie.endShadows(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];st(n,r,e,a)}Se&&Re.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];ot(b,e,n,n.viewport)}}else r.length>0&&st(n,r,e,t),Se&&Re.render(e),ot(b,e,t)}j!==null&&te===0&&(L.updateMultisampleRenderTarget(j),L.updateRenderTargetMipmap(j)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),Ue.resetDefaultState(),ne=-1,re=null,C.pop(),C.length>0?(x=C[C.length-1],L.setTextureUnits(x.state.textureUnits),ge===!0&&Ie.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function at(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||e.intersectsFrustum(he)){r&&be.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ve);let i=je.update(e),a=e.material;a.visible&&b.push(e,i,a,n,be.z,null,t)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||e.intersectsFrustum(he))){let i=je.update(e),a=e.material;if(r&&(e.boundingSphere===void 0?(i.boundingSphere===null&&i.computeBoundingSphere(),be.copy(i.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),be.copy(e.boundingSphere.center)),be.applyMatrix4(e.matrixWorld).applyMatrix4(ve)),Array.isArray(a)){let r=i.groups;for(let o=0,s=r.length;o<s;o++){let s=r[o],c=a[s.materialIndex];c&&c.visible&&b.push(e,i,c,n,be.z,s,t)}}else a.visible&&b.push(e,i,a,n,be.z,null,t)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)at(i[e],t,n,r)}function ot(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),ge===!0&&Ie.setGlobalState(T.clippingPlanes,n),r&&F.viewport(M.copy(r)),i.length>0&&ct(i,t,n),a.length>0&&ct(a,t,n),o.length>0&&ct(o,t,n),F.buffers.depth.setTest(!0),F.buffers.depth.setMask(!0),F.buffers.color.setMask(!0),F.setPolygonOffset(!1)}function st(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=Te.has(`EXT_color_buffer_half_float`)||Te.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new LC(1,1,{generateMipmaps:!0,type:e?Lx:Ax,minFilter:kx,samples:Math.max(4,Ee.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:wC.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||M;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(ae),oe=T.getClearAlpha(),oe<1&&T.setClearColor(16777215,.5),T.clear(),Se&&Re.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),ge===!0&&Ie.setGlobalState(T.clippingPlanes,r),ct(e,n,r),L.updateMultisampleRenderTarget(a),L.updateRenderTargetMipmap(a),Te.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,lt(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(L.updateMultisampleRenderTarget(a),L.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(ae,oe),d!==void 0&&(r.viewport=d),T.toneMapping=u}function ct(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&<(o,t,n,s,l,c)}}function lt(e,t,n,r,i,a){D!==null&&i.isNodeMaterial&&D.setObject(e,i),e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function ut(e,t,n){t.isScene!==!0&&(t=xe);let r=I.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=Me.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=Me.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=Oe.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,Xe),l=/* @__PURE__ */ new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return ft(e,s),d}else s.uniforms=Me.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=Me.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=Ie.uniform),ft(e,s),r.needsLights=ht(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.sunLights.value=i.state.sun,f.sunLightShadows.value=i.state.sunShadow,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.sunShadowMatrix.value=i.state.sunShadowMatrix,f.sunShadowCascade.value=i.state.sunShadowCascade,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function dt(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=tk.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ft(e,t){let n=I.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function pt(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function R(e,t,n,r,i){t.isScene!==!0&&(t=xe),L.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=j===null?T.outputColorSpace:j.isXRRenderTarget===!0?j.texture.colorSpace:wC.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=Oe.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(j===null||j.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=I.get(r),y=x.state.lights;if(ge===!0&&(_e===!0||e!==re)){let t=e===re&&r.id===ne;Ie.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i._colorsTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i._colorsTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Ie.numPlanes||v.numIntersection!==Ie.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=ut(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),k=v.uniforms;if(F.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==ne&&(ne=r.id,w=!0),v.needsLights){let e=pt(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||re!==e){F.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(P,`projectionMatrix`,e.projectionMatrix),O.setValue(P,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(P,ye.setFromMatrixPosition(e.matrixWorld)),Ee.logarithmicDepthBuffer&&O.setValue(P,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(P,`isOrthographic`,e.isOrthographicCamera===!0),re!==e&&(re=e,w=!0,E=!0)}if(v.needsLights&&(y.state.sunShadowMap.length>0&&O.setValue(P,`sunShadowMap`,y.state.sunShadowMap,L),y.state.directionalShadowMap.length>0&&O.setValue(P,`directionalShadowMap`,y.state.directionalShadowMap,L),y.state.spotShadowMap.length>0&&O.setValue(P,`spotShadowMap`,y.state.spotShadowMap,L),y.state.pointShadowMap.length>0&&O.setValue(P,`pointShadowMap`,y.state.pointShadowMap,L)),i.isSkinnedMesh){O.setOptional(P,i,`bindMatrix`),O.setOptional(P,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(P,`boneTexture`,e.boneTexture,L))}i.isBatchedMesh&&(O.setOptional(P,i,`batchingTexture`),O.setValue(P,`batchingTexture`,i._matricesTexture,L),O.setOptional(P,i,`batchingIdTexture`),O.setValue(P,`batchingIdTexture`,i._indirectTexture,L),O.setOptional(P,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(P,`batchingColorTexture`,i._colorsTexture,L));let A=n.morphAttributes;if((A.position!==void 0||A.normal!==void 0||A.color!==void 0)&&ze.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(P,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),k.dfgLUT!==void 0&&(k.dfgLUT.value=SA()),w){if(O.setValue(P,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&mt(k,E),a&&r.fog===!0&&Ne.refreshFogUniforms(k,a),Ne.refreshMaterialUniforms(k,r,le,ce,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;k.probesSH.value=e.texture,k.probesMin.value.copy(e.boundingBox.min),k.probesMax.value.copy(e.boundingBox.max),k.probesResolution.value.copy(e.resolution)}tk.upload(P,dt(v),k,L)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(tk.upload(P,dt(v),k,L),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(P,`center`,i.center),O.setValue(P,`modelViewMatrix`,i.modelViewMatrix),O.setValue(P,`normalMatrix`,i.normalMatrix),O.setValue(P,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];We.update(n,S),We.bind(n,S)}}return S}function mt(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.sunLights.needsUpdate=t,e.sunLightShadows.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function ht(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return ee},this.getActiveMipmapLevel=function(){return te},this.getRenderTarget=function(){return j},this.setRenderTargetTextures=function(e,t,n){let r=I.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),I.get(e.texture).__webglTexture=t,I.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=I.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0},this.setRenderTarget=function(e,t=0,n=0){j=e,ee=t,te=n;let r=null,i=!1,a=!1;if(e){let o=I.get(e);if(o.__useDefaultFramebuffer!==void 0){F.bindFramebuffer(P.FRAMEBUFFER,o.__webglFramebuffer),M.copy(e.viewport),ie.copy(e.scissor),N=e.scissorTest,F.viewport(M),F.scissor(ie),F.setScissorTest(N),ne=-1;return}if(o.__webglFramebuffer===void 0)L.setupRenderTarget(e);else if(o.__hasExternalTextures)L.rebindTextures(e,I.get(e.texture).__webglTexture,I.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&I.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.`);L.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=I.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&L.useMultisampledRTT(e)===!1?I.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,M.copy(e.viewport),ie.copy(e.scissor),N=e.scissorTest}else M.copy(fe).multiplyScalar(le).floor(),ie.copy(pe).multiplyScalar(le).floor(),N=me;if(n!==0&&(r=O),F.bindFramebuffer(P.FRAMEBUFFER,r)&&F.drawBuffers(e,r),F.viewport(M),F.scissor(ie),F.setScissorTest(N),i){let r=I.get(e.texture);P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=I.get(e.textures[t]);P.framebufferTextureLayer(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=I.get(e.texture);P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,t.__webglTexture,n)}ne=-1};function gt(e){let t=I.get(e);return(t.__readFormat!==e.format||t.__readType!==e.type)&&(t.__readFormat=e.format,t.__readType=e.type,t.__formatReadable=Ee.textureFormatReadable(e.format),t.__typeReadable=Ee.textureTypeReadable(e.type)),t}this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=I.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){F.bindFramebuffer(P.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;e.textures.length>1&&P.readBuffer(P.COLOR_ATTACHMENT0+s);let u=gt(o);if(u.__formatReadable===!1){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(u.__typeReadable===!1){J(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&P.readPixels(t,n,r,i,He.convert(c),He.convert(l),a)}finally{let e=j===null?null:I.get(j).__webglFramebuffer;F.bindFramebuffer(P.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=I.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){F.bindFramebuffer(P.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;e.textures.length>1&&P.readBuffer(P.COLOR_ATTACHMENT0+s);let d=gt(o);if(d.__formatReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(d.__typeReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let f=P.createBuffer();P.bindBuffer(P.PIXEL_PACK_BUFFER,f),P.bufferData(P.PIXEL_PACK_BUFFER,a.byteLength,P.STREAM_READ),P.readPixels(t,n,r,i,He.convert(l),He.convert(u),0),P.bindBuffer(P.PIXEL_PACK_BUFFER,null);let p=j===null?null:I.get(j).__webglFramebuffer;F.bindFramebuffer(P.FRAMEBUFFER,p);let m=P.fenceSync(P.SYNC_GPU_COMMANDS_COMPLETE,0);return P.flush(),await aC(P,m,4),P.bindBuffer(P.PIXEL_PACK_BUFFER,f),P.getBufferSubData(P.PIXEL_PACK_BUFFER,0,a),P.bindBuffer(P.PIXEL_PACK_BUFFER,null),P.deleteBuffer(f),P.deleteSync(m),a}throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)}},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;L.setTexture2D(e,0),P.copyTexSubImage2D(P.TEXTURE_2D,n,0,0,o,s,i,a),F.unbindTexture()},this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=He.convert(t.format),_=He.convert(t.type),v;t.isData3DTexture?(L.setTexture3D(t,0),v=P.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(L.setTexture2DArray(t,0),v=P.TEXTURE_2D_ARRAY):(L.setTexture2D(t,0),v=P.TEXTURE_2D),F.activeTexture(P.TEXTURE0),F.pixelStorei(P.UNPACK_FLIP_Y_WEBGL,t.flipY),F.pixelStorei(P.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),F.pixelStorei(P.UNPACK_ALIGNMENT,t.unpackAlignment);let y=F.getParameter(P.UNPACK_ROW_LENGTH),b=F.getParameter(P.UNPACK_IMAGE_HEIGHT),x=F.getParameter(P.UNPACK_SKIP_PIXELS),S=F.getParameter(P.UNPACK_SKIP_ROWS),C=F.getParameter(P.UNPACK_SKIP_IMAGES);F.pixelStorei(P.UNPACK_ROW_LENGTH,h.width),F.pixelStorei(P.UNPACK_IMAGE_HEIGHT,h.height),F.pixelStorei(P.UNPACK_SKIP_PIXELS,l),F.pixelStorei(P.UNPACK_SKIP_ROWS,u),F.pixelStorei(P.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=I.get(e),r=I.get(t),h=I.get(n.__renderTarget),g=I.get(r.__renderTarget);F.bindFramebuffer(P.READ_FRAMEBUFFER,h.__webglFramebuffer),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(P.framebufferTextureLayer(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,I.get(e).__webglTexture,i,d+n),P.framebufferTextureLayer(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,I.get(t).__webglTexture,a,m+n)),P.blitFramebuffer(l,u,o,s,f,p,o,s,P.DEPTH_BUFFER_BIT,P.NEAREST);F.bindFramebuffer(P.READ_FRAMEBUFFER,null),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||I.has(e)){let n=I.get(e),r=I.get(t);F.bindFramebuffer(P.READ_FRAMEBUFFER,k),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,A);for(let e=0;e<c;e++)w?P.framebufferTextureLayer(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):P.framebufferTexture2D(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,n.__webglTexture,i),T?P.framebufferTextureLayer(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):P.framebufferTexture2D(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,r.__webglTexture,a),i===0?T?P.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):P.copyTexSubImage2D(v,a,f,p,l,u,o,s):P.blitFramebuffer(l,u,o,s,f,p,o,s,P.COLOR_BUFFER_BIT,P.NEAREST);F.bindFramebuffer(P.READ_FRAMEBUFFER,null),F.bindFramebuffer(P.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?P.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?P.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):P.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?P.texSubImage2D(P.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?P.compressedTexSubImage2D(P.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):P.texSubImage2D(P.TEXTURE_2D,a,f,p,o,s,g,_,h);F.pixelStorei(P.UNPACK_ROW_LENGTH,y),F.pixelStorei(P.UNPACK_IMAGE_HEIGHT,b),F.pixelStorei(P.UNPACK_SKIP_PIXELS,x),F.pixelStorei(P.UNPACK_SKIP_ROWS,S),F.pixelStorei(P.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&P.generateMipmap(v),F.unbindTexture()},this.initRenderTarget=function(e){I.get(e).__webglFramebuffer===void 0&&L.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?L.setTextureCube(e,0):e.isData3DTexture?L.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?L.setTexture2DArray(e,0):L.setTexture2D(e,0),F.unbindTexture()},this.resetState=function(){ee=0,te=0,j=null,F.reset(),Ue.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return XS}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=wC._getDrawingBufferColorSpace(e),t.unpackColorSpace=wC._getUnpackColorSpace()}},wA={request:e=>{e()},cancel:()=>{}};function TA(e){return new Z().set(...e)}var EA=class{lenses;uniform;named;constructor(e,t){this.lenses=e,this.uniform=t,this.named=Array.from({length:e.length})}follow(e){for(let[t,n]of this.lenses.entries()){let r=e[n.frameSlot];if(!r)continue;let i=el($c,r.colorSpace.matrix);i!==this.named[t]&&(this.named[t]=i,this.uniform.value[t]=TA(ml(n.displayConversion.matrix,i)))}}};function DA(e){return Number.isSafeInteger(e)?e.toFixed(1):String(e)}var OA=0,kA=1,AA=[[`CONVERSION_HLG_TO_SDR_BT709`,kA],[`HLG_A`,DA(tl.a)],[`HLG_B`,DA(tl.b)],[`HLG_C`,DA(tl.c)],[`HLG_SEGMENT_JOIN`,DA(tl.segmentJoin)],[`HLG_SQUARE_SEGMENT_DIVISOR`,DA(tl.squareSegmentDivisor)],[`HLG_LOG_SEGMENT_DIVISOR`,DA(tl.logSegmentDivisor)],[`BT709_LUMINANCE_RED`,DA(rl[0])],[`BT709_LUMINANCE_GREEN`,DA(rl[1])],[`BT709_LUMINANCE_BLUE`,DA(rl[2])]];function jA(e){let t=e.map(e=>MA(e.displayConversion));return{uLensConversion:{value:t.map(e=>e.kind)},uLensMatrixCorrection:{value:e.map(()=>TA(Mr))},uLensGamut:{value:t.map(e=>e.gamut)},uLensTone:{value:t.map(e=>e.tone)}}}function MA(e){switch(e.kind){case`as-recorded`:return{kind:OA,gamut:TA(Mr),tone:new FC};case`hlg-to-sdr-bt709`:{let{exposure:t,kneeStart:n,ceiling:r,exponent:i}=e.tone;return{kind:kA,gamut:TA(e.gamut),tone:new FC(t,n,r,i)}}}}var NA={fast:{minFilter:Dx,generateMipmaps:!1,anisotropy:1,shaderSampling:0},balanced:{minFilter:kx,generateMipmaps:!0,anisotropy:4,shaderSampling:1},high:{minFilter:kx,generateMipmaps:!0,anisotropy:8,shaderSampling:2}},PA=0,FA=1,IA=Object.fromEntries([[`MAX_LENSES`,2],[`LENS_MEI`,PA],[`LENS_RADIAL_POLYNOMIAL`,FA],[`MEI_RADIAL_TERMS`,oe.radial],[`MEI_TANGENTIAL_ORDERS`,oe.tangential],[`MEI_THIN_PRISM_ORDERS`,oe.thinPrism],...AA,[`SAMPLING_BILINEAR`,0],[`SAMPLING_TRILINEAR`,1],[`SAMPLING_SUPERSAMPLED`,2]]);function LA(e,t){let n=$A(e.lenses,`a stitching setup has one or two lenses`);return{...RA(e),...zA(n),...WA(n),...jA(n),uTexture0:{value:t[0]??null},uTexture1:{value:t[1]??null}}}function RA(e){return{uLensCount:{value:e.lenses.length},uViewRotation:{value:new Z},uStabilization:{value:new Z},uPlaneHalfExtent:{value:1},uPictureAspect:{value:1},uScreenArea:{value:Array.from({length:2},()=>new FC(0,0,1,1))},uFeather:{value:new Y(e.feather.start,e.feather.end)}}}function zA(e){let t=e.map(e=>VA(e.projection));return{uLensRotation:{value:e.map(e=>TA(e.rotation))},uLensKind:{value:t.map(e=>e.kind)},uLensPrincipalPoint:{value:e.map(e=>QA(e.projection.principalPoint))},uLensFocal:{value:t.map(e=>e.focal)},uLensXi:{value:t.map(e=>e.xi)},uLensRadial:{value:t.flatMap(e=>e.radial)},uLensTangential:{value:t.flatMap(e=>e.tangential)},uLensThinPrism:{value:t.flatMap(e=>e.thinPrism)},uLensPolynomial:{value:t.map(e=>e.polynomial)},uLensHalfFov:{value:e.map(e=>e.halfFieldOfView)}}}var BA={radial:[],tangential:[],thinPrism:[]};function VA(e){switch(e.kind){case`mei`:return{kind:PA,focal:new Y(...e.focal),xi:e.xi,...HA(e.distortion),polynomial:new FC};case`radial-polynomial`:return{kind:FA,focal:new Y,xi:0,...HA(BA),polynomial:new FC(...e.coefficients)}}}function HA(e){return{radial:UA(e.radial,oe.radial,()=>0),tangential:UA(e.tangential.map(e=>new Y(e.p1,e.p2)),oe.tangential,()=>new Y),thinPrism:UA(e.thinPrism.map(e=>new Y(e.x,e.y)),oe.thinPrism,()=>new Y)}}function UA(e,t,n){return N(e.length<=t,`a Mei lens has ${e.length} terms of a family the shader holds ${t} of`),Array.from({length:t},(t,r)=>e[r]??n())}function WA(e){return{uLensWindow:{value:e.map(e=>new FC(e.window.x,e.window.y,e.window.width,e.window.height))},uLensRegion:{value:e.map(e=>new FC(e.region.x,e.region.y,e.region.width,e.region.height))},uLensTexture:{value:e.map(e=>e.frameSlot)},uLensGain:{value:e.map(()=>new X(1,1,1))},uSampling:{value:0}}}function GA(e,t){e.uSampling.value=t.shaderSampling}function KA(e,t){e.uStabilization.value=TA(t)}function qA(e,t,n){ae(t,e.uLensCount.value,`lens`),e.uLensGain.value[t]?.set(...n)}var JA={rotation:Mr,planeHalfExtent:1,pictureAspect:1};function YA(e,t,n){let r=XA(t,n);e.uViewRotation.value=TA(r.rotation),e.uPlaneHalfExtent.value=r.planeHalfExtent,e.uPictureAspect.value=r.pictureAspect,e.uScreenArea.value=$A(r.areas,`a picture fills one area per lens at most`).map(e=>ZA(e))}function XA(e,t){switch(e.kind){case`rectilinear`:return{rotation:e.rotation,planeHalfExtent:Hs(e.fieldOfView),pictureAspect:Us(e.area,t),areas:[e.area]};case`equirectangular`:return{...JA,rotation:e.rotation,areas:[e.area]};case`lens-tiles`:return{...JA,areas:e.tiles}}}function ZA(e){return new FC(e.x,e.y,e.width,e.height)}function QA(e){return new Y(e.x,e.y)}function $A(e,t){let n=e.at(-1);return N(n!==void 0&&e.length<=2,t),Array.from({length:2},(t,r)=>e[r]??n)}var ej=`// One triangle covering the whole viewport; the fragment shader does all the work.
|
|
4224
4223
|
in vec3 position;
|
|
4225
4224
|
out vec2 vNdc;
|
|
4226
4225
|
|
|
@@ -4228,9 +4227,9 @@ void main() {
|
|
|
4228
4227
|
vNdc = position.xy;
|
|
4229
4228
|
gl_Position = vec4(position.xy, 0.0, 1.0);
|
|
4230
4229
|
}
|
|
4231
|
-
`,
|
|
4232
|
-
`),uniforms:{...e},depthTest:!1,depthWrite:!1})}function
|
|
4233
|
-
`)}`)}var
|
|
4230
|
+
`,tj=3,nj=[-1,-1,0,tj,-1,0,-1,tj,0],rj=3;function ij(){let e=new _T;return e.setAttribute(`position`,new aT(nj,rj)),e}function aj(e){return{chunks:e,defines:IA}}function oj(e,t){return new fE({glslVersion:YS,defines:{...t.defines},vertexShader:ej,fragmentShader:t.chunks.join(`
|
|
4231
|
+
`),uniforms:{...e},depthTest:!1,depthWrite:!1})}function sj(e,t){let n=e.getContext(`webgl2`,{preserveDrawingBuffer:t.preserveDrawingBuffer??!1,antialias:!1,alpha:!1,depth:!1,stencil:!1});if(!n)throw new j(`render-unavailable`,`this browser has no WebGL2 context`);let r=new CA({canvas:e,context:n});return r.setPixelRatio(1),r.debug.onShaderError=(e,t,...n)=>{cj(e,t,n)},r}function cj(e,t,n){throw new j(`render-unavailable`,`a shader did not compile or link: ${[e.getProgramInfoLog(t),...n.map(t=>e.getShaderInfoLog(t))].filter(Boolean).join(`
|
|
4232
|
+
`)}`)}var lj=255;function uj(e,t,n){let r=[];for(let i=0;i<n;i+=1){let n=dj(e.subarray(i*t*4,(i+1)*t*4));if(!n)return;r.push(n)}return r}function dj(e){let t=[0,0,0],n=0;for(let r=0;r+4<=e.length;r+=4)(e[r+4-1]??0)!==0&&(t[0]+=e[r]??0,t[1]+=e[r+1]??0,t[2]+=e[r+2]??0,n+=1);if(n===0)return;let r=n*lj;return[t[0]/r,t[1]/r,t[2]/r]}function fj(e,t,n){e.compile(t,n);let r=e.info.programs??[];for(let e of r)e.getUniforms()}function pj(e,t,n){let r=e.getRenderTarget();e.setRenderTarget(t);try{n()}finally{e.setRenderTarget(r)}}var mj=`in vec2 vNdc;
|
|
4234
4233
|
out vec4 outColor;
|
|
4235
4234
|
|
|
4236
4235
|
// One row per lens: what that lens sees along the seam ring, the circle of directions halfway
|
|
@@ -4251,7 +4250,7 @@ void main() {
|
|
|
4251
4250
|
LensSample seen = sampleLensWith(lens, dirBody, SAMPLING_BILINEAR);
|
|
4252
4251
|
outColor = seen.isImaged ? vec4(seen.signal, 1.0) : vec4(0.0);
|
|
4253
4252
|
}
|
|
4254
|
-
`,
|
|
4253
|
+
`,hj=`// How lens i's texels are brought to the SDR BT.709 display, as the core's exposureSignalOf and
|
|
4255
4254
|
// shownOf (ADR 0033): the browser's upload has applied the track's matrix and range; the
|
|
4256
4255
|
// transfer and primaries are this chunk's. Shown as recorded, or HLG converted to scene light,
|
|
4257
4256
|
// into BT.709 and toned; gain matching scales the exposure signal between the two (ADR 0012).
|
|
@@ -4326,7 +4325,7 @@ vec3 shownOf(int i, vec3 signal) {
|
|
|
4326
4325
|
vec3 toDisplay(int i, vec3 texel) {
|
|
4327
4326
|
return shownOf(i, exposureSignalOf(i, texel));
|
|
4328
4327
|
}
|
|
4329
|
-
`,
|
|
4328
|
+
`,gj=`// An equirectangular picture: a full turn across and a half turn from top to bottom.
|
|
4330
4329
|
|
|
4331
4330
|
// Direction in view space (x right, y down, z forward) seen through a point of the picture, given
|
|
4332
4331
|
// as fractions of the picture from its top-left corner.
|
|
@@ -4336,7 +4335,7 @@ vec3 rayThroughPicture(vec2 point) {
|
|
|
4336
4335
|
float pitch = -centred.y * HALF_PI;
|
|
4337
4336
|
return vec3(sin(yaw) * cos(pitch), -sin(pitch), cos(yaw) * cos(pitch));
|
|
4338
4337
|
}
|
|
4339
|
-
`,
|
|
4338
|
+
`,_j=`// The fixed join: every lens read where the calibration's template reads it, for an infinitely
|
|
4340
4339
|
// far scene, and blended across the whole feather band. The stitch the player draws; the lab's
|
|
4341
4340
|
// bent join (ADR 0026) implements the same three functions.
|
|
4342
4341
|
float disparityAt(vec3 dirBody) {
|
|
@@ -4350,14 +4349,14 @@ vec3 seamReadDirection(int i, vec3 dirBody, float disparity) {
|
|
|
4350
4349
|
vec2 seamFeather(float disparity) {
|
|
4351
4350
|
return uFeather;
|
|
4352
4351
|
}
|
|
4353
|
-
`,
|
|
4352
|
+
`,vj=`// GLSL ES 3.0 needs the default precisions before any float or int is mentioned.
|
|
4354
4353
|
precision highp float;
|
|
4355
4354
|
precision highp int;
|
|
4356
4355
|
|
|
4357
4356
|
const float PI = 3.14159265358979;
|
|
4358
4357
|
const float HALF_PI = 0.5 * PI;
|
|
4359
4358
|
const float TWO_PI = 2.0 * PI;
|
|
4360
|
-
`,
|
|
4359
|
+
`,yj=`// The depth is positive for every direction inside a lens's field; directions behind it are
|
|
4361
4360
|
// projected too, for the footprint's derivatives, and must not divide by zero.
|
|
4362
4361
|
const float MIN_DEPTH = 1e-3;
|
|
4363
4362
|
|
|
@@ -4425,7 +4424,7 @@ vec2 projectRadialPolynomial(int i, vec3 d, float theta) {
|
|
|
4425
4424
|
vec2 unit = lateral > 0.0 ? d.xy / lateral : vec2(0.0);
|
|
4426
4425
|
return uLensPrincipalPoint[i] + radius * unit;
|
|
4427
4426
|
}
|
|
4428
|
-
`,
|
|
4427
|
+
`,bj=`// How a body direction becomes a texel of one lens, for the stitch and the seam meters: the
|
|
4429
4428
|
// pose and field as uniforms, and the sampling through each lens model, the texel as its
|
|
4430
4429
|
// exposure signal. Needs lensTextures.glsl, displayConversion.glsl and lensModels.glsl.
|
|
4431
4430
|
uniform vec2 uFeather;
|
|
@@ -4482,7 +4481,7 @@ LensSample sampleLensWith(int i, vec3 dirBody, int sampling) {
|
|
|
4482
4481
|
LensSample sampleLensAt(int i, vec3 dirBody) {
|
|
4483
4482
|
return sampleLensWith(i, dirBody, uSampling);
|
|
4484
4483
|
}
|
|
4485
|
-
`,
|
|
4484
|
+
`,xj=`// Where each lens's image is: the decoded frames as textures, each lens's region of its frame,
|
|
4486
4485
|
// and how a screen pixel reads them. Every program that reads a lens needs these.
|
|
4487
4486
|
uniform int uLensCount;
|
|
4488
4487
|
uniform vec4 uLensRegion[MAX_LENSES];
|
|
@@ -4559,7 +4558,7 @@ vec4 sampleLens(int textureIndex, Footprint footprint, int sampling) {
|
|
|
4559
4558
|
if (sampling == SAMPLING_SUPERSAMPLED) return fetchSupersampled(textureIndex, footprint);
|
|
4560
4559
|
return fetchBase(textureIndex, footprint.uv);
|
|
4561
4560
|
}
|
|
4562
|
-
`,
|
|
4561
|
+
`,Sj=`// The decoded lens images on their own, unstitched: each lens's region of its frame as the
|
|
4563
4562
|
// decoder delivered it, brought to the display (ADR 0033), in the lens's screen area, with no
|
|
4564
4563
|
// pose, stabilization or gain. Black around the areas. Every pixel reads every tile, and the area
|
|
4565
4564
|
// picks one without a branch: a read inside a branch that some pixels of a 2x2 quad skip took a
|
|
@@ -4579,7 +4578,7 @@ void main() {
|
|
|
4579
4578
|
}
|
|
4580
4579
|
outColor = vec4(color, 1.0);
|
|
4581
4580
|
}
|
|
4582
|
-
`,
|
|
4581
|
+
`,Cj=`// A rectilinear picture: the image plane scaled so that the horizontal field of view means what
|
|
4583
4582
|
// the picture says.
|
|
4584
4583
|
uniform float uPlaneHalfExtent;
|
|
4585
4584
|
uniform float uPictureAspect;
|
|
@@ -4591,7 +4590,7 @@ vec3 rayThroughPicture(vec2 point) {
|
|
|
4591
4590
|
vec2 plane = vec2(centred.x * uPlaneHalfExtent, centred.y * uPlaneHalfExtent / uPictureAspect);
|
|
4592
4591
|
return normalize(vec3(plane, 1.0));
|
|
4593
4592
|
}
|
|
4594
|
-
`,
|
|
4593
|
+
`,wj=`// Where on the viewport the picture goes: per area, x, y, width and height as fractions of the
|
|
4595
4594
|
// viewport from its top-left corner.
|
|
4596
4595
|
uniform vec4 uScreenArea[MAX_LENSES];
|
|
4597
4596
|
|
|
@@ -4605,7 +4604,7 @@ vec2 pointInArea(vec2 ndc, vec4 area) {
|
|
|
4605
4604
|
bool isInArea(vec2 point) {
|
|
4606
4605
|
return all(greaterThanEqual(point, vec2(0.0))) && all(lessThanEqual(point, vec2(1.0)));
|
|
4607
4606
|
}
|
|
4608
|
-
`,
|
|
4607
|
+
`,Tj=`// The stitched sphere through the picture's rays: each lens's texel for the ray, read and weighted
|
|
4609
4608
|
// across the feather band as the seam join says, and matched in exposure. Every pixel samples,
|
|
4610
4609
|
// even outside the picture's area, so the footprints' derivatives are defined; the area decides
|
|
4611
4610
|
// what shows.
|
|
@@ -4640,7 +4639,7 @@ void main() {
|
|
|
4640
4639
|
bool isShown = isInArea(point) && weightSum > 0.0;
|
|
4641
4640
|
outColor = isShown ? vec4(sum / weightSum, 1.0) : vec4(0.0, 0.0, 0.0, 1.0);
|
|
4642
4641
|
}
|
|
4643
|
-
`,mP=[lP,rP],hP=[...mP,sP,cP];function gP(e){return[oP,...hP,e]}function _P(e){let t=t=>[oP,fP,t,...hP,e,pP];return{rectilinear:t(dP),equirectangular:t(iP),"lens-tiles":[oP,fP,...mP,uP]}}var vP=_P(aP),yP=gP(nP);function bP(e){return[...new Set(e.flat())]}bP([...Object.values(vP),yP]);var xP=64,SP=class{renderer;lensCount;target=new EE(xP,2,{depthBuffer:!1,stencilBuffer:!1});pixels=new Uint8Array(xP*2*4);camera=new Ek;scene=new fD;material;geometry=KN();isDisposed=!1;constructor(e,t,n){this.renderer=e,this.lensCount=n,this.material=JN(t,qN(yP)),this.scene.add(new AO(this.geometry,this.material));try{eP(e,this.scene,this.camera)}catch(e){throw this.dispose(),e}}async measure(){try{await this.readSeam()}catch(e){if(this.isDisposed||this.renderer.getContext().isContextLost())return;throw e}return this.isDisposed?void 0:QN(this.pixels,xP,this.lensCount)}dispose(){this.isDisposed||(this.isDisposed=!0,this.target.dispose(),this.material.dispose(),this.geometry.dispose())}draw(){tP(this.renderer,this.target,()=>{this.renderer.render(this.scene,this.camera)})}async readSeam(){this.draw(),await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,xP,2,this.pixels)}};function CP(e,t){return Array.from({length:e},()=>{let e=new zO;return e.flipY=!1,e.colorSpace=``,e.magFilter=hw,wP(e,t),e})}function wP(e,t){e.minFilter=t.minFilter,e.generateMipmaps=t.generateMipmaps,e.anisotropy=t.anisotropy}var TP={programs:vP,defines:wN};function EP(e,t){let n=n=>JN(e,{chunks:t.programs[n],defines:t.defines});return{rectilinear:n(`rectilinear`),equirectangular:n(`equirectangular`),"lens-tiles":n(`lens-tiles`)}}function DP(e,t,n){let r=new Ek;for(let i of Object.values(n)){let n=new fD;n.add(new AO(t,i)),eP(e,n,r)}}function OP(e){for(let t of Object.values(e))t.dispose()}var kP={shaders:TP,uniforms:{}},AP=class{parts;canvas;framing=uc;viewMode=ks;hasFrames=!1;isDisposed=!1;meters=/* @__PURE__ */ new Set;constructor(e,t){this.parts=e,this.canvas=t,this.applyFraming(),t.addEventListener(`webglcontextrestored`,this.onContextRestored)}static create(e,t,n={}){let r={options:n,pictures:kP};return new this(this.openParts(e,t,r),e)}static openParts(e,t,n){jP(t);let r=YN(e,n.options);try{return NP(r,t,n.pictures)}catch(e){throw r.dispose(),e}}get lensCount(){return this.parts.lensCount}setFraming(e){this.ensureLive(),this.framing=e,this.applyFraming(),this.render()}setViewMode(e){this.ensureLive(),this.viewMode=e,this.applyFraming(),this.render()}setQuality(e){this.ensureLive();let t=xN[e];for(let e of this.parts.textures)wP(e,t),this.hasFrames&&(e.needsUpdate=!0);NN(this.parts.uniforms,t),this.render()}setLensGains(e){this.ensureLive();for(let[t,n]of e.entries())FN(this.parts.uniforms,t,n);this.render()}createSeamMeter(){this.ensureLive();let e=new SP(this.parts.renderer,this.parts.uniforms,this.parts.lensCount);return this.tracked({measure:()=>e.measure(),dispose:()=>{e.dispose()}})}setStabilization(e){this.ensureLive(),PN(this.parts.uniforms,e)}present(e){this.ensureLive();let{frames:t}=e.pair;j(t.length===this.parts.textures.length,`a pair of ${t.length} frames does not fit ${this.parts.textures.length} lens textures`);for(let[e,n]of this.parts.textures.entries()){let r=t[e];r&&n.setFrame(r.handle)}this.parts.matrixCorrections.follow(t.map(e=>e.handle)),this.hasFrames=!0,this.render()}resize(e){this.ensureLive(),this.parts.renderer.setSize(e.width,e.height,!1),this.applyFraming(),this.render()}dispose(){if(!this.isDisposed){this.isDisposed=!0,this.canvas.removeEventListener(`webglcontextrestored`,this.onContextRestored);for(let e of this.meters)e.dispose();this.parts.seamProof.dispose();for(let e of this.parts.textures)e.dispose();OP(this.parts.materials),this.parts.pass.geometry.dispose(),this.parts.renderer.dispose()}}get webgl(){return this.parts.renderer}get uniforms(){return this.parts.uniforms}tracked(e){let t={...e,dispose:()=>{this.meters.delete(t),e.dispose()}};return this.meters.add(t),t}render(){this.hasFrames&&this.parts.renderer.render(this.parts.scene,this.parts.camera)}ensureLive(){j(!this.isDisposed,`the renderer has been disposed`)}onContextRestored=()=>{this.render()};applyFraming(){let e={width:this.canvas.width,height:this.canvas.height},t=kc(this.viewMode).picture(this.framing,{viewport:e,lensCount:this.parts.lensCount});this.parts.pass.material=this.parts.materials[t.kind],LN(this.parts.uniforms,t,Ps(e))}};function jP(e){if(!(e.lenses.length<=2&&e.frameSlotCount<=2))throw new A(`unsupported-layout`,`the renderer draws at most 2 lenses from 2 frames; the layout has ${e.lenses.length} lenses in ${e.frameSlotCount} frames`)}function MP(e,t){let n=xN[Ts],r=CP(e.frameSlotCount,n),i=TN(e,r);return NN(i,n),{textures:r,uniforms:i,materials:EP({...i,...t.uniforms},t.shaders)}}function NP(e,t,n){let{textures:r,uniforms:i,materials:a}=MP(t,n),o=new AO(KN(),a.rectilinear),s=PP(e,{pass:o,materials:a,textures:r,uniforms:i}),c=new fD;return c.add(o),{renderer:e,scene:c,camera:new Ek,pass:o,materials:a,textures:r,uniforms:i,matrixCorrections:new mN(t.lenses,i.uLensMatrixCorrection),lensCount:t.lenses.length,seamProof:s}}function PP(e,t){let{pass:n,materials:r,textures:i,uniforms:a}=t;try{return DP(e,n.geometry,r),new SP(e,a,a.uLensCount.value)}catch(e){OP(r),n.geometry.dispose();for(let e of i)e.dispose();throw e}}var FP=class{actions=[];isDisposed=!1;add(e){if(this.isDisposed){e();return}this.actions.push(e)}disposeAll(){if(!this.isDisposed){this.isDisposed=!0;for(let e of this.actions.splice(0).toReversed())e()}}toDisposer(){return()=>{this.disposeAll()}}},IP={maxPendingPackets:4,pairTolerance:F(5e-4)},LP=`the recording has no audio track; playback follows a silent clock`,RP=`this browser cannot play the audio track through Media Source Extensions; playback follows a silent clock`,zP=`the audio track could not be prepared for playback; playback follows a silent clock`;async function BP(e){let t=new FP;try{let n=await UP(e);t.add(()=>{n.clock.dispose()}),e.signal.throwIfAborted();let r=VP(e,t),i=JP(e,n.clock,r.gainMatching);return t.add(()=>{i.dispose()}),qP(i,e.opened),{session:i,renderer:r.renderer,...HP(r,i),soundWarnings:n.warnings,dispose:t.toDisposer()}}catch(e){throw t.disposeAll(),e}}function VP(e,t){let n=AP.create(e.host.canvas,GP(e.opened));t.add(()=>{n.dispose()});let{sink:r,stabilizing:i}=KP(n,e.opened),a=new Gc(r,n);return t.add(()=>{a.dispose()}),{renderer:n,stabilizing:i,gainMatching:a}}function HP(e,t){return{setStabilization:n=>{e.stabilizing?.setStabilizer(is(n)),t.redraw()},setQuality:t=>{e.renderer.setQuality(t)},setGainMatching:n=>{n?e.gainMatching.enable():e.gainMatching.disable(),t.redraw()}}}async function UP(e){let{soundSegments:t}=e.opened;if(!t)return WP(LP);try{let n=t();return aw.isSupported(n)?(e.signal.throwIfAborted(),{clock:await aw.open(e.host.audio,n),warnings:[]}):WP(RP)}catch(e){return WP(`${zP} (${oe(e)})`)}}function WP(e){return{clock:new Zu(()=>mt(performance.now())),warnings:[e]}}function GP(e){return Fc({calibration:e.calibration,layout:e.layout,displayConversions:e.displayConversions})}function KP(e,t){if(!t.motion)return{sink:e,stabilizing:void 0};let n=new Bc({sink:e,orientations:t.motion.orientations,frameTimes:t.frameTimes});return{sink:n,stabilizing:n}}function qP(e,t){e.events.on(`statechange`,e=>{ed(e)&&t.readAhead()})}function JP(e,t,n){return new _d({frameSources:e.opened.frameSources,decoderPort:e.decoderPort,clock:t,sink:n,duration:e.opened.duration,buffer:e.opened.buffer,pipeline:IP,queueCapacity:4})}function YP(e,t,n=Ts){let r=br(t,1,Ds(n));return{width:Math.max(1,Math.round(e.width*r)),height:Math.max(1,Math.round(e.height*r))}}function XP(e){let{width:t,height:n}=e.getBoundingClientRect();return{width:t,height:n}}var ZP=class{canvas;renderer;observer;ratioWatch=new AbortController;quality=Ts;constructor(e,t){this.canvas=e,this.renderer=t,this.observer=new ResizeObserver(()=>{this.fit()}),this.observer.observe(e),this.watchPixelRatio(),this.fit()}setQuality(e){this.quality=e,this.fit()}dispose(){this.observer.disconnect(),this.ratioWatch.abort()}watchPixelRatio(){globalThis.matchMedia(`(resolution: ${globalThis.devicePixelRatio}dppx)`).addEventListener(`change`,()=>{this.fit(),this.watchPixelRatio()},{once:!0,signal:this.ratioWatch.signal})}fit(){let e=YP(XP(this.canvas),globalThis.devicePixelRatio,this.quality);(e.width!==this.canvas.width||e.height!==this.canvas.height)&&this.renderer.resize(e)}},QP={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}},$P=class{tick;scheduler;isActive=!1;handle;constructor(e,t=QP){this.tick=e,this.scheduler=t}start(){this.isActive||(this.isActive=!0,this.schedule())}stop(){this.isActive=!1,this.handle!==void 0&&(this.scheduler.cancel(this.handle),this.handle=void 0)}schedule(){this.handle=this.scheduler.request(()=>{this.handle=void 0,this.tick(),this.isActive&&this.schedule()})}};async function eF(e,t){let{ports:n,signal:r}=t,i=await Wu(e,n.decoderPort,aF(t));if(r.throwIfAborted(),!i.canDecode)throw rF(i)}var tF={"no-key-frame":{code:`no-key-frame`,message:`the recording has no key frame to start decoding from`},"key-frame-late":{code:`source-unreadable`,message:`the recording's first frames did not arrive in time`}},nF={code:`codec-unsupported`,message:`this browser cannot decode the recording`};function rF(e){let t=iF(e),{code:n,message:r}=(t===void 0?void 0:tF[t])??nF;return new A(n,`${r}: ${oF(e)}`)}function iF(e){let t=new Set(e.sources.filter(e=>e.verdict!==`decodes`).map(e=>e.verdict));t.has(`key-frame-late`)&&t.delete(`timed-out`);let[n]=t;return t.size===1?n:void 0}function aF(e){let t=e.ports.probeDeadline();return e.signal.addEventListener(`abort`,()=>{t.resolve()},{once:!0}),t}function oF(e){return e.sources.filter(e=>e.verdict!==`decodes`).map(e=>`track ${e.track.trackIndex} ${e.verdict}${e.detail?` (${e.detail})`:``}`).join(`; `)}async function sF(e,t){let{ports:n,signal:r}=t,i=e.map(e=>({input:e,opened:n.sources.open(e,r)})),a=await fF(i,n);r.throwIfAborted();let o=[...i,...await uF(i,a,t)],s=await Promise.all(o.map(e=>lF(e,n)));return r.throwIfAborted(),{recording:a,inputs:s}}function cF(e){let t=e.codecs.video.map(({description:e})=>({description:e}));return{name:PC(e.input),videoTracks:t}}async function lF(e,t){let{source:n}=e.opened,{table:r,movieBytes:i}=await Do(n),a=await t.codecReader.read(i);return{...e,table:r,codecs:a,size:await n.size()}}async function uF(e,t,n){if(e.length!==1||t.info.fileLayout!==`split-files`||!n.findSecondFile)return[];let r=await n.findSecondFile();return n.signal.throwIfAborted(),r===void 0?[]:[{input:r,opened:n.ports.sources.open(r,n.signal)}]}var dF={fileLayout:void 0,trackOrder:void 0};async function fF(e,t){try{return await mF(e.map(({opened:e})=>e.source))}catch(n){let[r]=e;throw e.length===1&&ae(n,`invalid-trailer`)&&r&&await pF(r,t),n}}async function pF(e,t){let n;try{n=await lF(e,t)}catch{return}try{Ro([cF(n)],dF)}catch(e){if(ae(e,`missing-second-file`))throw e}}async function mF(e){let[t,n]=e;j(t!==void 0,`a recording needs at least one input`);try{return await er(t)}catch(e){if(n===void 0||!ae(e,`invalid-trailer`))throw e;return er(n)}}async function hF(e,t){let n=new FP;try{let r=await sF(e,t),i=Ro(r.inputs.map(e=>cF(e)),r.recording.info),a=vF(r.recording),o=gF(r.inputs,n),s=Pc(i).map(e=>_F(o,e));await eF(s,t);let c=await Gi(r.recording,s[0]);return t.signal.throwIfAborted(),yF({read:r,files:o,layout:i,frameSources:s,calibration:a,timing:c},t.ports.audioPackager,n)}catch(e){throw n.disposeAll(),e}}function gF(e,t){return e.map(({opened:n,table:r,codecs:i,size:a})=>{let o=bu({size:a,duration:r.duration},e.length),s=cu({table:r,stream:n.stream,codecs:i,policy:o});return t.add(()=>{s.dispose()}),s})}function _F(e,t){let n=e[t.inputIndex]?.videoTracks[t.trackIndex];return j(n!==void 0,`the layout points at track ${t.trackIndex} of input ${t.inputIndex}, which does not exist`),n}function vF(e){let{calibration:t,warnings:n}=e.calibration;if(t)return t;throw new A(`no-calibration`,`the recording carries no usable lens calibration, so it cannot be stitched${n.length>0?` (${n.join(`; `)})`:``}`)}function yF(e,t,n){let{read:r,files:i,layout:a,frameSources:o,calibration:s,timing:c}=e,l=F(Math.min(...i.map(e=>e.duration))),u=fl(o.map(e=>e.description.colour)),[d]=i.flatMap(e=>e.audioTracks);return{recording:r.recording,layout:a,frameSources:o,calibration:s,displayConversions:u.conversions,duration:l,frameTimes:c.frameTimes,motion:c.motion,soundSegments:d&&(()=>t.segmentsOf(d.samples,d.configuration)),metadata:bF(e,l,d!==void 0),warnings:[...c.warnings,...u.warnings],readAhead:()=>{for(let e of i)e.download.startReadingAhead()},buffer:new xu(i.map(e=>e.download)),dispose:n.toDisposer()}}function bF(e,t,n){let{info:r}=e.read.recording,{motion:i}=e.timing;return{model:r.model,firmware:r.firmware,captureMode:r.captureMode,layout:e.layout.kind,layoutEvidence:e.layout.evidence,tracks:e.frameSources.map(e=>e.description),calibrationVersion:e.calibration.version,frameTimeSource:e.timing.frameTimeSource,hasGyro:i!==void 0,imuFrame:i&&{name:i.imuFrame.name,isVerified:i.imuFrame.isVerified},hasAudio:n,duration:t}}async function xF(e,t,n){let r=SF(e,t,n),i=e.second?[e.main,e.second]:[e.main];try{return await hF(i,r)}catch(t){let{findSecondFile:i}=r;if(!i||!ae(t,`missing-second-file`))throw t;let a=await i();if(n.throwIfAborted(),!a)throw t;return hF([e.main,a],r)}}function SF(e,t,n){let{main:r}=e;return e.second===void 0&&NC(r)?{ports:t,signal:n,findSecondFile:et(()=>CF(r,t))}:{ports:t,signal:n}}async function CF(e,t){let n=await aa(e.url,t.locatorFor(e));return n===void 0?void 0:{...e,url:n}}async function wF(e){let{parts:t,signal:n}=e,r=await xF(e.source,t.ports,n),i=new FP;i.add(()=>{r.dispose()});try{let e=await t.pipelines({opened:r,host:t.host,decoderPort:t.ports.decoderPort,signal:n});i.add(()=>{e.dispose()}),n.throwIfAborted();let a=new ZP(t.host.canvas,e.renderer);i.add(()=>{a.dispose()});let o=TF(e,a);return{opened:r,pipeline:o,warnings:EF(r,o),dispose:i.toDisposer()}}catch(e){throw i.disposeAll(),e}}function TF(e,t){return{...e,setQuality:n=>{e.setQuality(n),t.setQuality(n)}}}function EF(e,t){return[...e.warnings.map(e=>({code:`recording-degraded`,message:e})),...t.soundWarnings.map(e=>({code:`no-sound`,message:e}))]}var DF={kind:`idle`};function OF(){return{kind:`loading`,controller:new AbortController,settled:new Du}}function kF(e){switch(e.kind){case`idle`:return`idle`;case`loading`:return`loading`;case`loaded`:return e.loaded.pipeline.session.state;case`failed`:return`error`}}var AF=class{events;mode=Zo;isMatching=!0;qualityValue=Ts;target;constructor(e){this.events=e}get stabilization(){return this.mode}get quality(){return this.qualityValue}attach(e){this.target=e,e?.setStabilization(this.mode),e?.setGainMatching(this.isMatching),e?.setQuality(this.qualityValue)}setStabilization(e){e!==this.mode&&(this.mode=e,this.target?.setStabilization(e),this.events.emit(`stabilizationchange`,e))}setGainMatching(e){this.isMatching=e,this.target?.setGainMatching(e)}setQuality(e){e!==this.qualityValue&&(this.qualityValue=e,this.target?.setQuality(e),this.events.emit(`qualitychange`,e))}},jF=class{audio;events;canSetVolume;constructor(e,t){this.audio=e,this.events=t,this.canSetVolume=NF(e.ownerDocument),e.addEventListener(`volumechange`,this.onVolumeChange)}get volume(){return this.audio.volume}get isMuted(){return this.audio.muted}setVolume(e){this.audio.volume=br(e,0,1)}setMuted(e){this.audio.muted=e}dispose(){this.audio.removeEventListener(`volumechange`,this.onVolumeChange)}onVolumeChange=()=>{this.events.emit(`volumechange`,{volume:this.volume,isMuted:this.isMuted})}},MF=.5;function NF(e){let t=e.createElement(`audio`);return t.volume=MF,t.volume===MF}var PF=2,FF=class{events;measureViewport;framing=uc;mode=ks;surface;lensCount=PF;constructor(e,t){this.events=e,this.measureViewport=t}get current(){return this.framing.view}get viewMode(){return this.mode}get canPan(){return this.rules().canPan(this.framing)}attach(e){this.surface=e,e&&(this.lensCount=e.lensCount),e?.setViewMode(this.mode),e?.setFraming(this.framing)}set(e){this.frame({...this.framing,view:xs(e)})}setMode(e){e!==this.mode&&(this.mode=e,this.surface?.setViewMode(e),this.events.emit(`viewmodechange`,e))}lookAt(e,t){this.frame({...this.framing,view:ec(this.framing.view,e,t)})}pan(e){this.frame(this.rules().pan(this.framing,e,this.context()))}turn(e,t){this.frame(this.rules().turn(this.framing,{yaw:e,pitch:t},this.context()))}zoom(e,t=Ms){this.frame(this.rules().zoom(this.framing,{steps:e,focus:t},this.context()))}reset(){this.frame(this.rules().reset(this.framing))}frame(e){if(dc(e,this.framing))return;let t=!Ss(e.view,this.framing.view);this.framing=e,this.surface?.setFraming(e),t&&this.events.emit(`viewchange`,e.view)}context(){return{viewport:this.measureViewport(),lensCount:this.lensCount}}rules(){return kc(this.mode)}},IF=/* @__PURE__ */ new Set([`ready`,`paused`,`ended`]),LF=/* @__PURE__ */ new Map([[`playing`,`playing`],[`buffering`,`waiting`]]);function RF(e,t){return t===`seeking`?[`seeking`]:e===`seeking`?t===`buffering`?[`seeked`,`waiting`]:[`seeked`]:t===`paused`?e===`ready`?[]:[`pause`]:zF(e,t)}function zF(e,t){let n=LF.get(t);return n===void 0?[]:e===void 0||IF.has(e)?[`play`,n]:[n]}var BF=class{targets;stopListening=[];lastState;detachments=0;constructor(e){this.targets=e}attach(e){this.detach(),this.lastState=e.state;let{events:t}=this.targets;this.stopListening=[e.events.on(`statechange`,t=>{this.onStateChange(t,e)}),e.events.on(`timeupdate`,e=>{t.emit(`timeupdate`,e)}),e.events.on(`present`,e=>{t.emit(`frame`,e)}),e.events.on(`ended`,()=>{this.targets.onEnded()}),e.events.on(`error`,e=>{t.emit(`error`,e)})]}detach(){for(let e of this.stopListening)e();this.stopListening=[],this.lastState=void 0,this.detachments+=1}onStateChange(e,t){let n=this.lastState;this.lastState=e;let r=this.detachments;for(let i of RF(n,e))if(this.emitTransport(i,t),this.detachments!==r)return;this.targets.onState(e)}emitTransport(e,t){let{events:n}=this.targets;e===`seeking`||e===`seeked`?n.emit(e,t.currentTime):n.emit(e,void 0)}},VF=class{parts;events=new nd;outbox=new vl(this.events);loop;phase=DF;viewing;picture=new AF(this.outbox);pendingStartTime;sound;relay=new BF({events:this.outbox,onState:()=>{this.announceStatus()},onEnded:()=>{this.onEnded()}});isLoopingValue=!1;isDisposed=!1;lastStatus=`idle`;constructor(e){this.parts=e,this.loop=new $P(this.tick),e.host.audio.addEventListener(`ended`,this.tick),this.sound=new jF(e.host.audio,this.outbox);let{canvas:t}=e.host;this.viewing=new FF(this.outbox,()=>XP(t))}get status(){return kF(this.phase)}get metadata(){return this.loaded?.opened.metadata}get currentTime(){return this.loaded?.pipeline.session.currentTime??F(0)}get duration(){return this.loaded?.opened.duration??F(0)}get isPaused(){return!ed(this.loaded?.pipeline.session.state)}get view(){return this.viewing.current}get viewMode(){return this.viewing.viewMode}get canPan(){return this.viewing.canPan}get stabilization(){return this.picture.stabilization}get quality(){return this.picture.quality}get isLooping(){return this.isLoopingValue}get volume(){return this.sound.volume}get isMuted(){return this.sound.isMuted}get canSetVolume(){return this.sound.canSetVolume}async load(e,t={}){if(this.isDisposed)return;let n=this.outbox.change(()=>{this.unload();let e=OF();return this.phase=e,this.announceStatus(),e});try{await this.complete(n,e,t)}catch(e){if(n.controller.signal.aborted)return;throw this.failWith(e)}finally{n.settled.resolve()}}unload(){this.outbox.change(()=>{this.release(),this.announceStatus()})}async play(){if(await this.loadInProgress(),this.phase.kind===`failed`)throw this.phase.failure;await this.loaded?.pipeline.session.play()}pause(){this.loaded?.pipeline.session.pause()}stop(){this.loaded?.pipeline.session.stop()}seek(e){Ad(e,`time`);let t=this.loaded?.pipeline.session;t&&t.state!==`error`?t.seek(F(e)):this.pendingStartTime=F(e)}async scrub(e){Ad(e,`time`),await this.loaded?.pipeline.session.scrub(F(e))}setView(e){this.viewing.set(jd(e))}lookAt(e,n){Ad(e,`yaw`),Ad(n,`pitch`),this.viewing.lookAt(t(e),t(n))}pan(e){this.viewing.pan(e)}turn(e,n){Ad(e,`yaw turn`),Ad(n,`pitch turn`),this.viewing.turn(t(e),t(n))}zoom(e,t){Ad(e,`zoom steps`),this.viewing.zoom(e,t)}resetView(){this.viewing.reset()}setViewMode(e){this.viewing.setMode(e)}setStabilization(e){this.picture.setStabilization(e)}setQuality(e){this.picture.setQuality(e)}setLooping(e){this.isLoopingValue=e}setGainMatching(e){this.picture.setGainMatching(e)}setVolume(e){Ad(e,`volume`),this.sound.setVolume(e)}setMuted(e){this.sound.setMuted(e)}dispose(){this.isDisposed=!0,this.unload(),this.parts.host.audio.removeEventListener(`ended`,this.tick),this.sound.dispose(),this.events.removeAll()}tick=()=>{this.loaded?.pipeline.session.tick()};async loadInProgress(){this.phase.kind===`loading`&&await this.phase.settled.promise}get loaded(){return this.phase.kind===`loaded`?this.phase.loaded:void 0}async complete(e,t,n){let{signal:r}=e.controller,i=await wF({source:t,parts:this.parts,signal:r});if(r.aborted){i.dispose();return}this.outbox.change(()=>{this.attach(i,e.controller),this.startAtPendingTime(i),n.preload!==!1&&i.pipeline.session.preload()}),n.autoplay&&this.loaded===i&&await this.autoplay()}startAtPendingTime(e){let t=this.pendingStartTime;this.pendingStartTime=void 0,t!==void 0&&e.pipeline.session.seek(t)}attach(e,t){this.phase={kind:`loaded`,loaded:e,controller:t},this.viewing.attach(e.pipeline.renderer);let{session:n}=e.pipeline;this.picture.attach(e.pipeline),this.relay.attach(n),this.loop.start(),this.announceStatus();for(let t of e.warnings)this.outbox.emit(`warning`,t);this.outbox.emit(`ready`,e.opened.metadata)}async autoplay(){try{await this.play()}catch(e){this.outbox.emit(`warning`,ae(e,`playback-blocked`)?{code:`autoplay-blocked`,message:`playback waits for a user gesture`}:{code:`playback-failed`,message:`autoplay failed: ${oe(e)}`})}}onEnded(){this.outbox.emit(`ended`,void 0),this.isLoopingValue&&this.replay()}async replay(){try{await this.play()}catch(e){this.outbox.emit(`warning`,{code:`playback-failed`,message:`the loop could not restart playback: ${oe(e)}`})}}release(){let e=this.phase;this.phase=DF,e.kind===`loading`&&e.controller.abort(),this.loop.stop(),this.relay.detach(),this.viewing.attach(void 0),this.picture.attach(void 0),e.kind===`loaded`&&(e.loaded.dispose(),e.controller.abort())}failWith(e){let t=re(e,`invariant-violation`,`the player failed unexpectedly`);return this.outbox.change(()=>{this.release(),this.phase={kind:`failed`,failure:t},this.announceStatus(),this.outbox.emit(`error`,t)}),t}announceStatus(){let{status:e}=this;this.outbox.post(()=>{e!==this.lastStatus&&(this.lastStatus=e,this.events.emit(`statuschange`,e))})}};function HF(e,t){return new VF({host:e,ports:IC(t),pipelines:BP})}function UF(e,t={}){let n=t.signal??new AbortController().signal,{source:r}=LC(t.http??{}).open(WF(e),n);return fr(r)}function WF(e){return typeof e==`string`?{url:e}:{blob:e,name:e instanceof File?e.name:``}}var GF={Src:`src`,Src2:`src2`},KF={CrossOrigin:`crossorigin`},qF={FieldOfView:`fov`,Yaw:`yaw`,Pitch:`pitch`},JF={Autoplay:`autoplay`,Preload:`preload`,GainMatch:`gain-match`,Muted:`muted`,Loop:`loop`,Stabilization:`stabilization`,ViewMode:`view-mode`,Quality:`quality`,Controls:`controls`,Poster:`poster`},YF=[...Object.values(GF),...Object.values(KF),...Object.values(qF),...Object.values(JF)];function XF(e,t){let n=QF(e(KF.CrossOrigin)),r=ZF(e(GF.Src),t,n);return r&&{main:r,second:ZF(e(GF.Src2),t,n)}}function ZF(e,t,n){let r=e?.trim()??``;return r===``?void 0:{url:$F(r,t),...n}}function QF(e){return Ed(cI,e)===`use-credentials`?{credentials:`include`}:{}}function $F(e,t){try{return new URL(e,t).href}catch{return e}}var eI={[qF.FieldOfView]:`fieldOfView`,[qF.Yaw]:`yaw`,[qF.Pitch]:`pitch`};function tI(e,t,n){let r=eI[t],i=rI(n);return r===void 0||i===void 0?e:{...e,[r]:i}}function nI(e){return e!==null}function rI(e){if(e===null||e.trim()===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function iI(e,t,n){return{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected one of ${n.join(`, `)}`}}function aI(e,t){return t===null||rI(t)!==void 0?void 0:{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected a number of degrees`}}var oI={name:JF.Preload,keywords:[`none`,`auto`],fallback:`auto`},sI={name:JF.GainMatch,keywords:[`on`,`off`],fallback:`on`},cI={name:KF.CrossOrigin,property:`crossOrigin`,keywords:[`anonymous`,`use-credentials`],fallback:`anonymous`};function lI(e){return Ed(oI,e)===`auto`}function uI(e){return Ed(sI,e)===`on`}function dI(e,t,n){return n?fI(n):XF(e,t)}function fI(e){return{main:{blob:e.main,name:e.main.name},second:e.second&&{blob:e.second,name:e.second.name}}}var pI=class{element;player;scheduled;isOwed=!0;awaited;startTime;files;constructor(e,t){this.element=e,this.player=t}connected(){this.isOwed&&this.schedule(),this.awaited?.follow(this.scheduled??Promise.resolve()),this.awaited=void 0}async disconnected(){await Promise.resolve(),!this.element.isConnected&&(this.player.unload(),this.isOwed=!0)}sourceChanged(){this.files=void 0,this.schedule()}requestChanged(){this.files===void 0&&this.schedule()}loadFiles(e){this.files=e,this.schedule()}load(){return this.element.isConnected?this.scheduled??this.reload():this.loadOnConnection()}seek(e){this.scheduled?this.startTime=e:this.player.seek(e)}async settled(){try{await this.scheduled}catch{}}loadOnConnection(){return this.isOwed=!0,this.awaited??=new Du,this.awaited.promise}schedule(){if(this.isOwed=!this.element.isConnected,this.scheduled||!this.element.isConnected)return;let e=this.loadAfterPendingChanges();this.scheduled=e,e.catch(mI)}async loadAfterPendingChanges(){await Promise.resolve(),this.scheduled=void 0,this.element.isConnected&&await this.reload()}reload(){this.isOwed=!1;let e=e=>this.element.getAttribute(e),t=dI(e,document.baseURI,this.files);delete this.element.dataset.hasFrame;let n=this.startTime;if(this.startTime=void 0,!t)return this.player.unload(),Promise.resolve();let r=this.player.load(t,{autoplay:this.element.autoplay,preload:lI(e(JF.Preload))});return n!==void 0&&this.player.seek(n),r}};function mI(){}var hI=`data-fill`,gI=class{element;constructor(e){this.element=e}get isActive(){return this.isNativelyFullscreen()||this.element.hasAttribute(hI)}async toggle(){await(this.isActive?this.exit():this.enter())}async exit(){this.isNativelyFullscreen()&&await document.exitFullscreen(),this.element.removeAttribute(hI)}isNativelyFullscreen(){return this.element.matches(`:fullscreen`)}async enter(){if(document.fullscreenEnabled)try{await this.element.requestFullscreen();return}catch{}this.element.setAttribute(hI,``)}},_I=`data-idle`,vI=2500,yI=[`pointermove`,`pointerdown`,`keydown`,`focusin`],bI={capture:!0},xI=class{element;shouldHide;timer;wasIdleAtPress=!1;constructor(e,t){this.element=e,this.shouldHide=t}get wasIdleAtLastPress(){return this.wasIdleAtPress}start(){this.element.addEventListener(`pointerdown`,this.onPress,bI);for(let e of yI)this.element.addEventListener(e,this.onActivity,bI);this.onActivity()}stop(){for(let e of yI)this.element.removeEventListener(e,this.onActivity,bI);this.element.removeEventListener(`pointerdown`,this.onPress,bI),this.clearTimer(),this.element.removeAttribute(_I)}refresh(){this.shouldHide()||this.element.removeAttribute(_I),this.restart()}onPress=()=>{this.wasIdleAtPress=this.element.hasAttribute(_I)};onActivity=()=>{this.element.removeAttribute(_I),this.restart()};restart(){this.clearTimer(),this.timer=setTimeout(()=>{this.shouldHide()&&this.element.setAttribute(_I,``)},vI)}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}};function SI(e,t,n){return({player:r,warn:i},a)=>{let o=vd(a,t);o?n(r,o):a!==null&&i(iI(e,a,t))}}var CI={[JF.Stabilization]:SI(JF.Stabilization,Xo,(e,t)=>{e.setStabilization(t)}),[JF.ViewMode]:SI(JF.ViewMode,Os,(e,t)=>{e.setViewMode(t)}),[JF.Quality]:SI(JF.Quality,ws,(e,t)=>{e.setQuality(t)}),[JF.Muted]:({player:e},t)=>{e.setMuted(nI(t))},[JF.Loop]:({player:e},t)=>{e.setLooping(nI(t))},[JF.Poster]:({posterImage:e},t)=>{e.src=t??``},[JF.GainMatch]:({player:e},t)=>{e.setGainMatching(uI(t))}};function wI(e){return Object.hasOwn(CI,e)}function TI(e,t,n){wI(t)&&CI[t](e,n)}function EI(e,t){e.hasAttribute(`tabindex`)||(e.tabIndex=0),e.hasAttribute(`role`)||e.setAttribute(`role`,`region`),e.hasAttribute(`aria-label`)||e.hasAttribute(`aria-labelledby`)||e.setAttribute(`aria-label`,t)}function DI(e,t,n){e.getAttribute(`aria-label`)===t&&e.setAttribute(`aria-label`,n)}function OI(e,t){let n=/* @__PURE__ */ new Map;for(let r of t)Object.hasOwn(e,r)&&(n.set(r,Reflect.get(e,r)),Reflect.deleteProperty(e,r));return n}function kI(e,t,n){let r=[...t];t.clear();for(let[t,i]of r)try{Reflect.set(e,t,i)}catch(e){n({code:`refused-property`,message:`${t} set before the element was defined was refused: ${oe(e)}`})}}var AI=_l({stabilization:!0,viewMode:!0,quality:!0,fov:!0,yaw:!0,pitch:!0,muted:!0,loop:!0,volume:!0});function jI(e,t){let n={stabilization:{get:()=>t.stabilization,set:LI(e=>{t.setStabilization(PI(e))})},viewMode:{get:()=>t.viewMode,set:LI(e=>{t.setViewMode(FI(e))})},quality:{get:()=>t.quality,set:LI(e=>{t.setQuality(II(e))})},...MI(t),...NI(t)};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{configurable:!0,enumerable:!0,...r})}function MI(e){let t=(t,n)=>({get:()=>e.view[t],set:LI(r=>{e.setView({...e.view,[t]:zI(r,n)})})});return{fov:t(`fieldOfView`,`fov`),yaw:t(`yaw`,`yaw`),pitch:t(`pitch`,`pitch`)}}function NI(e){return{muted:{get:()=>e.isMuted,set:t=>{e.setMuted(!!t)}},loop:{get:()=>e.isLooping,set:t=>{e.setLooping(!!t)}},volume:{get:()=>e.volume,set:LI(t=>{e.setVolume(BI(t,`volume`))})}}}function PI(e){return RI(e,yd,`stabilization`)}function FI(e){return RI(e,bd,`viewMode`)}function II(e){return RI(e,xd,`quality`)}function LI(e){return t=>{t!=null&&t!==``&&e(t)}}function RI(e,t,n){let r=typeof e==`string`?t(e):void 0;if(r===void 0)throw new A(`invalid-argument`,`${n} cannot be ${String(e)}`);return r}function zI(e,n){return t(BI(e,n))}function BI(e,t){return Ad(e,t),e}var VI=`/*
|
|
4642
|
+
`,Ej=[xj,hj],Dj=[...Ej,yj,bj];function Oj(e){return[vj,...Dj,e]}function kj(e){let t=t=>[vj,wj,t,...Dj,e,Tj];return{rectilinear:t(Cj),equirectangular:t(gj),"lens-tiles":[vj,wj,...Ej,Sj]}}var Aj=kj(_j),jj=Oj(mj);function Mj(e){return[...new Set(e.flat())]}Mj([...Object.values(Aj),jj]);var Nj=64,Pj=class{renderer;lensCount;target=new LC(Nj,2,{depthBuffer:!1,stencilBuffer:!1});pixels=new Uint8Array(Nj*2*4);camera=new LE;scene=new Cw;material;geometry=ij();isDisposed=!1;constructor(e,t,n){this.renderer=e,this.lensCount=n,this.material=oj(t,aj(jj)),this.scene.add(new VT(this.geometry,this.material));try{fj(e,this.scene,this.camera)}catch(e){throw this.dispose(),e}}async measure(){try{await this.readSeam()}catch(e){if(this.isDisposed||this.renderer.getContext().isContextLost())return;throw e}return this.isDisposed?void 0:uj(this.pixels,Nj,this.lensCount)}dispose(){this.isDisposed||(this.isDisposed=!0,this.target.dispose(),this.material.dispose(),this.geometry.dispose())}draw(){pj(this.renderer,this.target,()=>{this.renderer.render(this.scene,this.camera)})}async readSeam(){this.draw(),await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,Nj,2,this.pixels)}};function Fj(e,t){return Array.from({length:e},()=>{let e=new XT;return e.flipY=!1,e.colorSpace=``,e.magFilter=Dx,Ij(e,t),e})}function Ij(e,t){e.minFilter=t.minFilter,e.generateMipmaps=t.generateMipmaps,e.anisotropy=t.anisotropy}var Lj={programs:Aj,defines:IA};function Rj(e,t){let n=n=>oj(e,{chunks:t.programs[n],defines:t.defines});return{rectilinear:n(`rectilinear`),equirectangular:n(`equirectangular`),"lens-tiles":n(`lens-tiles`)}}function zj(e,t,n){let r=new LE;for(let i of Object.values(n)){let n=new Cw;n.add(new VT(t,i)),fj(e,n,r)}}function Bj(e){for(let t of Object.values(e))t.dispose()}var Vj={shaders:Lj,uniforms:{}},Hj=class{parts;canvas;framing=uc;viewMode=ks;hasFrames=!1;isDisposed=!1;meters=/* @__PURE__ */ new Set;constructor(e,t){this.parts=e,this.canvas=t,this.applyFraming(),t.addEventListener(`webglcontextrestored`,this.onContextRestored)}static create(e,t,n={}){let r={options:n,pictures:Vj};return new this(this.openParts(e,t,r),e)}static openParts(e,t,n){Uj(t);let r=sj(e,n.options);try{return{...Gj(r,t,n.pictures),drawSchedule:n.options.drawSchedule??wA}}catch(e){throw r.dispose(),e}}get lensCount(){return this.parts.lensCount}setFraming(e){this.ensureLive(),this.framing=e,this.applyFraming(),this.redraw()}setViewMode(e){this.ensureLive(),this.viewMode=e,this.applyFraming(),this.redraw()}setQuality(e){this.ensureLive();let t=NA[e];for(let e of this.parts.textures)Ij(e,t),this.hasFrames&&(e.needsUpdate=!0);GA(this.parts.uniforms,t),this.redraw()}setLensGains(e){this.ensureLive();for(let[t,n]of e.entries())qA(this.parts.uniforms,t,n);this.redraw()}createSeamMeter(){this.ensureLive();let e=new Pj(this.parts.renderer,this.parts.uniforms,this.parts.lensCount);return this.tracked({measure:()=>e.measure(),dispose:()=>{e.dispose()}})}setStabilization(e){this.ensureLive(),KA(this.parts.uniforms,e)}present(e){this.ensureLive();let{frames:t}=e.pair;N(t.length===this.parts.textures.length,`a pair of ${t.length} frames does not fit ${this.parts.textures.length} lens textures`);for(let[e,n]of this.parts.textures.entries()){let r=t[e];r&&n.setFrame(r.handle)}this.parts.matrixCorrections.follow(t.map(e=>e.handle)),this.hasFrames=!0,this.drawNow()}resize(e){this.ensureLive(),this.parts.renderer.setSize(e.width,e.height,!1),this.applyFraming(),this.drawNow()}dispose(){if(!this.isDisposed){this.isDisposed=!0,this.parts.drawSchedule.cancel(),this.canvas.removeEventListener(`webglcontextrestored`,this.onContextRestored);for(let e of this.meters)e.dispose();this.parts.seamProof.dispose();for(let e of this.parts.textures)e.dispose();Bj(this.parts.materials),this.parts.pass.geometry.dispose(),this.parts.renderer.dispose()}}get webgl(){return this.parts.renderer}get uniforms(){return this.parts.uniforms}tracked(e){let t={...e,dispose:()=>{this.meters.delete(t),e.dispose()}};return this.meters.add(t),t}redraw(){this.parts.drawSchedule.request(this.draw)}ensureLive(){N(!this.isDisposed,`the renderer has been disposed`)}onContextRestored=()=>{this.redraw()};drawNow(){this.parts.drawSchedule.cancel(),this.draw()}draw=()=>{this.hasFrames&&this.parts.renderer.render(this.parts.scene,this.parts.camera)};applyFraming(){let e={width:this.canvas.width,height:this.canvas.height},t=kc(this.viewMode).picture(this.framing,{viewport:e,lensCount:this.parts.lensCount});this.parts.pass.material=this.parts.materials[t.kind],YA(this.parts.uniforms,t,Ps(e))}};function Uj(e){if(!(e.lenses.length<=2&&e.frameSlotCount<=2))throw new j(`unsupported-layout`,`the renderer draws at most 2 lenses from 2 frames; the layout has ${e.lenses.length} lenses in ${e.frameSlotCount} frames`)}function Wj(e,t){let n=NA[Ts],r=Fj(e.frameSlotCount,n),i=LA(e,r);return GA(i,n),{textures:r,uniforms:i,materials:Rj({...i,...t.uniforms},t.shaders)}}function Gj(e,t,n){let{textures:r,uniforms:i,materials:a}=Wj(t,n),o=new VT(ij(),a.rectilinear),s=Kj(e,{pass:o,materials:a,textures:r,uniforms:i}),c=new Cw;return c.add(o),{renderer:e,scene:c,camera:new LE,pass:o,materials:a,textures:r,uniforms:i,matrixCorrections:new EA(t.lenses,i.uLensMatrixCorrection),lensCount:t.lenses.length,seamProof:s}}function Kj(e,t){let{pass:n,materials:r,textures:i,uniforms:a}=t;try{return zj(e,n.geometry,r),new Pj(e,a,a.uLensCount.value)}catch(e){Bj(r),n.geometry.dispose();for(let e of i)e.dispose();throw e}}var qj={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}},Jj=class{frames;pendingDraw;handle;constructor(e=qj){this.frames=e}request(e){let t=this.pendingDraw!==void 0;this.pendingDraw=e,t||(this.handle=this.frames.request(this.drawPending))}cancel(){this.pendingDraw=void 0,this.handle!==void 0&&(this.frames.cancel(this.handle),this.handle=void 0)}drawPending=()=>{let e=this.pendingDraw;this.pendingDraw=void 0,this.handle=void 0,e?.()}},Yj=class{actions=[];isDisposed=!1;add(e){if(this.isDisposed){e();return}this.actions.push(e)}disposeAll(){if(!this.isDisposed){this.isDisposed=!0;for(let e of this.actions.splice(0).toReversed())e()}}toDisposer(){return()=>{this.disposeAll()}}},Xj={maxPendingPackets:4,pairTolerance:R(5e-4)},Zj=`the recording has no audio track; playback follows a silent clock`,Qj=`this browser cannot play the audio track through Media Source Extensions; playback follows a silent clock`,$j=`the audio track could not be prepared for playback; playback follows a silent clock`;async function eM(e){let t=new Yj;try{let n=await rM(e);t.add(()=>{n.clock.dispose()}),e.signal.throwIfAborted();let r=tM(e,t),i=cM(e,n.clock,r.gainMatching);return t.add(()=>{i.dispose()}),sM(i,e.opened),{session:i,renderer:r.renderer,...nM(r,i),soundWarnings:n.warnings,dispose:t.toDisposer()}}catch(e){throw t.disposeAll(),e}}function tM(e,t){let n=Hj.create(e.host.canvas,aM(e.opened),{drawSchedule:new Jj});t.add(()=>{n.dispose()});let{sink:r,stabilizing:i}=oM(n,e.opened),a=new Gc(r,n);return t.add(()=>{a.dispose()}),{renderer:n,stabilizing:i,gainMatching:a}}function nM(e,t){return{setStabilization:n=>{e.stabilizing?.setStabilizer(is(n)),t.redraw()},setQuality:t=>{e.renderer.setQuality(t)},setGainMatching:n=>{n?e.gainMatching.enable():e.gainMatching.disable(),t.redraw()}}}async function rM(e){let{soundSegments:t}=e.opened;if(!t)return iM(Zj);try{let n=t();return _x.isSupported(n)?(e.signal.throwIfAborted(),{clock:await _x.open(e.host.audio,n),warnings:[]}):iM(Qj)}catch(e){return iM(`${$j} (${ie(e)})`)}}function iM(e){return{clock:new Qu(()=>pt(performance.now())),warnings:[e]}}function aM(e){return Fc({calibration:e.calibration,layout:e.layout,displayConversions:e.displayConversions})}function oM(e,t){if(!t.motion)return{sink:e,stabilizing:void 0};let n=new Bc({sink:e,orientations:t.motion.orientations,frameTimes:t.frameTimes});return{sink:n,stabilizing:n}}function sM(e,t){e.events.on(`statechange`,e=>{td(e)&&t.readAhead()})}function cM(e,t,n){return new vd({frameSources:e.opened.frameSources,decoderPort:e.decoderPort,clock:t,sink:n,duration:e.opened.duration,buffer:e.opened.buffer,pipeline:Xj,queueCapacity:4})}function lM(e,t,n=Ts){let r=yr(t,1,Ds(n));return{width:Math.max(1,Math.round(e.width*r)),height:Math.max(1,Math.round(e.height*r))}}function uM(e){let{width:t,height:n}=e.getBoundingClientRect();return{width:t,height:n}}var dM=class{canvas;renderer;observer;ratioWatch=new AbortController;quality=Ts;constructor(e,t){this.canvas=e,this.renderer=t,this.observer=new ResizeObserver(()=>{this.fit()}),this.observer.observe(e),this.watchPixelRatio(),this.fit()}setQuality(e){this.quality=e,this.fit()}dispose(){this.observer.disconnect(),this.ratioWatch.abort()}watchPixelRatio(){globalThis.matchMedia(`(resolution: ${globalThis.devicePixelRatio}dppx)`).addEventListener(`change`,()=>{this.fit(),this.watchPixelRatio()},{once:!0,signal:this.ratioWatch.signal})}fit(){let e=lM(uM(this.canvas),globalThis.devicePixelRatio,this.quality);(e.width!==this.canvas.width||e.height!==this.canvas.height)&&this.renderer.resize(e)}},fM=class{tick;scheduler;isActive=!1;handle;constructor(e,t=qj){this.tick=e,this.scheduler=t}start(){this.isActive||(this.isActive=!0,this.schedule())}stop(){this.isActive=!1,this.handle!==void 0&&(this.scheduler.cancel(this.handle),this.handle=void 0)}schedule(){this.handle=this.scheduler.request(()=>{this.handle=void 0,this.tick(),this.isActive&&this.schedule()})}};async function pM(e,t){let{ports:n,signal:r}=t,i=await Gu(e,n.decoderPort,vM(t));if(r.throwIfAborted(),!i.canDecode)throw gM(i)}var mM={"no-key-frame":{code:`no-key-frame`,message:`the recording has no key frame to start decoding from`},"key-frame-late":{code:`source-unreadable`,message:`the recording's first frames did not arrive in time`}},hM={code:`codec-unsupported`,message:`this browser cannot decode the recording`};function gM(e){let t=_M(e),{code:n,message:r}=(t===void 0?void 0:mM[t])??hM;return new j(n,`${r}: ${yM(e)}`)}function _M(e){let t=new Set(e.sources.filter(e=>e.verdict!==`decodes`).map(e=>e.verdict));t.has(`key-frame-late`)&&t.delete(`timed-out`);let[n]=t;return t.size===1?n:void 0}function vM(e){let t=e.ports.probeDeadline();return e.signal.addEventListener(`abort`,()=>{t.resolve()},{once:!0}),t}function yM(e){return e.sources.filter(e=>e.verdict!==`decodes`).map(e=>`track ${e.track.trackIndex} ${e.verdict}${e.detail?` (${e.detail})`:``}`).join(`; `)}async function bM(e,t){let{ports:n,signal:r}=t,i=e.map(e=>({input:e,opened:n.sources.open(e,r)})),a=await TM(i,n);r.throwIfAborted();let o=[...i,...await CM(i,a,t)],s=await Promise.all(o.map(e=>SM(e,n)));return r.throwIfAborted(),{recording:a,inputs:s}}function xM(e){let t=e.codecs.video.map(({description:e})=>({description:e}));return{name:Kb(e.input),videoTracks:t}}async function SM(e,t){let{source:n}=e.opened,{table:r,movieBytes:i}=await Do(n),a=await t.codecReader.read(i);return{...e,table:r,codecs:a,size:await n.size()}}async function CM(e,t,n){if(e.length!==1||t.info.fileLayout!==`split-files`||!n.findSecondFile)return[];let r=await n.findSecondFile();return n.signal.throwIfAborted(),r===void 0?[]:[{input:r,opened:n.ports.sources.open(r,n.signal)}]}var wM={fileLayout:void 0,trackOrder:void 0};async function TM(e,t){try{return await DM(e.map(({opened:e})=>e.source))}catch(n){let[r]=e;throw e.length===1&&M(n,`invalid-trailer`)&&r&&await EM(r,t),n}}async function EM(e,t){let n;try{n=await SM(e,t)}catch{return}try{Ro([xM(n)],wM)}catch(e){if(M(e,`missing-second-file`))throw e}}async function DM(e){let[t,n]=e;N(t!==void 0,`a recording needs at least one input`);try{return await $n(t)}catch(e){if(n===void 0||!M(e,`invalid-trailer`))throw e;return $n(n)}}async function OM(e,t){let n=new Yj;try{let r=await bM(e,t),i=Ro(r.inputs.map(e=>xM(e)),r.recording.info),a=jM(r.recording),o=kM(r.inputs,n),s=Pc(i).map(e=>AM(o,e));await pM(s,t);let c=await Gi(r.recording,s[0]);return t.signal.throwIfAborted(),MM({read:r,files:o,layout:i,frameSources:s,calibration:a,timing:c},t.ports.audioPackager,n)}catch(e){throw n.disposeAll(),e}}function kM(e,t){return e.map(({opened:n,table:r,codecs:i,size:a})=>{let o=xu({size:a,duration:r.duration},e.length),s=cu({table:r,stream:n.stream,codecs:i,policy:o});return t.add(()=>{s.dispose()}),s})}function AM(e,t){let n=e[t.inputIndex]?.videoTracks[t.trackIndex];return N(n!==void 0,`the layout points at track ${t.trackIndex} of input ${t.inputIndex}, which does not exist`),n}function jM(e){let{calibration:t,warnings:n}=e.calibration;if(t)return t;throw new j(`no-calibration`,`the recording carries no usable lens calibration, so it cannot be stitched${n.length>0?` (${n.join(`; `)})`:``}`)}function MM(e,t,n){let{read:r,files:i,layout:a,frameSources:o,calibration:s,timing:c}=e,l=R(Math.min(...i.map(e=>e.duration))),u=fl(o.map(e=>e.description.colour)),[d]=i.flatMap(e=>e.audioTracks);return{recording:r.recording,layout:a,frameSources:o,calibration:s,displayConversions:u.conversions,duration:l,frameTimes:c.frameTimes,motion:c.motion,soundSegments:d&&(()=>t.segmentsOf(d.samples,d.configuration)),metadata:NM(e,l,d!==void 0),warnings:[...c.warnings,...u.warnings],readAhead:()=>{for(let e of i)e.download.startReadingAhead()},buffer:new Su(i.map(e=>e.download)),dispose:n.toDisposer()}}function NM(e,t,n){let{info:r}=e.read.recording,{motion:i}=e.timing;return{model:r.model,firmware:r.firmware,captureMode:r.captureMode,layout:e.layout.kind,layoutEvidence:e.layout.evidence,tracks:e.frameSources.map(e=>e.description),calibrationVersion:e.calibration.version,frameTimeSource:e.timing.frameTimeSource,hasGyro:i!==void 0,imuFrame:i&&{name:i.imuFrame.name,isVerified:i.imuFrame.isVerified},hasAudio:n,duration:t}}async function PM(e,t,n){let r=FM(e,t,n),i=e.second?[e.main,e.second]:[e.main];try{return await OM(i,r)}catch(t){let{findSecondFile:i}=r;if(!i||!M(t,`missing-second-file`))throw t;let a=await i();if(n.throwIfAborted(),!a)throw t;return OM([e.main,a],r)}}function FM(e,t,n){let{main:r}=e;return e.second===void 0&&Gb(r)?{ports:t,signal:n,findSecondFile:$e(()=>IM(r,t))}:{ports:t,signal:n}}async function IM(e,t){let n=await aa(e.url,t.locatorFor(e));return n===void 0?void 0:{...e,url:n}}async function LM(e){let{parts:t,signal:n}=e,r=await PM(e.source,t.ports,n),i=new Yj;i.add(()=>{r.dispose()});try{let e=await t.pipelines({opened:r,host:t.host,decoderPort:t.ports.decoderPort,signal:n});i.add(()=>{e.dispose()}),n.throwIfAborted();let a=new dM(t.host.canvas,e.renderer);i.add(()=>{a.dispose()});let o=RM(e,a);return{opened:r,pipeline:o,warnings:zM(r,o),dispose:i.toDisposer()}}catch(e){throw i.disposeAll(),e}}function RM(e,t){return{...e,setQuality:n=>{e.setQuality(n),t.setQuality(n)}}}function zM(e,t){return[...e.warnings.map(e=>({code:`recording-degraded`,message:e})),...t.soundWarnings.map(e=>({code:`no-sound`,message:e}))]}var BM={kind:`idle`};function VM(){return{kind:`loading`,controller:new AbortController,settled:new Ou}}function HM(e){switch(e.kind){case`idle`:return`idle`;case`loading`:return`loading`;case`loaded`:return e.loaded.pipeline.session.state;case`failed`:return`error`}}var UM=class{events;mode=Zo;isMatching=!0;qualityValue=Ts;target;constructor(e){this.events=e}get stabilization(){return this.mode}get quality(){return this.qualityValue}attach(e){this.target=e,e?.setStabilization(this.mode),e?.setGainMatching(this.isMatching),e?.setQuality(this.qualityValue)}setStabilization(e){e!==this.mode&&(this.mode=e,this.target?.setStabilization(e),this.events.emit(`stabilizationchange`,e))}setGainMatching(e){this.isMatching=e,this.target?.setGainMatching(e)}setQuality(e){e!==this.qualityValue&&(this.qualityValue=e,this.target?.setQuality(e),this.events.emit(`qualitychange`,e))}},WM=class{audio;events;canSetVolume;constructor(e,t){this.audio=e,this.events=t,this.canSetVolume=KM(e.ownerDocument),e.addEventListener(`volumechange`,this.onVolumeChange)}get volume(){return this.audio.volume}get isMuted(){return this.audio.muted}setVolume(e){this.audio.volume=yr(e,0,1)}setMuted(e){this.audio.muted=e}dispose(){this.audio.removeEventListener(`volumechange`,this.onVolumeChange)}onVolumeChange=()=>{this.events.emit(`volumechange`,{volume:this.volume,isMuted:this.isMuted})}},GM=.5;function KM(e){let t=e.createElement(`audio`);return t.volume=GM,t.volume===GM}var qM=2,JM=class{events;measureViewport;framing=uc;mode=ks;surface;lensCount=qM;constructor(e,t){this.events=e,this.measureViewport=t}get current(){return this.framing.view}get viewMode(){return this.mode}get canPan(){return this.rules().canPan(this.framing)}attach(e){this.surface=e,e&&(this.lensCount=e.lensCount),e?.setViewMode(this.mode),e?.setFraming(this.framing)}set(e){this.frame({...this.framing,view:xs(e)})}setMode(e){e!==this.mode&&(this.mode=e,this.surface?.setViewMode(e),this.events.emit(`viewmodechange`,e))}lookAt(e,t){this.frame({...this.framing,view:ec(this.framing.view,e,t)})}pan(e){this.frame(this.rules().pan(this.framing,e,this.context()))}turn(e,t){this.frame(this.rules().turn(this.framing,{yaw:e,pitch:t},this.context()))}zoom(e,t=Ms){this.frame(this.rules().zoom(this.framing,{steps:e,focus:t},this.context()))}reset(){this.frame(this.rules().reset(this.framing))}frame(e){if(dc(e,this.framing))return;let t=!Ss(e.view,this.framing.view);this.framing=e,this.surface?.setFraming(e),t&&this.events.emit(`viewchange`,e.view)}context(){return{viewport:this.measureViewport(),lensCount:this.lensCount}}rules(){return kc(this.mode)}},YM=/* @__PURE__ */ new Set([`ready`,`paused`,`ended`]),XM=/* @__PURE__ */ new Map([[`playing`,`playing`],[`buffering`,`waiting`]]);function ZM(e,t){return t===`seeking`?[`seeking`]:e===`seeking`?t===`buffering`?[`seeked`,`waiting`]:[`seeked`]:t===`paused`?e===`ready`?[]:[`pause`]:QM(e,t)}function QM(e,t){let n=XM.get(t);return n===void 0?[]:e===void 0||YM.has(e)?[`play`,n]:[n]}var $M=class{targets;stopListening=[];lastState;detachments=0;constructor(e){this.targets=e}attach(e){this.detach(),this.lastState=e.state;let{events:t}=this.targets;this.stopListening=[e.events.on(`statechange`,t=>{this.onStateChange(t,e)}),e.events.on(`timeupdate`,e=>{t.emit(`timeupdate`,e)}),e.events.on(`present`,e=>{t.emit(`frame`,e)}),e.events.on(`ended`,()=>{this.targets.onEnded()}),e.events.on(`error`,e=>{t.emit(`error`,e)})]}detach(){for(let e of this.stopListening)e();this.stopListening=[],this.lastState=void 0,this.detachments+=1}onStateChange(e,t){let n=this.lastState;this.lastState=e;let r=this.detachments;for(let i of ZM(n,e))if(this.emitTransport(i,t),this.detachments!==r)return;this.targets.onState(e)}emitTransport(e,t){let{events:n}=this.targets;e===`seeking`||e===`seeked`?n.emit(e,t.currentTime):n.emit(e,void 0)}},eN=class{parts;events=new rd;outbox=new vl(this.events);loop;phase=BM;viewing;picture=new UM(this.outbox);pendingStartTime;sound;relay=new $M({events:this.outbox,onState:()=>{this.announceStatus()},onEnded:()=>{this.onEnded()}});isLoopingValue=!1;isDisposed=!1;lastStatus=`idle`;constructor(e){this.parts=e,this.loop=new fM(this.tick),e.host.audio.addEventListener(`ended`,this.tick),this.sound=new WM(e.host.audio,this.outbox);let{canvas:t}=e.host;this.viewing=new JM(this.outbox,()=>uM(t))}get status(){return HM(this.phase)}get metadata(){return this.loaded?.opened.metadata}get currentTime(){return this.loaded?.pipeline.session.currentTime??R(0)}get duration(){return this.loaded?.opened.duration??R(0)}get isPaused(){return!td(this.loaded?.pipeline.session.state)}get view(){return this.viewing.current}get viewMode(){return this.viewing.viewMode}get canPan(){return this.viewing.canPan}get stabilization(){return this.picture.stabilization}get quality(){return this.picture.quality}get isLooping(){return this.isLoopingValue}get volume(){return this.sound.volume}get isMuted(){return this.sound.isMuted}get canSetVolume(){return this.sound.canSetVolume}async load(e,t={}){if(this.isDisposed)return;let n=this.outbox.change(()=>{this.unload();let e=VM();return this.phase=e,this.announceStatus(),e});try{await this.complete(n,e,t)}catch(e){if(n.controller.signal.aborted)return;throw this.failWith(e)}finally{n.settled.resolve()}}unload(){this.outbox.change(()=>{this.release(),this.announceStatus()})}async play(){if(await this.loadInProgress(),this.phase.kind===`failed`)throw this.phase.failure;await this.loaded?.pipeline.session.play()}pause(){this.loaded?.pipeline.session.pause()}stop(){this.loaded?.pipeline.session.stop()}seek(e){jd(e,`time`);let t=this.loaded?.pipeline.session;t&&t.state!==`error`?t.seek(R(e)):this.pendingStartTime=R(e)}async scrub(e){jd(e,`time`),await this.loaded?.pipeline.session.scrub(R(e))}setView(e){this.viewing.set(Md(e))}lookAt(e,n){jd(e,`yaw`),jd(n,`pitch`),this.viewing.lookAt(t(e),t(n))}pan(e){this.viewing.pan(e)}turn(e,n){jd(e,`yaw turn`),jd(n,`pitch turn`),this.viewing.turn(t(e),t(n))}zoom(e,t){jd(e,`zoom steps`),this.viewing.zoom(e,t)}resetView(){this.viewing.reset()}setViewMode(e){this.viewing.setMode(e)}setStabilization(e){this.picture.setStabilization(e)}setQuality(e){this.picture.setQuality(e)}setLooping(e){this.isLoopingValue=e}setGainMatching(e){this.picture.setGainMatching(e)}setVolume(e){jd(e,`volume`),this.sound.setVolume(e)}setMuted(e){this.sound.setMuted(e)}dispose(){this.isDisposed=!0,this.unload(),this.parts.host.audio.removeEventListener(`ended`,this.tick),this.sound.dispose(),this.events.removeAll()}tick=()=>{this.loaded?.pipeline.session.tick()};async loadInProgress(){this.phase.kind===`loading`&&await this.phase.settled.promise}get loaded(){return this.phase.kind===`loaded`?this.phase.loaded:void 0}async complete(e,t,n){let{signal:r}=e.controller,i=await LM({source:t,parts:this.parts,signal:r});if(r.aborted){i.dispose();return}this.outbox.change(()=>{this.attach(i,e.controller),this.startAtPendingTime(i),n.preload!==!1&&i.pipeline.session.preload()}),n.autoplay&&this.loaded===i&&await this.autoplay()}startAtPendingTime(e){let t=this.pendingStartTime;this.pendingStartTime=void 0,t!==void 0&&e.pipeline.session.seek(t)}attach(e,t){this.phase={kind:`loaded`,loaded:e,controller:t},this.viewing.attach(e.pipeline.renderer);let{session:n}=e.pipeline;this.picture.attach(e.pipeline),this.relay.attach(n),this.loop.start(),this.announceStatus();for(let t of e.warnings)this.outbox.emit(`warning`,t);this.outbox.emit(`ready`,e.opened.metadata)}async autoplay(){try{await this.play()}catch(e){this.outbox.emit(`warning`,M(e,`playback-blocked`)?{code:`autoplay-blocked`,message:`playback waits for a user gesture`}:{code:`playback-failed`,message:`autoplay failed: ${ie(e)}`})}}onEnded(){this.outbox.emit(`ended`,void 0),this.isLoopingValue&&this.replay()}async replay(){try{await this.play()}catch(e){this.outbox.emit(`warning`,{code:`playback-failed`,message:`the loop could not restart playback: ${ie(e)}`})}}release(){let e=this.phase;this.phase=BM,e.kind===`loading`&&e.controller.abort(),this.loop.stop(),this.relay.detach(),this.viewing.attach(void 0),this.picture.attach(void 0),e.kind===`loaded`&&(e.loaded.dispose(),e.controller.abort())}failWith(e){let t=ne(e,`invariant-violation`,`the player failed unexpectedly`);return this.outbox.change(()=>{this.release(),this.phase={kind:`failed`,failure:t},this.announceStatus(),this.outbox.emit(`error`,t)}),t}announceStatus(){let{status:e}=this;this.outbox.post(()=>{e!==this.lastStatus&&(this.lastStatus=e,this.events.emit(`statuschange`,e))})}};function tN(e,t){return new eN({host:e,ports:Jb(t),pipelines:eM})}function nN(e,t={}){let n=t.signal??new AbortController().signal,{source:r}=Yb(t.http??{}).open(rN(e),n);return dr(r)}function rN(e){return typeof e==`string`?{url:e}:{blob:e,name:e instanceof File?e.name:``}}var iN={Src:`src`,Src2:`src2`},aN={CrossOrigin:`crossorigin`},oN={FieldOfView:`fov`,Yaw:`yaw`,Pitch:`pitch`},sN={Autoplay:`autoplay`,Preload:`preload`,GainMatch:`gain-match`,Muted:`muted`,Loop:`loop`,Stabilization:`stabilization`,ViewMode:`view-mode`,Quality:`quality`,Controls:`controls`,Poster:`poster`},cN=[...Object.values(iN),...Object.values(aN),...Object.values(oN),...Object.values(sN)];function lN(e,t){let n=dN(e(aN.CrossOrigin)),r=uN(e(iN.Src),t,n);return r&&{main:r,second:uN(e(iN.Src2),t,n)}}function uN(e,t,n){let r=e?.trim()??``;return r===``?void 0:{url:fN(r,t),...n}}function dN(e){return Dd(xN,e)===`use-credentials`?{credentials:`include`}:{}}function fN(e,t){try{return new URL(e,t).href}catch{return e}}var pN={[oN.FieldOfView]:`fieldOfView`,[oN.Yaw]:`yaw`,[oN.Pitch]:`pitch`};function mN(e,t,n){let r=pN[t],i=gN(n);return r===void 0||i===void 0?e:{...e,[r]:i}}function hN(e){return e!==null}function gN(e){if(e===null||e.trim()===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function _N(e,t,n){return{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected one of ${n.join(`, `)}`}}function vN(e,t){return t===null||gN(t)!==void 0?void 0:{code:`ignored-attribute`,message:`ignoring ${e}="${t}"; expected a number of degrees`}}var yN={name:sN.Preload,keywords:[`none`,`auto`],fallback:`auto`},bN={name:sN.GainMatch,keywords:[`on`,`off`],fallback:`on`},xN={name:aN.CrossOrigin,property:`crossOrigin`,keywords:[`anonymous`,`use-credentials`],fallback:`anonymous`};function SN(e){return Dd(yN,e)===`auto`}function CN(e){return Dd(bN,e)===`on`}function wN(e,t,n){return n?TN(n):lN(e,t)}function TN(e){return{main:{blob:e.main,name:e.main.name},second:e.second&&{blob:e.second,name:e.second.name}}}var EN=class{element;player;scheduled;isOwed=!0;awaited;startTime;files;constructor(e,t){this.element=e,this.player=t}connected(){this.isOwed&&this.schedule(),this.awaited?.follow(this.scheduled??Promise.resolve()),this.awaited=void 0}async disconnected(){await Promise.resolve(),!this.element.isConnected&&(this.player.unload(),this.isOwed=!0)}sourceChanged(){this.files=void 0,this.schedule()}requestChanged(){this.files===void 0&&this.schedule()}loadFiles(e){this.files=e,this.schedule()}load(){return this.element.isConnected?this.scheduled??this.reload():this.loadOnConnection()}seek(e){this.scheduled?this.startTime=e:this.player.seek(e)}async settled(){try{await this.scheduled}catch{}}loadOnConnection(){return this.isOwed=!0,this.awaited??=new Ou,this.awaited.promise}schedule(){if(this.isOwed=!this.element.isConnected,this.scheduled||!this.element.isConnected)return;let e=this.loadAfterPendingChanges();this.scheduled=e,e.catch(DN)}async loadAfterPendingChanges(){await Promise.resolve(),this.scheduled=void 0,this.element.isConnected&&await this.reload()}reload(){this.isOwed=!1;let e=e=>this.element.getAttribute(e),t=wN(e,document.baseURI,this.files);delete this.element.dataset.hasFrame;let n=this.startTime;if(this.startTime=void 0,!t)return this.player.unload(),Promise.resolve();let r=this.player.load(t,{autoplay:this.element.autoplay,preload:SN(e(sN.Preload))});return n!==void 0&&this.player.seek(n),r}};function DN(){}var ON=`data-fill`,kN=class{element;constructor(e){this.element=e}get isActive(){return this.isNativelyFullscreen()||this.element.hasAttribute(ON)}async toggle(){await(this.isActive?this.exit():this.enter())}async exit(){this.isNativelyFullscreen()&&await document.exitFullscreen(),this.element.removeAttribute(ON)}isNativelyFullscreen(){return this.element.matches(`:fullscreen`)}async enter(){if(document.fullscreenEnabled)try{await this.element.requestFullscreen();return}catch{}this.element.setAttribute(ON,``)}},AN=`data-idle`,jN=2500,MN=[`pointermove`,`pointerdown`,`keydown`,`focusin`],NN={capture:!0},PN=class{element;shouldHide;timer;wasIdleAtPress=!1;constructor(e,t){this.element=e,this.shouldHide=t}get wasIdleAtLastPress(){return this.wasIdleAtPress}start(){this.element.addEventListener(`pointerdown`,this.onPress,NN);for(let e of MN)this.element.addEventListener(e,this.onActivity,NN);this.onActivity()}stop(){for(let e of MN)this.element.removeEventListener(e,this.onActivity,NN);this.element.removeEventListener(`pointerdown`,this.onPress,NN),this.clearTimer(),this.element.removeAttribute(AN)}refresh(){this.shouldHide()||this.element.removeAttribute(AN),this.restart()}onPress=()=>{this.wasIdleAtPress=this.element.hasAttribute(AN)};onActivity=()=>{this.element.removeAttribute(AN),this.restart()};restart(){this.clearTimer(),this.timer=setTimeout(()=>{this.shouldHide()&&this.element.setAttribute(AN,``)},jN)}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}};function FN(e,t,n){return({player:r,warn:i},a)=>{let o=yd(a,t);o?n(r,o):a!==null&&i(_N(e,a,t))}}var IN={[sN.Stabilization]:FN(sN.Stabilization,Xo,(e,t)=>{e.setStabilization(t)}),[sN.ViewMode]:FN(sN.ViewMode,Os,(e,t)=>{e.setViewMode(t)}),[sN.Quality]:FN(sN.Quality,ws,(e,t)=>{e.setQuality(t)}),[sN.Muted]:({player:e},t)=>{e.setMuted(hN(t))},[sN.Loop]:({player:e},t)=>{e.setLooping(hN(t))},[sN.Poster]:({posterImage:e},t)=>{e.src=t??``},[sN.GainMatch]:({player:e},t)=>{e.setGainMatching(CN(t))}};function LN(e){return Object.hasOwn(IN,e)}function RN(e,t,n){LN(t)&&IN[t](e,n)}function zN(e,t){e.hasAttribute(`tabindex`)||(e.tabIndex=0),e.hasAttribute(`role`)||e.setAttribute(`role`,`region`),e.hasAttribute(`aria-label`)||e.hasAttribute(`aria-labelledby`)||e.setAttribute(`aria-label`,t)}function BN(e,t,n){e.getAttribute(`aria-label`)===t&&e.setAttribute(`aria-label`,n)}function VN(e,t){let n=/* @__PURE__ */ new Map;for(let r of t)Object.hasOwn(e,r)&&(n.set(r,Reflect.get(e,r)),Reflect.deleteProperty(e,r));return n}function HN(e,t,n){let r=[...t];t.clear();for(let[t,i]of r)try{Reflect.set(e,t,i)}catch(e){n({code:`refused-property`,message:`${t} set before the element was defined was refused: ${ie(e)}`})}}var UN=_l({stabilization:!0,viewMode:!0,quality:!0,fov:!0,yaw:!0,pitch:!0,muted:!0,loop:!0,volume:!0});function WN(e,t){let n={stabilization:{get:()=>t.stabilization,set:XN(e=>{t.setStabilization(qN(e))})},viewMode:{get:()=>t.viewMode,set:XN(e=>{t.setViewMode(JN(e))})},quality:{get:()=>t.quality,set:XN(e=>{t.setQuality(YN(e))})},...GN(t),...KN(t)};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{configurable:!0,enumerable:!0,...r})}function GN(e){let t=(t,n)=>({get:()=>e.view[t],set:XN(r=>{e.setView({...e.view,[t]:QN(r,n)})})});return{fov:t(`fieldOfView`,`fov`),yaw:t(`yaw`,`yaw`),pitch:t(`pitch`,`pitch`)}}function KN(e){return{muted:{get:()=>e.isMuted,set:t=>{e.setMuted(!!t)}},loop:{get:()=>e.isLooping,set:t=>{e.setLooping(!!t)}},volume:{get:()=>e.volume,set:XN(t=>{e.setVolume($N(t,`volume`))})}}}function qN(e){return ZN(e,bd,`stabilization`)}function JN(e){return ZN(e,xd,`viewMode`)}function YN(e){return ZN(e,Sd,`quality`)}function XN(e){return t=>{t!=null&&t!==``&&e(t)}}function ZN(e,t,n){let r=typeof e==`string`?t(e):void 0;if(r===void 0)throw new j(`invalid-argument`,`${n} cannot be ${String(e)}`);return r}function QN(e,n){return t($N(e,n))}function $N(e,t){return jd(e,t),e}var eP=`/*
|
|
4644
4643
|
* The controls' own styles: the big play button, the bar, its buttons, sliders and menus, and the
|
|
4645
4644
|
* grab hand over the picture. The host's custom properties (\`--gyro-view-*\`) theme them. Secondary
|
|
4646
4645
|
* words, fills and tracks are the text colour at lower strengths, so a page that changes the text
|
|
@@ -5114,17 +5113,17 @@ canvas[data-draggable]:active {
|
|
|
5114
5113
|
transition: none;
|
|
5115
5114
|
}
|
|
5116
5115
|
}
|
|
5117
|
-
`,
|
|
5116
|
+
`,tP=`gyroview`;function nP(e){let t=document.createElement(`template`);return t.innerHTML=rP()?.createHTML(e)??e,t.content}var rP=$e(()=>{let e=globalThis.trustedTypes;try{return e?.createPolicy(tP,{createHTML:e=>e})}catch{return}});function iP(e){return`<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">${e}</svg>`}function aP(e){return iP(`<g transform="scale(1.2)" stroke-width="1.5">${e}</g>`)}var oP=`<path d="M4 9.5v5h3.5L12 19V5L7.5 9.5z"/>`,sP={play:iP(`<path d="M8 5v14l11-7z" fill="currentColor"/>`),pause:iP(`<rect x="6" y="5" width="4" height="14" rx="1" fill="currentColor" stroke="none"/><rect x="14" y="5" width="4" height="14" rx="1" fill="currentColor" stroke="none"/>`),sound:iP(`${oP}<path d="M15.5 9a4 4 0 0 1 0 6"/><path d="M18.5 6a8 8 0 0 1 0 12"/>`),muted:iP(`${oP}<path d="M16 9.5l5 5M21 9.5l-5 5"/>`),resetView:iP(`<path d="M4.5 12a7.5 7.5 0 1 0 2.2-5.3"/><path d="M4.5 4.5v4h4"/>`),fullscreen:iP(`<path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5"/>`),close:iP(`<path d="M6 6l12 12M18 6L6 18"/>`)},cP={off:aP(`<path d="M2 11l2.5-3 3 4.5 3-6 3 5 2-2.5L18 11"/>`),lock:aP(`<rect x="4.5" y="9" width="11" height="8" rx="1.5"/><path d="M7 9V6.5a3 3 0 016 0V9"/>`),horizon:aP(`<circle cx="10" cy="10" r="7"/><path d="M3 10h14M8 13h4"/>`),follow:aP(`<path d="M3 15c3.5 0 4-9 8.5-9 2 0 3 1 4.5 1"/><path d="M14 4.5L16.5 7 14 9.5"/>`)},lP={"raw-lenses":aP(`<circle cx="6" cy="10" r="4.25"/><circle cx="14" cy="10" r="4.25"/>`),equirectangular:aP(`<rect x="2" y="5" width="16" height="10" rx="1.5"/><path d="M2 10h16M7.5 5c-1.2 3.3-1.2 6.7 0 10M12.5 5c1.2 3.3 1.2 6.7 0 10"/>`),normal:aP(`<path d="M10 16L3.2 7.2a10 10 0 0113.6 0z"/>`)},uP=/* @__PURE__ */ new Map;function dP(e){let t=uP.get(e);return t||(t=nP(sP[e]),uP.set(e,t)),t.cloneNode(!0)}var fP={names:`stabilizationModes`,descriptions:`stabilizationModeDescriptions`},pP={names:`viewModes`,descriptions:`viewModeDescriptions`},mP=new Set([fP,pP].flatMap(e=>[e.names,e.descriptions])),hP=`The video could not be loaded.`,gP=`This browser cannot play this video.`,_P=`This file cannot be played.`,vP=`The video could not be played.`,yP={labels:{player:`360° video player`,loading:`Loading`,play:`Play`,pause:`Pause`,seek:`Seek`,position:`{time} of {duration}`,mute:`Mute`,volume:`Volume`,resetView:`Reset view`,stabilization:`Stabilization`,viewMode:`View`,fullscreen:`Fullscreen`,close:`Close`},stabilizationModes:{off:`Off`,lock:`Lock`,horizon:`Horizon`,follow:`Follow`},stabilizationModeDescriptions:{off:`Footage as the camera moved`,lock:`Orientation fixed to the world`,horizon:`Level horizon, follows heading`,follow:`Follows turns, smooths out shake`},viewModes:{"raw-lenses":`Raw lenses`,equirectangular:`Equirectangular`,normal:`Normal`},viewModeDescriptions:{"raw-lenses":`Both fisheye images as recorded`,equirectangular:`The full 360° frame, unwrapped`,normal:`Standard view, drag to look around`},errors:{"binary-out-of-bounds":_P,"binary-unsafe-integer":_P,"codec-unsupported":gP,cors:hP,decode:vP,"embed-destroyed":vP,"index-out-of-range":vP,"invalid-argument":vP,"invalid-byte-range":hP,"invalid-calibration":_P,"invalid-protobuf":_P,"invalid-trailer":_P,"invariant-violation":vP,"missing-second-file":`Part of this recording is missing.`,"no-calibration":_P,"no-info-record":_P,"no-key-frame":_P,"playback-blocked":vP,"range-unsupported":hP,"render-unavailable":gP,"source-changed":`The video was replaced while it played.`,"source-truncated":hP,"source-unreadable":hP,"unsupported-calibration":_P,"unsupported-container":_P,"unsupported-gyro-record":_P,"unsupported-info-format":_P,"unsupported-layout":_P,"webcodecs-unavailable":gP}};function bP(e){let t=wP(e)?e:{};return{labels:CP(yP.labels,t.labels),stabilizationModes:CP(yP.stabilizationModes,t.stabilizationModes),stabilizationModeDescriptions:CP(yP.stabilizationModeDescriptions,t.stabilizationModeDescriptions),viewModes:CP(yP.viewModes,t.viewModes),viewModeDescriptions:CP(yP.viewModeDescriptions,t.viewModeDescriptions),errors:CP(yP.errors,t.errors)}}function xP(e){return e!==null&&Object.hasOwn(yP.labels,e)}function SP(e){return e!==null&&mP.has(e)}function CP(e,t){if(!wP(t))return e;let n=Object.entries(e).map(([e,n])=>{let r=t[e];return[e,typeof r==`string`?r:n]});return Object.fromEntries(n)}function wP(e){return typeof e==`object`&&!!e}var TP={Stabilization:`stabilization`,ViewMode:`view-mode`};function EP(e){return{button:`${e}-button`,popup:`${e}-menu`}}function DP(e){return e.choices.map(t=>{let n=`${e.name}-${t}`;return`<button type="button" role="menuitemradio" aria-checked="false" tabindex="-1" data-choice="${t}" aria-labelledby="${n}-name" aria-describedby="${n}-description"><span class="choice-icon">${e.icons[t]??``}</span><span class="choice-name" id="${n}-name" data-choice-text="${e.words.names}"></span><span class="choice-description" id="${n}-description" data-choice-text="${e.words.descriptions}"></span></button>`}).join(``)}function OP(e){let t=EP(e.name),[n,r]=[`${e.name}-label`,`${e.name}-value`];return`<div class="choice">
|
|
5118
5117
|
<button class="icon-button setting ${t.button}" type="button" aria-haspopup="menu" aria-expanded="false" aria-labelledby="${n} ${r}"><span class="setting-icon"></span><span hidden><span id="${n}" data-text="${e.title}"></span> <span id="${r}" data-choice-text="${e.words.names}"></span></span></button>
|
|
5119
5118
|
<div class="popup ${t.popup}" hidden>
|
|
5120
5119
|
<div class="popup-header">
|
|
5121
5120
|
<p class="popup-title" aria-hidden="true" data-text="${e.title}"></p>
|
|
5122
|
-
<button class="icon-button popup-close" type="button" data-label="close">${
|
|
5121
|
+
<button class="icon-button popup-close" type="button" data-label="close">${sP.close}</button>
|
|
5123
5122
|
</div>
|
|
5124
|
-
<div role="menu" data-label="${e.title}">${
|
|
5123
|
+
<div role="menu" data-label="${e.title}">${DP(e)}</div>
|
|
5125
5124
|
</div>
|
|
5126
|
-
</div>`}function
|
|
5127
|
-
<button class="big-play" part="big-play" type="button">${
|
|
5125
|
+
</div>`}function kP(){return OP({name:TP.Stabilization,title:`stabilization`,choices:Xo,icons:cP,words:fP})+OP({name:TP.ViewMode,title:`viewMode`,choices:Os,icons:lP,words:pP})}var AP=eP;function jP(){return`
|
|
5126
|
+
<button class="big-play" part="big-play" type="button">${sP.play}</button>
|
|
5128
5127
|
<div class="controls" part="controls">
|
|
5129
5128
|
<input class="seek" type="range" min="0" max="0" step="0.01" value="0" data-label="seek" />
|
|
5130
5129
|
<div class="row">
|
|
@@ -5133,11 +5132,11 @@ canvas[data-draggable]:active {
|
|
|
5133
5132
|
<input class="volume" type="range" min="0" max="1" step="0.01" value="1" data-label="volume" />
|
|
5134
5133
|
<span class="time"><span class="elapsed">0:00</span> <span class="total">/ 0:00</span></span>
|
|
5135
5134
|
<span class="spacer"></span>
|
|
5136
|
-
${
|
|
5137
|
-
<button class="icon-button reset-view" type="button" data-label="resetView">${
|
|
5138
|
-
<button class="icon-button fullscreen" type="button" data-label="fullscreen">${
|
|
5135
|
+
${kP()}
|
|
5136
|
+
<button class="icon-button reset-view" type="button" data-label="resetView">${sP.resetView}</button>
|
|
5137
|
+
<button class="icon-button fullscreen" type="button" data-label="fullscreen">${sP.fullscreen}</button>
|
|
5139
5138
|
</div>
|
|
5140
|
-
</div>`}function
|
|
5139
|
+
</div>`}function MP(e,t,n){let r=e.querySelector(t);return N(r instanceof n,`the element template lacks ${t}`),r}function NP(e,t){let n=EP(t);return{button:MP(e,`.${n.button}`,HTMLButtonElement),icon:MP(e,`.${n.button} .setting-icon`,HTMLElement),popup:MP(e,`.${n.popup}`,HTMLElement),close:MP(e,`.${n.popup} .popup-close`,HTMLButtonElement)}}function PP(e){return{seek:MP(e,`.seek`,HTMLInputElement),play:MP(e,`.play`,HTMLButtonElement),bigPlay:MP(e,`.big-play`,HTMLButtonElement),elapsed:MP(e,`.time .elapsed`,HTMLElement),total:MP(e,`.time .total`,HTMLElement),mute:MP(e,`.mute`,HTMLButtonElement),volume:MP(e,`.volume`,HTMLInputElement),resetView:MP(e,`.reset-view`,HTMLButtonElement),stabilization:NP(e,TP.Stabilization),viewMode:NP(e,TP.ViewMode),fullscreen:MP(e,`.fullscreen`,HTMLButtonElement)}}var FP=_l({statuschange:!0,ready:!0,play:!0,playing:!0,waiting:!0,pause:!0,ended:!0,timeupdate:!0,seeking:!0,seeked:!0,frame:!0,viewchange:!0,viewmodechange:!0,stabilizationchange:!0,qualitychange:!0,volumechange:!0,warning:!0,error:!0});function IP(e,t){let{element:n,shadow:r,idle:i,wording:a}=t,o=MP(r,`.error-message`,HTMLElement),s=MP(r,`.error-code`,HTMLElement);e.events.on(`statuschange`,e=>{n.dataset.status=e,i.refresh()}),e.events.on(`frame`,()=>{n.dataset.hasFrame=``}),e.events.on(`error`,e=>{a.showError(o,e.code),s.textContent=e.code});for(let t of FP)e.events.on(t,e=>{n.dispatchEvent(new CustomEvent(t,{detail:e,composed:!0}))})}var LP=`:host {
|
|
5141
5140
|
--gyro-view-accent: #fff;
|
|
5142
5141
|
--gyro-view-controls-background: rgb(0 0 0 / 60%);
|
|
5143
5142
|
--gyro-view-menu-background: rgb(24 24 23 / 92%);
|
|
@@ -5272,7 +5271,7 @@ canvas {
|
|
|
5272
5271
|
font-size: 0.8rem;
|
|
5273
5272
|
opacity: 0.7;
|
|
5274
5273
|
}
|
|
5275
|
-
`;function
|
|
5274
|
+
`;function RP(){return`
|
|
5276
5275
|
<div class="stage" part="stage">
|
|
5277
5276
|
<canvas part="canvas"></canvas>
|
|
5278
5277
|
<img class="poster" part="poster" alt="" />
|
|
@@ -5284,6 +5283,6 @@ canvas {
|
|
|
5284
5283
|
<p class="error-message" part="error-message"></p>
|
|
5285
5284
|
<p class="error-code" part="error-code"></p>
|
|
5286
5285
|
</div>
|
|
5287
|
-
${
|
|
5286
|
+
${jP()}
|
|
5288
5287
|
</div>
|
|
5289
|
-
`}var EL=et(()=>UI(TL())),DL=et(()=>[wL,_L].map(e=>kL(e)));function OL(e){e.adoptedStyleSheets=DL(),e.append(EL().cloneNode(!0))}function kL(e){let t=new CSSStyleSheet;return t.replaceSync(e),t}var AL=typeof HTMLElement==`function`?HTMLElement:Object,jL=class extends AL{addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}},ML=/* @__PURE__ */ new Map([[`ArrowDown`,(e,t)=>(e+1)%t],[`ArrowUp`,(e,t)=>(e-1+t)%t],[`Home`,()=>0],[`End`,(e,t)=>t-1]]),NL={capture:!0},PL=class{parts;host;items;constructor(e,t,n){this.parts=t,this.host=n,this.items=[...t.popup.querySelectorAll(`:scope [role="menuitemradio"]`)];for(let e of this.items)e.addEventListener(`click`,()=>{this.closeToButton();let{choice:t}=e.dataset;t!==void 0&&n.choose(t)});t.close.addEventListener(`click`,()=>{this.closeToButton()}),this.bindButton(),this.bindDismissal(e),this.bindKeys(e)}get isOpen(){return!this.parts.popup.hidden}markChosen(e){for(let t of this.items)t.setAttribute(`aria-checked`,String(t.dataset.choice===e));let t=this.items.find(t=>t.dataset.choice===e)?.querySelector(`:scope .choice-icon > svg`);this.parts.icon.replaceChildren(...t?[t.cloneNode(!0)]:[]),this.parts.button.dataset.choice=e,this.host.wording.write(this.parts.button)}setAvailable(e){this.parts.button.hidden=!e,e||this.setOpen(!1)}bindButton(){this.parts.button.addEventListener(`click`,()=>{this.setOpen(!this.isOpen),this.isOpen&&this.focusItem(this.items.findIndex(e=>FL(e)))})}bindDismissal(e){let{button:t,popup:n}=this.parts;e.addEventListener(`pointerdown`,e=>{this.isOpen&&(e.composedPath().some(e=>e===n||e===t)||(this.setOpen(!1),e.stopPropagation()))},NL),e.addEventListener(`focusout`,e=>{let r=e instanceof FocusEvent?e.relatedTarget:null;r!==t&&r instanceof Node&&!n.contains(r)&&this.setOpen(!1)})}bindKeys(e){e.addEventListener(`keydown`,e=>{this.isOpen&&e instanceof KeyboardEvent&&this.onKey(e)})}onKey(e){let t=e.composedPath();if(e.key===`Escape`){this.closeToButton(),e.stopPropagation();return}t.includes(this.parts.popup)&&(e.stopPropagation(),e.key===`Tab`?this.setOpen(!1):this.moveFocus(e,t))}moveFocus(e,t){let n=ML.get(e.key);if(!n)return;e.preventDefault();let r=this.items.findIndex(e=>t.includes(e));this.focusItem(n(r,this.items.length))}focusItem(e){(this.items[e]??this.items[0])?.focus()}closeToButton(){this.setOpen(!1),this.parts.button.focus()}setOpen(e){this.parts.popup.hidden=!e,this.parts.button.setAttribute(`aria-expanded`,String(e))}};function FL(e){return e.getAttribute(`aria-checked`)===`true`}var IL=class{viewMode;stabilization;player;constructor(e,t,n){let{player:r,wording:i}=n;this.player=r,this.viewMode=new PL(e,t.viewMode,{wording:i,choose:e=>{let t=bd(e);t&&r.setViewMode(t)}}),this.stabilization=new PL(e,t.stabilization,{wording:i,choose:e=>{let t=yd(e);t&&r.setStabilization(t)}}),this.followPlayer()}followPlayer(){let{player:e}=this;e.events.on(`viewmodechange`,e=>{this.viewMode.markChosen(e),this.offerStabilization()}),e.events.on(`stabilizationchange`,e=>{this.stabilization.markChosen(e)}),e.events.on(`statuschange`,()=>{this.offerStabilization()}),this.viewMode.markChosen(e.viewMode),this.stabilization.markChosen(e.stabilization),this.offerStabilization()}offerStabilization(){let e=this.player.metadata?.hasGyro===!0,t=kc(this.player.viewMode).isStabilized;this.stabilization.setAvailable(e&&t)}},LL=60,RL=60;function zL(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%LL,r=Math.floor(t/LL)%RL,i=Math.floor(t/3600);return i>0?`${i}:${BL(r)}:${BL(n)}`:`${r}:${BL(n)}`}function BL(e){return String(e).padStart(2,`0`)}function VL(e){let t=Number(e.min),n=Number(e.max)-t,r=n>0?(Number(e.value)-t)/n:0;e.style.setProperty(`--fill`,String(br(r,0,1)))}var HL=/* @__PURE__ */ new Map([[`ArrowLeft`,-1],[`ArrowDown`,-1],[`ArrowRight`,1],[`ArrowUp`,1]]),UL=[`pointerup`,`pointercancel`,`change`],WL=class{parts;host;isScrubbing=!1;scrubTarget;scrubbing;constructor(e,t){this.parts=e,this.host=t,this.bindInput();let{events:n}=this.host.player;n.on(`statuschange`,()=>{this.showRecording()}),n.on(`timeupdate`,e=>{this.follow(e)}),this.showRecording()}bindInput(){let{seek:e}=this.parts;e.addEventListener(`input`,()=>{this.isScrubbing=!0;let t=Number(e.value);this.showTime(t),this.scrubTo(t)});for(let t of UL)e.addEventListener(t,()=>{this.endScrub()});e.addEventListener(`keydown`,e=>{let t=HL.get(e.key);if(t===void 0)return;e.preventDefault();let{player:n}=this.host;n.seek(n.currentTime+t*5)})}showRecording(){let{duration:e,currentTime:t}=this.host.player;this.parts.seek.max=String(e),this.follow(t)}follow(e){this.isScrubbing||(this.parts.seek.value=String(e),this.showTime(e))}scrubTo(e){this.scrubTarget=e,this.scrubbing??=this.drainScrubs()}async drainScrubs(){try{for(;this.scrubTarget!==void 0;){let e=this.scrubTarget;this.scrubTarget=void 0,await this.host.player.scrub(e)}}catch(e){this.host.warn({code:`playback-failed`,message:`the seek bar could not show that moment: ${oe(e)}`})}finally{this.scrubbing=void 0}}endScrub(){this.isScrubbing&&(this.isScrubbing=!1,this.scrubTarget=void 0,this.host.player.seek(Number(this.parts.seek.value)))}showTime(e){let[t,n]=[zL(e),zL(this.host.player.duration)];this.parts.elapsed.textContent=t,this.parts.total.textContent=`/ ${n}`;let{position:r}=this.host.wording.current.labels,i=r.replaceAll(`{time}`,()=>t).replaceAll(`{duration}`,()=>n);this.parts.seek.setAttribute(`aria-valuetext`,i),VL(this.parts.seek)}},GL=100,KL=class{parts;player;constructor(e,t){this.parts=e,this.player=t,e.volume.hidden=!t.canSetVolume,e.mute.addEventListener(`click`,()=>{t.setMuted(!t.isMuted)}),e.volume.addEventListener(`input`,()=>{t.setVolume(Number(e.volume.value)),t.isMuted&&t.setMuted(!1)}),t.events.on(`volumechange`,()=>{this.reflect()}),this.reflect()}reflect(){let{isMuted:e,volume:t}=this.player,n=e?0:t;this.parts.mute.replaceChildren(QI(e?`muted`:`sound`)),this.parts.mute.setAttribute(`aria-pressed`,String(e)),this.parts.volume.value=String(n),this.parts.volume.setAttribute(`aria-valuetext`,`${Math.round(n*GL)}%`),VL(this.parts.volume)}},qL=class{parts;host;constructor(e,t){this.parts=e,this.host=t;let{player:n}=t;for(let n of[e.play,e.bigPlay])n.addEventListener(`click`,()=>{t.togglePlay()});n.events.on(`statuschange`,()=>{this.reflect(n.isPaused)}),this.reflect(n.isPaused)}reflect(e){for(let t of[this.parts.play,this.parts.bigPlay])this.host.wording.label(t,e?`play`:`pause`);this.parts.play.replaceChildren(QI(e?`play`:`pause`))}};function JL(e,t){e.resetView.addEventListener(`click`,()=>{t.player.resetView()}),e.fullscreen.addEventListener(`click`,()=>{t.toggleFullscreen()})}function YL(e,t){let n=xL(e);new qL(n,t),JL(n,t),new WL(n,t),new KL(n,t.player),new IL(e,n,{player:t.player,wording:t.wording})}var XL=`data-label`,ZL=`data-text`,QL=`data-choice-text`,$L=`data-error`,eR={label:`[data-label]`,text:`[data-text]`,choiceText:`[data-choice-text]`,choice:`[data-choice]`,error:`[data-error]`},tR=class{words=oL;get current(){return this.words}replace(e){this.words=sL(e)}label(e,t){e.setAttribute(XL,t),e.setAttribute(`aria-label`,this.words.labels[t])}showError(e,t){e.setAttribute($L,t),e.textContent=this.words.errors[t]}write(e){for(let t of e.querySelectorAll(eR.label))this.writeLabel(t);for(let t of e.querySelectorAll(eR.text))this.writeText(t);for(let t of e.querySelectorAll(eR.choiceText))this.writeChoiceText(t);for(let t of e.querySelectorAll(eR.error))this.writeError(t)}writeLabel(e){let t=e.getAttribute(XL);cL(t)&&e.setAttribute(`aria-label`,this.words.labels[t])}writeText(e){let t=e.getAttribute(ZL);cL(t)&&(e.textContent=this.words.labels[t])}writeChoiceText(e){let t=e.getAttribute(QL),n=e.closest(eR.choice)?.dataset.choice;n!==void 0&&lL(t)&&(e.textContent=this.words[t][n]??``)}writeError(e){let t=e.getAttribute($L);ne(t)&&(e.textContent=this.words.errors[t])}},nR=[...Object.values(GF),JF.Poster],rR=[oI,sI],iR=[cI],aR=[JF.Autoplay,JF.Controls],oR=Object.values(GF),sR=Object.values(KF),cR=[...[...nR,...rR.map(({name:e})=>e),...aR].map(e=>kd(e)),...iR.map(({property:e})=>e),...AI,`currentTime`,`messages`],lR=Object.values(qF),uR=class extends jL{static observedAttributes=YF;earlyProperties;player;loads;wording=new tR;fullscreen=new gI(this);idle;posterImage;constructor(){super(),this.earlyProperties=OI(this,cR),Sd(this,nR),wd(this,rR),Td(this,iR),Cd(this,aR);let e=this.attachShadow({mode:`open`});OL(e),this.wording.write(e);let t=yL(e,`canvas`,HTMLCanvasElement),n=yL(e,`audio`,HTMLAudioElement);this.posterImage=yL(e,`.poster`,HTMLImageElement),this.player=HF({canvas:t,audio:n}),this.loads=new pI(this,this.player),jI(this,this.player);let r=this.controlsHost();YL(e,r),new qd(t,this.player,this.onPictureTap),zd(this,r),this.idle=new xI(this,()=>this.player.status===`playing`);let{idle:i,wording:a}=this;CL(this.player,{element:this,shadow:e,idle:i,wording:a})}get status(){return this.player.status}get metadata(){return this.player.metadata}get currentTime(){return this.player.currentTime}set currentTime(e){this.seek(e)}get duration(){return this.player.duration}get paused(){return this.player.isPaused}get view(){return this.player.view}get messages(){return this.wording.current}set messages(e){let t=this.wording.current.labels.player;this.wording.replace(e),this.shadowRoot&&this.wording.write(this.shadowRoot),DI(this,t,this.wording.current.labels.player)}connectedCallback(){EI(this,this.wording.current.labels.player),kI(this,this.earlyProperties,this.warn),this.dataset.status=this.player.status,this.idle.start(),this.loads.connected()}disconnectedCallback(){this.idle.stop(),this.loads.disconnected()}attributeChangedCallback(e,t,n){if(oR.includes(e))this.loads.sourceChanged();else if(sR.includes(e))this.loads.requestChanged();else if(lR.includes(e)){this.player.setView(tI(this.player.view,e,n));let t=aI(e,n);t!==void 0&&this.warn(t)}else TI({player:this.player,posterImage:this.posterImage,warn:this.warn},e,n)}async play(){await this.loads.settled(),await this.player.play()}pause(){this.player.pause()}stop(){this.player.stop()}seek(e){Ad(e,`time`),this.loads.seek(e)}scrub(e){return this.player.scrub(e)}lookAt(e,t){this.player.lookAt(e,t)}resetView(){this.player.resetView()}zoom(e,t){this.player.zoom(e,t)}setStabilization(e){this.player.setStabilization(PI(e))}setViewMode(e){this.player.setViewMode(FI(e))}setQuality(e){this.player.setQuality(II(e))}toggleFullscreen(){return this.fullscreen.toggle()}load(){return this.loads.load()}loadFiles(e){this.loads.loadFiles(e)}controlsHost(){return{player:this.player,wording:this.wording,togglePlay:this.togglePlayback,toggleFullscreen:()=>{this.toggleFullscreen()},warn:this.warn,isFullscreen:()=>this.fullscreen.isActive,exitFullscreen:()=>{this.fullscreen.exit()}}}onPictureTap=e=>{let t=this.controls&&this.idle.wasIdleAtLastPress;e!==`mouse`&&t||this.togglePlayback()};togglePlayback=()=>{Zd(this.player)};warn=e=>{this.dispatchEvent(new CustomEvent(`warning`,{detail:e,composed:!0}))}},dR=`gyro-view`;function fR(){if(typeof customElements>`u`)return;let e=customElements.get(dR);e===void 0?customElements.define(dR,uR):e!==uR&&pR()}var pR=et(()=>{console.warn(`<${dR}> was defined by another copy of gyroview; that copy's element is used`)});fR();export{k as GYRO_VIEW_ERROR_CATEGORIES,ee as GYRO_VIEW_ERROR_CODES,dR as GYRO_VIEW_TAG,uR as GyroViewElement,A as GyroViewError,ws as PICTURE_QUALITIES,VF as Player,Xo as STABILIZATION_MODES,Os as VIEW_MODES,Xd as attachKeyboard,Yd as attachViewGestures,HF as createBrowserPlayer,fR as defineGyroView,ae as hasErrorCode,UF as inspectRecording,ne as isGyroViewErrorCode};
|
|
5288
|
+
`}var zP=$e(()=>nP(RP())),BP=$e(()=>[LP,AP].map(e=>HP(e)));function VP(e){e.adoptedStyleSheets=BP(),e.append(zP().cloneNode(!0))}function HP(e){let t=new CSSStyleSheet;return t.replaceSync(e),t}var UP=typeof HTMLElement==`function`?HTMLElement:Object,WP=class extends UP{addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}},GP=/* @__PURE__ */ new Map([[`ArrowDown`,(e,t)=>(e+1)%t],[`ArrowUp`,(e,t)=>(e-1+t)%t],[`Home`,()=>0],[`End`,(e,t)=>t-1]]),KP={capture:!0},qP=class{parts;host;items;constructor(e,t,n){this.parts=t,this.host=n,this.items=[...t.popup.querySelectorAll(`:scope [role="menuitemradio"]`)];for(let e of this.items)e.addEventListener(`click`,()=>{this.closeToButton();let{choice:t}=e.dataset;t!==void 0&&n.choose(t)});t.close.addEventListener(`click`,()=>{this.closeToButton()}),this.bindButton(),this.bindDismissal(e),this.bindKeys(e)}get isOpen(){return!this.parts.popup.hidden}markChosen(e){for(let t of this.items)t.setAttribute(`aria-checked`,String(t.dataset.choice===e));let t=this.items.find(t=>t.dataset.choice===e)?.querySelector(`:scope .choice-icon > svg`);this.parts.icon.replaceChildren(...t?[t.cloneNode(!0)]:[]),this.parts.button.dataset.choice=e,this.host.wording.write(this.parts.button)}setAvailable(e){this.parts.button.hidden=!e,e||this.setOpen(!1)}bindButton(){this.parts.button.addEventListener(`click`,()=>{this.setOpen(!this.isOpen),this.isOpen&&this.focusItem(this.items.findIndex(e=>JP(e)))})}bindDismissal(e){let{button:t,popup:n}=this.parts;e.addEventListener(`pointerdown`,e=>{this.isOpen&&(e.composedPath().some(e=>e===n||e===t)||(this.setOpen(!1),e.stopPropagation()))},KP),e.addEventListener(`focusout`,e=>{let r=e instanceof FocusEvent?e.relatedTarget:null;r!==t&&r instanceof Node&&!n.contains(r)&&this.setOpen(!1)})}bindKeys(e){e.addEventListener(`keydown`,e=>{this.isOpen&&e instanceof KeyboardEvent&&this.onKey(e)})}onKey(e){let t=e.composedPath();if(e.key===`Escape`){this.closeToButton(),e.stopPropagation();return}t.includes(this.parts.popup)&&(e.stopPropagation(),e.key===`Tab`?this.setOpen(!1):this.moveFocus(e,t))}moveFocus(e,t){let n=GP.get(e.key);if(!n)return;e.preventDefault();let r=this.items.findIndex(e=>t.includes(e));this.focusItem(n(r,this.items.length))}focusItem(e){(this.items[e]??this.items[0])?.focus()}closeToButton(){this.setOpen(!1),this.parts.button.focus()}setOpen(e){this.parts.popup.hidden=!e,this.parts.button.setAttribute(`aria-expanded`,String(e))}};function JP(e){return e.getAttribute(`aria-checked`)===`true`}var YP=class{viewMode;stabilization;player;constructor(e,t,n){let{player:r,wording:i}=n;this.player=r,this.viewMode=new qP(e,t.viewMode,{wording:i,choose:e=>{let t=xd(e);t&&r.setViewMode(t)}}),this.stabilization=new qP(e,t.stabilization,{wording:i,choose:e=>{let t=bd(e);t&&r.setStabilization(t)}}),this.followPlayer()}followPlayer(){let{player:e}=this;e.events.on(`viewmodechange`,e=>{this.viewMode.markChosen(e),this.offerStabilization()}),e.events.on(`stabilizationchange`,e=>{this.stabilization.markChosen(e)}),e.events.on(`statuschange`,()=>{this.offerStabilization()}),this.viewMode.markChosen(e.viewMode),this.stabilization.markChosen(e.stabilization),this.offerStabilization()}offerStabilization(){let e=this.player.metadata?.hasGyro===!0,t=kc(this.player.viewMode).isStabilized;this.stabilization.setAvailable(e&&t)}},XP=60,ZP=60;function QP(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%XP,r=Math.floor(t/XP)%ZP,i=Math.floor(t/3600);return i>0?`${i}:${$P(r)}:${$P(n)}`:`${r}:${$P(n)}`}function $P(e){return String(e).padStart(2,`0`)}function eF(e){let t=Number(e.min),n=Number(e.max)-t,r=n>0?(Number(e.value)-t)/n:0;e.style.setProperty(`--fill`,String(yr(r,0,1)))}var tF=/* @__PURE__ */ new Map([[`ArrowLeft`,-1],[`ArrowDown`,-1],[`ArrowRight`,1],[`ArrowUp`,1]]),nF=[`pointerup`,`pointercancel`,`change`],rF=class{parts;host;isScrubbing=!1;scrubTarget;scrubbing;constructor(e,t){this.parts=e,this.host=t,this.bindInput();let{events:n}=this.host.player;n.on(`statuschange`,()=>{this.showRecording()}),n.on(`timeupdate`,e=>{this.follow(e)}),this.showRecording()}bindInput(){let{seek:e}=this.parts;e.addEventListener(`input`,()=>{this.isScrubbing=!0;let t=Number(e.value);this.showTime(t),this.scrubTo(t)});for(let t of nF)e.addEventListener(t,()=>{this.endScrub()});e.addEventListener(`keydown`,e=>{let t=tF.get(e.key);if(t===void 0)return;e.preventDefault();let{player:n}=this.host;n.seek(n.currentTime+t*5)})}showRecording(){let{duration:e,currentTime:t}=this.host.player;this.parts.seek.max=String(e),this.follow(t)}follow(e){this.isScrubbing||(this.parts.seek.value=String(e),this.showTime(e))}scrubTo(e){this.scrubTarget=e,this.scrubbing??=this.drainScrubs()}async drainScrubs(){try{for(;this.scrubTarget!==void 0;){let e=this.scrubTarget;this.scrubTarget=void 0,await this.host.player.scrub(e)}}catch(e){this.host.warn({code:`playback-failed`,message:`the seek bar could not show that moment: ${ie(e)}`})}finally{this.scrubbing=void 0}}endScrub(){this.isScrubbing&&(this.isScrubbing=!1,this.scrubTarget=void 0,this.host.player.seek(Number(this.parts.seek.value)))}showTime(e){let[t,n]=[QP(e),QP(this.host.player.duration)];this.parts.elapsed.textContent=t,this.parts.total.textContent=`/ ${n}`;let{position:r}=this.host.wording.current.labels,i=r.replaceAll(`{time}`,()=>t).replaceAll(`{duration}`,()=>n);this.parts.seek.setAttribute(`aria-valuetext`,i),eF(this.parts.seek)}},iF=100,aF=class{parts;player;constructor(e,t){this.parts=e,this.player=t,e.volume.hidden=!t.canSetVolume,e.mute.addEventListener(`click`,()=>{t.setMuted(!t.isMuted)}),e.volume.addEventListener(`input`,()=>{t.setVolume(Number(e.volume.value)),t.isMuted&&t.setMuted(!1)}),t.events.on(`volumechange`,()=>{this.reflect()}),this.reflect()}reflect(){let{isMuted:e,volume:t}=this.player,n=e?0:t;this.parts.mute.replaceChildren(dP(e?`muted`:`sound`)),this.parts.mute.setAttribute(`aria-pressed`,String(e)),this.parts.volume.value=String(n),this.parts.volume.setAttribute(`aria-valuetext`,`${Math.round(n*iF)}%`),eF(this.parts.volume)}},oF=class{parts;host;constructor(e,t){this.parts=e,this.host=t;let{player:n}=t;for(let n of[e.play,e.bigPlay])n.addEventListener(`click`,()=>{t.togglePlay()});n.events.on(`statuschange`,()=>{this.reflect(n.isPaused)}),this.reflect(n.isPaused)}reflect(e){for(let t of[this.parts.play,this.parts.bigPlay])this.host.wording.label(t,e?`play`:`pause`);this.parts.play.replaceChildren(dP(e?`play`:`pause`))}};function sF(e,t){e.resetView.addEventListener(`click`,()=>{t.player.resetView()}),e.fullscreen.addEventListener(`click`,()=>{t.toggleFullscreen()})}function cF(e,t){let n=PP(e);new oF(n,t),sF(n,t),new rF(n,t),new aF(n,t.player),new YP(e,n,{player:t.player,wording:t.wording})}var lF=`data-label`,uF=`data-text`,dF=`data-choice-text`,fF=`data-error`,pF={label:`[data-label]`,text:`[data-text]`,choiceText:`[data-choice-text]`,choice:`[data-choice]`,error:`[data-error]`},mF=class{words=yP;get current(){return this.words}replace(e){this.words=bP(e)}label(e,t){e.setAttribute(lF,t),e.setAttribute(`aria-label`,this.words.labels[t])}showError(e,t){e.setAttribute(fF,t),e.textContent=this.words.errors[t]}write(e){for(let t of e.querySelectorAll(pF.label))this.writeLabel(t);for(let t of e.querySelectorAll(pF.text))this.writeText(t);for(let t of e.querySelectorAll(pF.choiceText))this.writeChoiceText(t);for(let t of e.querySelectorAll(pF.error))this.writeError(t)}writeLabel(e){let t=e.getAttribute(lF);xP(t)&&e.setAttribute(`aria-label`,this.words.labels[t])}writeText(e){let t=e.getAttribute(uF);xP(t)&&(e.textContent=this.words.labels[t])}writeChoiceText(e){let t=e.getAttribute(dF),n=e.closest(pF.choice)?.dataset.choice;n!==void 0&&SP(t)&&(e.textContent=this.words[t][n]??``)}writeError(e){let t=e.getAttribute(fF);te(t)&&(e.textContent=this.words.errors[t])}},hF=[...Object.values(iN),sN.Poster],gF=[yN,bN],_F=[xN],vF=[sN.Autoplay,sN.Controls],yF=Object.values(iN),bF=Object.values(aN),xF=[...[...hF,...gF.map(({name:e})=>e),...vF].map(e=>Ad(e)),..._F.map(({property:e})=>e),...UN,`currentTime`,`messages`],SF=Object.values(oN),CF=class extends WP{static observedAttributes=cN;earlyProperties;player;loads;wording=new mF;fullscreen=new kN(this);idle;posterImage;constructor(){super(),this.earlyProperties=VN(this,xF),Cd(this,hF),Td(this,gF),Ed(this,_F),wd(this,vF);let e=this.attachShadow({mode:`open`});VP(e),this.wording.write(e);let t=MP(e,`canvas`,HTMLCanvasElement),n=MP(e,`audio`,HTMLAudioElement);this.posterImage=MP(e,`.poster`,HTMLImageElement),this.player=tN({canvas:t,audio:n}),this.loads=new EN(this,this.player),WN(this,this.player);let r=this.controlsHost();cF(e,r),new Jd(t,this.player,this.onPictureTap),Bd(this,r),this.idle=new PN(this,()=>this.player.status===`playing`);let{idle:i,wording:a}=this;IP(this.player,{element:this,shadow:e,idle:i,wording:a})}get status(){return this.player.status}get metadata(){return this.player.metadata}get currentTime(){return this.player.currentTime}set currentTime(e){this.seek(e)}get duration(){return this.player.duration}get paused(){return this.player.isPaused}get view(){return this.player.view}get messages(){return this.wording.current}set messages(e){let t=this.wording.current.labels.player;this.wording.replace(e),this.shadowRoot&&this.wording.write(this.shadowRoot),BN(this,t,this.wording.current.labels.player)}connectedCallback(){zN(this,this.wording.current.labels.player),HN(this,this.earlyProperties,this.warn),this.dataset.status=this.player.status,this.idle.start(),this.loads.connected()}disconnectedCallback(){this.idle.stop(),this.loads.disconnected()}attributeChangedCallback(e,t,n){if(yF.includes(e))this.loads.sourceChanged();else if(bF.includes(e))this.loads.requestChanged();else if(SF.includes(e)){this.player.setView(mN(this.player.view,e,n));let t=vN(e,n);t!==void 0&&this.warn(t)}else RN({player:this.player,posterImage:this.posterImage,warn:this.warn},e,n)}async play(){await this.loads.settled(),await this.player.play()}pause(){this.player.pause()}stop(){this.player.stop()}seek(e){jd(e,`time`),this.loads.seek(e)}scrub(e){return this.player.scrub(e)}lookAt(e,t){this.player.lookAt(e,t)}resetView(){this.player.resetView()}zoom(e,t){this.player.zoom(e,t)}setStabilization(e){this.player.setStabilization(qN(e))}setViewMode(e){this.player.setViewMode(JN(e))}setQuality(e){this.player.setQuality(YN(e))}toggleFullscreen(){return this.fullscreen.toggle()}load(){return this.loads.load()}loadFiles(e){this.loads.loadFiles(e)}controlsHost(){return{player:this.player,wording:this.wording,togglePlay:this.togglePlayback,toggleFullscreen:()=>{this.toggleFullscreen()},warn:this.warn,isFullscreen:()=>this.fullscreen.isActive,exitFullscreen:()=>{this.fullscreen.exit()}}}onPictureTap=e=>{let t=this.controls&&this.idle.wasIdleAtLastPress;e!==`mouse`&&t||this.togglePlayback()};togglePlayback=()=>{Qd(this.player)};warn=e=>{this.dispatchEvent(new CustomEvent(`warning`,{detail:e,composed:!0}))}},wF=`gyro-view`;function TF(){if(typeof customElements>`u`)return;let e=customElements.get(wF);e===void 0?customElements.define(wF,CF):e!==CF&&EF()}var EF=$e(()=>{console.warn(`<${wF}> was defined by another copy of gyroview; that copy's element is used`)});TF();export{A as GYRO_VIEW_ERROR_CATEGORIES,k as GYRO_VIEW_ERROR_CODES,wF as GYRO_VIEW_TAG,CF as GyroViewElement,j as GyroViewError,ws as PICTURE_QUALITIES,eN as Player,Xo as STABILIZATION_MODES,Os as VIEW_MODES,Zd as attachKeyboard,Xd as attachViewGestures,tN as createBrowserPlayer,TF as defineGyroView,M as hasErrorCode,nN as inspectRecording,te as isGyroViewErrorCode};
|