@shotstack/shotstack-studio 2.19.0 → 2.19.1
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/LICENSE +4 -0
- package/dist/shotstack-studio.es.js +33 -21
- package/dist/shotstack-studio.umd.js +4 -4
- package/package.json +1 -1
- package/readme.md +24 -0
package/LICENSE
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
<https://polyformproject.org/licenses/shield/1.0.0>
|
|
4
4
|
|
|
5
|
+
Required Notice: Copyright Shotstack Pty Ltd (https://shotstack.io)
|
|
6
|
+
|
|
7
|
+
Licensor Line of Business: Shotstack cloud video editing platform, including its APIs, Studio, the Studio SDK and the template library (https://shotstack.io)
|
|
8
|
+
|
|
5
9
|
## Acceptance
|
|
6
10
|
|
|
7
11
|
In order to get any license under these terms, you must agree
|
|
@@ -11,7 +11,7 @@ import "pixi.js/text-html";
|
|
|
11
11
|
import "pixi.js/sprite-tiling";
|
|
12
12
|
import "pixi.js/filters";
|
|
13
13
|
import "pixi.js/mesh";
|
|
14
|
-
const vI = "2.
|
|
14
|
+
const vI = "2.19.0", wI = {
|
|
15
15
|
version: vI
|
|
16
16
|
};
|
|
17
17
|
function Hb(e, t, i) {
|
|
@@ -51170,9 +51170,9 @@ class pb extends fT {
|
|
|
51170
51170
|
case "esds":
|
|
51171
51171
|
{
|
|
51172
51172
|
const a = this.currentTrack;
|
|
51173
|
-
if (!a)
|
|
51173
|
+
if (!a || a.info?.type !== "audio")
|
|
51174
51174
|
break;
|
|
51175
|
-
|
|
51175
|
+
t.skip(4);
|
|
51176
51176
|
const o = te(t);
|
|
51177
51177
|
M(o === 3), bp(t), t.skip(2);
|
|
51178
51178
|
const l = te(t), u = (l & 128) !== 0, c = (l & 64) !== 0, d = (l & 32) !== 0;
|
|
@@ -57039,11 +57039,11 @@ class VQ {
|
|
|
57039
57039
|
async next() {
|
|
57040
57040
|
for (; ; ) {
|
|
57041
57041
|
if (C.input._disposed)
|
|
57042
|
-
throw x(), new Gi();
|
|
57042
|
+
throw h = !0, f = !0, x(), new Gi();
|
|
57043
57043
|
if (h)
|
|
57044
57044
|
return { value: void 0, done: !0 };
|
|
57045
57045
|
if (b)
|
|
57046
|
-
throw x(), g;
|
|
57046
|
+
throw h = !0, f = !0, x(), g;
|
|
57047
57047
|
if (n.length > 0) {
|
|
57048
57048
|
const _ = n.shift();
|
|
57049
57049
|
return c(), { value: _, done: !1 };
|
|
@@ -57138,11 +57138,11 @@ class VQ {
|
|
|
57138
57138
|
async next() {
|
|
57139
57139
|
for (; ; ) {
|
|
57140
57140
|
if (w.input._disposed)
|
|
57141
|
-
throw C(), new Gi();
|
|
57141
|
+
throw d = !0, C(), new Gi();
|
|
57142
57142
|
if (d)
|
|
57143
57143
|
return { value: void 0, done: !0 };
|
|
57144
57144
|
if (p)
|
|
57145
|
-
throw C(), h;
|
|
57145
|
+
throw d = !0, C(), h;
|
|
57146
57146
|
if (s.length > 0) {
|
|
57147
57147
|
const x = s.shift();
|
|
57148
57148
|
return M(x !== void 0), u(), { value: x, done: !1 };
|
|
@@ -67294,29 +67294,39 @@ class ln extends ga {
|
|
|
67294
67294
|
this.state.tab === "in" ? this.state.inDirection = t : this.state.outDirection = t;
|
|
67295
67295
|
}
|
|
67296
67296
|
stepSpeed(t) {
|
|
67297
|
-
const i =
|
|
67298
|
-
|
|
67299
|
-
|
|
67300
|
-
const
|
|
67301
|
-
|
|
67297
|
+
const i = this.state.tab === "in" ? this.state.inEffect : this.state.outEffect;
|
|
67298
|
+
if (!this.supportsSpeedVariants(i))
|
|
67299
|
+
return;
|
|
67300
|
+
const r = ln.SPEEDS, n = this.state.tab === "in" ? this.state.inSpeed : this.state.outSpeed;
|
|
67301
|
+
let s = r.indexOf(n);
|
|
67302
|
+
s === -1 && (s = r.findIndex((l) => l >= n), s === -1 && (s = r.length - 1));
|
|
67303
|
+
const a = Math.max(0, Math.min(r.length - 1, s + t)), o = r[a];
|
|
67304
|
+
this.state.tab === "in" ? this.state.inSpeed = o : this.state.outSpeed = o, this.updateUI(), this.emit(this.state);
|
|
67302
67305
|
}
|
|
67303
67306
|
needsDirection(t) {
|
|
67304
67307
|
return ["slide", "wipe", "carousel"].includes(t);
|
|
67305
67308
|
}
|
|
67309
|
+
/**
|
|
67310
|
+
* Whether the Shotstack transition API exposes Slow/Fast variants for this effect.
|
|
67311
|
+
* `zoom` is fixed-speed (only `zoom` is valid — not `zoomSlow`/`zoomFast`).
|
|
67312
|
+
*/
|
|
67313
|
+
supportsSpeedVariants(t) {
|
|
67314
|
+
return !!t && t !== "zoom";
|
|
67315
|
+
}
|
|
67306
67316
|
updateUI() {
|
|
67307
67317
|
const { tab: t } = this.state, i = t === "in" ? this.state.inEffect : this.state.outEffect, r = t === "in" ? this.state.inDirection : this.state.outDirection, n = t === "in" ? this.state.inSpeed : this.state.outSpeed;
|
|
67308
|
-
this.tabButtons?.forEach((
|
|
67309
|
-
|
|
67310
|
-
}), this.effectButtons?.forEach((
|
|
67311
|
-
|
|
67318
|
+
this.tabButtons?.forEach((l) => {
|
|
67319
|
+
l.classList.toggle("active", l.dataset.tab === t);
|
|
67320
|
+
}), this.effectButtons?.forEach((l) => {
|
|
67321
|
+
l.classList.toggle("active", l.dataset.effect === i);
|
|
67312
67322
|
});
|
|
67313
67323
|
const s = this.needsDirection(i);
|
|
67314
|
-
this.directionRow?.classList.toggle("visible", s), this.directionButtons?.forEach((
|
|
67315
|
-
const
|
|
67316
|
-
|
|
67324
|
+
this.directionRow?.classList.toggle("visible", s), this.directionButtons?.forEach((l) => {
|
|
67325
|
+
const u = l.dataset.dir ?? "";
|
|
67326
|
+
l.classList.toggle("hidden", i === "wipe" && (u === "Up" || u === "Down")), l.classList.toggle("active", u === r);
|
|
67317
67327
|
}), this.speedLabel && (this.speedLabel.textContent = `${n.toFixed(2)}s`);
|
|
67318
|
-
const a = ln.SPEEDS.indexOf(n);
|
|
67319
|
-
this.speedDecreaseBtn && (this.speedDecreaseBtn.disabled = a <= 0), this.speedIncreaseBtn && (this.speedIncreaseBtn.disabled = a >= ln.SPEEDS.length - 1);
|
|
67328
|
+
const a = this.supportsSpeedVariants(i), o = ln.SPEEDS.indexOf(n);
|
|
67329
|
+
this.speedDecreaseBtn && (this.speedDecreaseBtn.disabled = !a || o <= 0), this.speedIncreaseBtn && (this.speedIncreaseBtn.disabled = !a || o >= ln.SPEEDS.length - 1);
|
|
67320
67330
|
}
|
|
67321
67331
|
// ─── Transition Value Parsing/Building ───────────────────────────────────
|
|
67322
67332
|
parseTransitionValue(t) {
|
|
@@ -67338,6 +67348,8 @@ class ln extends ga {
|
|
|
67338
67348
|
return this.needsDirection(t) ? t + i + n : t + n;
|
|
67339
67349
|
}
|
|
67340
67350
|
speedToSuffix(t, i) {
|
|
67351
|
+
if (!this.supportsSpeedVariants(i))
|
|
67352
|
+
return "";
|
|
67341
67353
|
if (i === "slide" || i === "carousel") {
|
|
67342
67354
|
if (t === 0.5) return "";
|
|
67343
67355
|
if (t === 1) return "Slow";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(Ai,gn){typeof exports=="object"&&typeof module<"u"?gn(exports,require("pixi.js"),require("howler"),require("pixi-filters"),require("opentype.js"),require("pixi.js/app"),require("pixi.js/events"),require("pixi.js/graphics"),require("pixi.js/text"),require("pixi.js/text-html"),require("pixi.js/sprite-tiling"),require("pixi.js/filters"),require("pixi.js/mesh")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","pixi-filters","opentype.js","pixi.js/app","pixi.js/events","pixi.js/graphics","pixi.js/text","pixi.js/text-html","pixi.js/sprite-tiling","pixi.js/filters","pixi.js/mesh"],gn):(Ai=typeof globalThis<"u"?globalThis:Ai||self,gn(Ai.ShotstackStudio={},Ai.PIXI,Ai.Howler,Ai.PIXI,Ai.opentype))})(this,function(Ai,gn,gI,yI,bI){"use strict";var Yn=typeof document<"u"?document.currentScript:null;function Vc(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const i in e)if(i!=="default"){const r=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:()=>e[i]})}}return t.default=e,Object.freeze(t)}const J=Vc(gn),Fb=Vc(gI),Sl=Vc(yI),h0=Vc(bI),vI={version:"2.18.0"};function Bb(e,t,i){const r=1-e;return 3*r*r*e*t+3*r*e*e*i+e*e*e}class wI{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={smooth:[[.5,0],[.5,1]],ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(t,i,r,n){if(r<=0)return t;if(r>=1)return i;const s=this.curves[n??""]??this.curves.ease,[[a,o],[l,u]]=s,c=this.solveForT(r,a,l),d=Bb(c,o,u);return t+(i-t)*d}solveForT(t,i,r){let n=0,s=1,a=t;for(let o=0;o<24;o+=1){const l=Bb(a,i,r)-t;if(Math.abs(l)<1e-5)break;l<0?n=a:s=a,a=(n+s)/2}return a}}const xi=1e-6;class As{property;length;cubicBuilder;cachedIndex=0;constructor(t,i,r=0){this.property=this.createKeyframes(t,i,r),this.length=i,this.cubicBuilder=new wI}getValue(t){const i=this.findKeyframe(t);if(!i){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const r=(t-i.start)/i.length;switch(i.interpolation){case"bezier":return this.cubicBuilder.getValue(i.from,i.to,r,i.easing);case"constant":return i.from;case"linear":default:return i.from+(i.to-i.from)*r}}findKeyframe(t){const i=this.property;if(i.length===0)return;const r=i[this.cachedIndex];if(r){const o=r.start+r.length;if(Number.isFinite(o)&&t>=r.start&&t<o)return r}const n=this.cachedIndex+1;if(n<i.length){const o=i[n],l=o.start+o.length;if(Number.isFinite(l)&&t>=o.start&&t<l)return this.cachedIndex=n,o}const s=this.cachedIndex-1;if(s>=0){const o=i[s],l=o.start+o.length;if(Number.isFinite(l)&&t>=o.start&&t<l)return this.cachedIndex=s,o}const a=this.binarySearchKeyframe(t);if(a!==-1)return this.cachedIndex=a,i[a]}binarySearchKeyframe(t){const i=this.property;let r=0,n=i.length-1;for(;r<=n;){const s=Math.floor((r+n)/2),a=i[s],o=a.start+a.length;if(!Number.isFinite(o)||t>=o)r=s+1;else if(t<a.start)n=s-1;else return s}return-1}createKeyframes(t,i,r=0){if(typeof t=="number")return[{start:0,length:i,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const n=this.createNormalizedKeyframes(t);return this.normaliseAdjacentBoundaries(n),this.validateKeyframes(n),this.insertFillerKeyframes(n,i,r)}createNormalizedKeyframes(t){return t.filter(i=>typeof i.start=="number"&&typeof i.length=="number").toSorted((i,r)=>i.start-r.start).map(i=>({start:i.start,length:i.length,from:typeof i.from=="number"?i.from:0,to:typeof i.to=="number"?i.to:0,interpolation:i.interpolation,easing:i.easing}))}normaliseAdjacentBoundaries(t){for(let i=0;i<t.length-1;i+=1){const r=t[i],n=t[i+1],s=r.start+r.length-n.start,a=n.start-r.start;Math.abs(s)<=xi&&a>0&&(r.length=a)}}validateKeyframes(t){for(let i=0;i<t.length;i+=1){const r=t[i],n=t[i+1];if(!n)break;if(r.start+r.length>n.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(t,i,r=0){const n=[];for(let s=0;s<t.length;s+=1){const a=t[s],o=t[s+1];if(s===0&&a.start>0){const c={start:0,length:a.start,from:r,to:a.from};n.push(c)}if(n.push(a),!o){if(i-(a.start+a.length)>0){const d=a.start+a.length,f={start:d,length:i-d,from:a.to,to:a.to};n.push(f)}break}if(o.start-(a.start+a.length)>0){const c=a.start+a.length,d=o.start-c,f={start:c,length:d,from:a.to,to:o.from};n.push(f)}}return n}}class wa{baseValue;mode;layers=[];length;clampRange;constructor(t,i,r,n){this.baseValue=t,this.length=i,this.mode=r,this.clampRange=n}addLayer(t){if(t.length===0)return;const i=this.mode==="additive"?0:1;this.layers.push(new As(t,this.length,i))}getValue(t){if(this.layers.length===0)return this.baseValue;if(this.mode==="additive"){let r=this.baseValue;for(const n of this.layers)r+=n.getValue(t);return r}let i=this.baseValue;for(const r of this.layers)i*=r.getValue(t);return this.clampRange&&(i=Math.max(this.clampRange.min,Math.min(this.clampRange.max,i))),i}}class xI{clipConfiguration;effectPreset;constructor(t){this.clipConfiguration=t;const[i,r]=(t.effect??"").split(/(Slow|Fast)/);this.effectPreset={name:i,speed:r}}buildRelative(t,i){const r=[],n=[],s=[],a=[],o=[],{effect:l,length:u}=this.clipConfiguration;if(!l)return{offsetXKeyframes:r,offsetYKeyframes:n,opacityKeyframes:s,scaleKeyframes:a,rotationKeyframes:o};const c=0,d=this.getPresetName();switch(d){case"zoomIn":{const f=this.getZoomSpeed();a.push({from:1,to:f,start:c,length:u,interpolation:"linear"});break}case"zoomOut":{const f=this.getZoomSpeed();a.push({from:f,to:1,start:c,length:u,interpolation:"linear"});break}case"slideLeft":case"slideRight":case"slideUp":case"slideDown":{const f=d==="slideLeft"||d==="slideRight",h=d==="slideLeft"||d==="slideUp",p=this.getFittedSize(t,i),g=f?t.width:t.height,b=f?p.width:p.height;let w=this.getSlideStart();const C=g+g*w*2;if(b<C){const k=C/b;a.push({from:k,to:k,start:c,length:u,interpolation:"linear"})}else w=(b-g)/2/g;const[x,_]=h?[w,-w]:[-w,w];(f?r:n).push({from:x,to:_,start:c,length:u});break}}return{offsetXKeyframes:r,offsetYKeyframes:n,opacityKeyframes:s,scaleKeyframes:a,rotationKeyframes:o}}getPresetName(){return this.effectPreset.name}getZoomSpeed(){const{name:t,speed:i}=this.effectPreset;if(t.startsWith("zoom"))switch(i){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const{name:t,speed:i}=this.effectPreset;if(t.startsWith("slide"))switch(i){case"Slow":return .03;case"Fast":return .2;default:return .12}return 0}getFittedSize(t,i){switch(this.clipConfiguration.fit??"crop"){case"cover":case"crop":{const n=Math.max(t.width/i.width,t.height/i.height);return{width:i.width*n,height:i.height*n}}case"contain":{const n=Math.min(t.width/i.width,t.height/i.height);return{width:i.width*n,height:i.height*n}}case"none":default:return i}}}class CI{clipConfiguration;inPreset;outPreset;constructor(t){this.clipConfiguration=t,this.inPreset=this.parseTransition(t.transition?.in),this.outPreset=this.parseTransition(t.transition?.out)}parseTransition(t){const[i,r]=(t??"").split(/(Slow|Fast|VeryFast)/);return{name:i,speed:r}}buildRelative(){return{in:this.buildTransitionKeyframes("in"),out:this.buildTransitionKeyframes("out")}}createEmptyKeyframeSet(){return{offsetXKeyframes:[],offsetYKeyframes:[],opacityKeyframes:[],scaleKeyframes:[],rotationKeyframes:[],maskXKeyframes:[],brightnessKeyframes:[],wipeFromRight:!1}}buildTransitionKeyframes(t){const i=this.createEmptyKeyframeSet();if(!(t==="in"?this.clipConfiguration.transition?.in:this.clipConfiguration.transition?.out))return i;const n=this.getPresetLength(t),s=t==="in"?0:this.clipConfiguration.length-n,a=this.getPresetName(t),o=t==="in";switch(a){case"fade":{const[l,u]=o?[0,1]:[1,0];i.opacityKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"bezier",easing:"easeInOut"});break}case"zoom":{const[l,u]=o?[10,1]:[1,10],[c,d]=o?[0,1]:[1,0],f=o?"easeIn":"easeOut";o?i.scaleKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"linear"}):i.scaleKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"bezier",easing:f}),i.opacityKeyframes.push({from:c,to:d,start:s,length:n,interpolation:"bezier",easing:f});break}case"slideLeft":case"slideRight":case"slideUp":case"slideDown":{const l=a==="slideLeft"||a==="slideRight",u=a==="slideLeft"||a==="slideUp",c=.025,[d,f]=o?[u?c:-c,0]:[0,u?-c:c],h=o?"linear":"bezier",[p,g]=o?[0,1]:[1,0];(l?i.offsetXKeyframes:i.offsetYKeyframes).push(o?{from:d,to:f,start:s,length:n,interpolation:h}:{from:d,to:f,start:s,length:n,interpolation:h,easing:"ease"}),i.opacityKeyframes.push({from:p,to:g,start:s,length:n,interpolation:"bezier",easing:"ease"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":{const l=a==="carouselLeft"||a==="carouselRight",u=a==="carouselLeft"||a==="carouselUp",c=l&&1||(o?1.05:1.1),[d,f]=o?[u?c:-c,0]:[0,u?-c:c];(l?i.offsetXKeyframes:i.offsetYKeyframes).push(o?{from:d,to:f,start:s,length:n,interpolation:"linear"}:{from:d,to:f,start:s,length:n,interpolation:"bezier",easing:"ease"});break}case"reveal":{const[l,u]=o?[0,1]:[1,0];i.maskXKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"bezier",easing:"ease"});break}case"wipeLeft":case"wipeRight":{const[l,u]=o?[1,-1]:[-1,1];i.brightnessKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"bezier",easing:"easeInOut"}),i.wipeFromRight=a==="wipeLeft"?o:!o;break}}return i}getPresetName(t){return t==="in"?this.inPreset.name:this.outPreset.name}getPresetLength(t){const{name:i,speed:r}=t==="in"?this.inPreset:this.outPreset,n=i.startsWith("carousel"),s=i.startsWith("slide");if(i==="zoom")return .4;switch(r){case"Slow":return 2;case"Fast":return n||s?.25:.5;case"VeryFast":return .25;default:return n||s?.5:1}}}const Nb="1.1764706",kI=`
|
|
1
|
+
(function(Ai,gn){typeof exports=="object"&&typeof module<"u"?gn(exports,require("pixi.js"),require("howler"),require("pixi-filters"),require("opentype.js"),require("pixi.js/app"),require("pixi.js/events"),require("pixi.js/graphics"),require("pixi.js/text"),require("pixi.js/text-html"),require("pixi.js/sprite-tiling"),require("pixi.js/filters"),require("pixi.js/mesh")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","pixi-filters","opentype.js","pixi.js/app","pixi.js/events","pixi.js/graphics","pixi.js/text","pixi.js/text-html","pixi.js/sprite-tiling","pixi.js/filters","pixi.js/mesh"],gn):(Ai=typeof globalThis<"u"?globalThis:Ai||self,gn(Ai.ShotstackStudio={},Ai.PIXI,Ai.Howler,Ai.PIXI,Ai.opentype))})(this,function(Ai,gn,gI,yI,bI){"use strict";var Yn=typeof document<"u"?document.currentScript:null;function Vc(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const i in e)if(i!=="default"){const r=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:()=>e[i]})}}return t.default=e,Object.freeze(t)}const J=Vc(gn),Fb=Vc(gI),Sl=Vc(yI),h0=Vc(bI),vI={version:"2.19.0"};function Bb(e,t,i){const r=1-e;return 3*r*r*e*t+3*r*e*e*i+e*e*e}class wI{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={smooth:[[.5,0],[.5,1]],ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(t,i,r,n){if(r<=0)return t;if(r>=1)return i;const s=this.curves[n??""]??this.curves.ease,[[a,o],[l,u]]=s,c=this.solveForT(r,a,l),d=Bb(c,o,u);return t+(i-t)*d}solveForT(t,i,r){let n=0,s=1,a=t;for(let o=0;o<24;o+=1){const l=Bb(a,i,r)-t;if(Math.abs(l)<1e-5)break;l<0?n=a:s=a,a=(n+s)/2}return a}}const xi=1e-6;class As{property;length;cubicBuilder;cachedIndex=0;constructor(t,i,r=0){this.property=this.createKeyframes(t,i,r),this.length=i,this.cubicBuilder=new wI}getValue(t){const i=this.findKeyframe(t);if(!i){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const r=(t-i.start)/i.length;switch(i.interpolation){case"bezier":return this.cubicBuilder.getValue(i.from,i.to,r,i.easing);case"constant":return i.from;case"linear":default:return i.from+(i.to-i.from)*r}}findKeyframe(t){const i=this.property;if(i.length===0)return;const r=i[this.cachedIndex];if(r){const o=r.start+r.length;if(Number.isFinite(o)&&t>=r.start&&t<o)return r}const n=this.cachedIndex+1;if(n<i.length){const o=i[n],l=o.start+o.length;if(Number.isFinite(l)&&t>=o.start&&t<l)return this.cachedIndex=n,o}const s=this.cachedIndex-1;if(s>=0){const o=i[s],l=o.start+o.length;if(Number.isFinite(l)&&t>=o.start&&t<l)return this.cachedIndex=s,o}const a=this.binarySearchKeyframe(t);if(a!==-1)return this.cachedIndex=a,i[a]}binarySearchKeyframe(t){const i=this.property;let r=0,n=i.length-1;for(;r<=n;){const s=Math.floor((r+n)/2),a=i[s],o=a.start+a.length;if(!Number.isFinite(o)||t>=o)r=s+1;else if(t<a.start)n=s-1;else return s}return-1}createKeyframes(t,i,r=0){if(typeof t=="number")return[{start:0,length:i,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const n=this.createNormalizedKeyframes(t);return this.normaliseAdjacentBoundaries(n),this.validateKeyframes(n),this.insertFillerKeyframes(n,i,r)}createNormalizedKeyframes(t){return t.filter(i=>typeof i.start=="number"&&typeof i.length=="number").toSorted((i,r)=>i.start-r.start).map(i=>({start:i.start,length:i.length,from:typeof i.from=="number"?i.from:0,to:typeof i.to=="number"?i.to:0,interpolation:i.interpolation,easing:i.easing}))}normaliseAdjacentBoundaries(t){for(let i=0;i<t.length-1;i+=1){const r=t[i],n=t[i+1],s=r.start+r.length-n.start,a=n.start-r.start;Math.abs(s)<=xi&&a>0&&(r.length=a)}}validateKeyframes(t){for(let i=0;i<t.length;i+=1){const r=t[i],n=t[i+1];if(!n)break;if(r.start+r.length>n.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(t,i,r=0){const n=[];for(let s=0;s<t.length;s+=1){const a=t[s],o=t[s+1];if(s===0&&a.start>0){const c={start:0,length:a.start,from:r,to:a.from};n.push(c)}if(n.push(a),!o){if(i-(a.start+a.length)>0){const d=a.start+a.length,f={start:d,length:i-d,from:a.to,to:a.to};n.push(f)}break}if(o.start-(a.start+a.length)>0){const c=a.start+a.length,d=o.start-c,f={start:c,length:d,from:a.to,to:o.from};n.push(f)}}return n}}class wa{baseValue;mode;layers=[];length;clampRange;constructor(t,i,r,n){this.baseValue=t,this.length=i,this.mode=r,this.clampRange=n}addLayer(t){if(t.length===0)return;const i=this.mode==="additive"?0:1;this.layers.push(new As(t,this.length,i))}getValue(t){if(this.layers.length===0)return this.baseValue;if(this.mode==="additive"){let r=this.baseValue;for(const n of this.layers)r+=n.getValue(t);return r}let i=this.baseValue;for(const r of this.layers)i*=r.getValue(t);return this.clampRange&&(i=Math.max(this.clampRange.min,Math.min(this.clampRange.max,i))),i}}class xI{clipConfiguration;effectPreset;constructor(t){this.clipConfiguration=t;const[i,r]=(t.effect??"").split(/(Slow|Fast)/);this.effectPreset={name:i,speed:r}}buildRelative(t,i){const r=[],n=[],s=[],a=[],o=[],{effect:l,length:u}=this.clipConfiguration;if(!l)return{offsetXKeyframes:r,offsetYKeyframes:n,opacityKeyframes:s,scaleKeyframes:a,rotationKeyframes:o};const c=0,d=this.getPresetName();switch(d){case"zoomIn":{const f=this.getZoomSpeed();a.push({from:1,to:f,start:c,length:u,interpolation:"linear"});break}case"zoomOut":{const f=this.getZoomSpeed();a.push({from:f,to:1,start:c,length:u,interpolation:"linear"});break}case"slideLeft":case"slideRight":case"slideUp":case"slideDown":{const f=d==="slideLeft"||d==="slideRight",h=d==="slideLeft"||d==="slideUp",p=this.getFittedSize(t,i),g=f?t.width:t.height,b=f?p.width:p.height;let w=this.getSlideStart();const C=g+g*w*2;if(b<C){const k=C/b;a.push({from:k,to:k,start:c,length:u,interpolation:"linear"})}else w=(b-g)/2/g;const[x,_]=h?[w,-w]:[-w,w];(f?r:n).push({from:x,to:_,start:c,length:u});break}}return{offsetXKeyframes:r,offsetYKeyframes:n,opacityKeyframes:s,scaleKeyframes:a,rotationKeyframes:o}}getPresetName(){return this.effectPreset.name}getZoomSpeed(){const{name:t,speed:i}=this.effectPreset;if(t.startsWith("zoom"))switch(i){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const{name:t,speed:i}=this.effectPreset;if(t.startsWith("slide"))switch(i){case"Slow":return .03;case"Fast":return .2;default:return .12}return 0}getFittedSize(t,i){switch(this.clipConfiguration.fit??"crop"){case"cover":case"crop":{const n=Math.max(t.width/i.width,t.height/i.height);return{width:i.width*n,height:i.height*n}}case"contain":{const n=Math.min(t.width/i.width,t.height/i.height);return{width:i.width*n,height:i.height*n}}case"none":default:return i}}}class CI{clipConfiguration;inPreset;outPreset;constructor(t){this.clipConfiguration=t,this.inPreset=this.parseTransition(t.transition?.in),this.outPreset=this.parseTransition(t.transition?.out)}parseTransition(t){const[i,r]=(t??"").split(/(Slow|Fast|VeryFast)/);return{name:i,speed:r}}buildRelative(){return{in:this.buildTransitionKeyframes("in"),out:this.buildTransitionKeyframes("out")}}createEmptyKeyframeSet(){return{offsetXKeyframes:[],offsetYKeyframes:[],opacityKeyframes:[],scaleKeyframes:[],rotationKeyframes:[],maskXKeyframes:[],brightnessKeyframes:[],wipeFromRight:!1}}buildTransitionKeyframes(t){const i=this.createEmptyKeyframeSet();if(!(t==="in"?this.clipConfiguration.transition?.in:this.clipConfiguration.transition?.out))return i;const n=this.getPresetLength(t),s=t==="in"?0:this.clipConfiguration.length-n,a=this.getPresetName(t),o=t==="in";switch(a){case"fade":{const[l,u]=o?[0,1]:[1,0];i.opacityKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"bezier",easing:"easeInOut"});break}case"zoom":{const[l,u]=o?[10,1]:[1,10],[c,d]=o?[0,1]:[1,0],f=o?"easeIn":"easeOut";o?i.scaleKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"linear"}):i.scaleKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"bezier",easing:f}),i.opacityKeyframes.push({from:c,to:d,start:s,length:n,interpolation:"bezier",easing:f});break}case"slideLeft":case"slideRight":case"slideUp":case"slideDown":{const l=a==="slideLeft"||a==="slideRight",u=a==="slideLeft"||a==="slideUp",c=.025,[d,f]=o?[u?c:-c,0]:[0,u?-c:c],h=o?"linear":"bezier",[p,g]=o?[0,1]:[1,0];(l?i.offsetXKeyframes:i.offsetYKeyframes).push(o?{from:d,to:f,start:s,length:n,interpolation:h}:{from:d,to:f,start:s,length:n,interpolation:h,easing:"ease"}),i.opacityKeyframes.push({from:p,to:g,start:s,length:n,interpolation:"bezier",easing:"ease"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":{const l=a==="carouselLeft"||a==="carouselRight",u=a==="carouselLeft"||a==="carouselUp",c=l&&1||(o?1.05:1.1),[d,f]=o?[u?c:-c,0]:[0,u?-c:c];(l?i.offsetXKeyframes:i.offsetYKeyframes).push(o?{from:d,to:f,start:s,length:n,interpolation:"linear"}:{from:d,to:f,start:s,length:n,interpolation:"bezier",easing:"ease"});break}case"reveal":{const[l,u]=o?[0,1]:[1,0];i.maskXKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"bezier",easing:"ease"});break}case"wipeLeft":case"wipeRight":{const[l,u]=o?[1,-1]:[-1,1];i.brightnessKeyframes.push({from:l,to:u,start:s,length:n,interpolation:"bezier",easing:"easeInOut"}),i.wipeFromRight=a==="wipeLeft"?o:!o;break}}return i}getPresetName(t){return t==="in"?this.inPreset.name:this.outPreset.name}getPresetLength(t){const{name:i,speed:r}=t==="in"?this.inPreset:this.outPreset,n=i.startsWith("carousel"),s=i.startsWith("slide");if(i==="zoom")return .4;switch(r){case"Slow":return 2;case"Fast":return n||s?.25:.5;case"VeryFast":return .25;default:return n||s?.5:1}}}const Nb="1.1764706",kI=`
|
|
2
2
|
in vec2 vTextureCoord;
|
|
3
3
|
out vec4 finalColor;
|
|
4
4
|
|
|
@@ -472,7 +472,7 @@ ${t.stack}`:t),this.createFallbackGraphic()}}async mountIframe(t){const i=this.c
|
|
|
472
472
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
473
473
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
474
474
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
475
|
-
*/class p1 extends ME{constructor(t){super(t),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=t._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(t=>t.trackBacking)}async getMimeType(){await this.readMetadata();const t=await this.getTrackBackings(),i=await Promise.all(t.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return zE({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:i.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let t=0,i=!1,r=!1;for(;;){let n=this.reader.requestSliceRange(t,ds,Ya);if(Lt(n)&&(n=await n),!n)break;const s=t,a=aa(n);if(!a)break;if(a.name==="ftyp"||a.name==="styp"){const o=on(n,4);this.isQuickTime=o==="qt "}else if(a.name==="moov"){let o=this.reader.requestSlice(n.filePos,a.contentSize);if(Lt(o)&&(o=await o),!o)break;this.moovSlice=o,this.readContiguousBoxes(this.moovSlice);for(const l of this.tracks){const u=l.editListPreviousSegmentDurations/this.movieTimescale;l.editListOffset-=Math.round(u*l.timescale)}i=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+a.totalSize,r=!0;break}else if(a.name==="moof"){if(!this.input._initInput)throw new 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),i=!1,r=!0;break}t=s+a.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),i){M(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);Lt(n)&&(n=await n),M(n);const s=vt(n),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-Ya){let o=this.reader.requestSliceRange(a,ds,Ya);if(Lt(o)&&(o=await o),o){const l=aa(o);if(l&&l.name==="mfra"){let u=this.reader.requestSlice(o.filePos,l.contentSize);Lt(u)&&(u=await u),u&&this.readContiguousBoxes(u)}}}}})()}async copyMetadataFromInitInput(t){const i=await t._getDemuxer();if(i.constructor!==p1)throw new Error("Init input must match the input's format.");await i.readMetadata(),this.movieTimescale=i.movieTimescale,this.movieDurationInTimescale=i.movieDurationInTimescale,this.metadataTags=i.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=i.fragmentTrackDefaults,this.psshBoxes=i.psshBoxes;for(const r of i.tracks){const n={id:r.id,demuxer:this,trackBacking:null,disposition:r.disposition,timescale:r.timescale,durationInMediaTimescale:r.durationInMediaTimescale,durationInMovieTimescale:r.durationInMovieTimescale,rotation:r.rotation,internalCodecId:r.internalCodecId,name:r.name,languageCode:r.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:r.editListPreviousSegmentDurations,editListOffset:r.editListOffset,encryptionInfo:r.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:r.info};if(r.trackBacking){if(M(n.info),n.info.type==="video"&&n.info.width!==-1){const s=n;n.trackBacking=new LE(s),this.tracks.push(n)}else if(n.info.type==="audio"&&n.info.numberOfChannels!==-1){const s=n;n.trackBacking=new $E(s),this.tracks.push(n)}}}}getSampleTableForTrack(t){if(t.sampleTable)return t.sampleTable;const i={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(t.sampleTable=i,t.sampleTableByteOffset===null)return i;M(this.moovSlice);const r=this.moovSlice.slice(t.sampleTableByteOffset);if(this.currentTrack=t,this.traverseBox(r),this.currentTrack=null,t.info?.type==="audio"&&t.info.codec&&Hr.includes(t.info.codec)&&i.sampleCompositionTimeOffsets.length===0){M(t.info?.type==="audio");const s=sa(t.info.codec),a=[],o=[];for(let l=0;l<i.sampleToChunk.length;l++){const u=i.sampleToChunk[l],c=i.sampleToChunk[l+1],d=(c?c.startChunkIndex:i.chunkOffsets.length)-u.startChunkIndex;for(let f=0;f<d;f++){const h=u.startSampleIndex+f*u.samplesPerChunk,p=h+u.samplesPerChunk,g=Ze(i.sampleTimingEntries,h,T=>T.startIndex),b=i.sampleTimingEntries[g],w=Ze(i.sampleTimingEntries,p,T=>T.startIndex),C=i.sampleTimingEntries[w],x=b.startDecodeTimestamp+(h-b.startIndex)*b.delta,S=C.startDecodeTimestamp+(p-C.startIndex)*C.delta-x,k=wi(a);k&&k.delta===S?k.count++:a.push({startIndex:u.startChunkIndex+f,startDecodeTimestamp:x,count:1,delta:S});const F=u.samplesPerChunk*s.sampleSize*t.info.numberOfChannels;o.push(F)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}i.sampleTimingEntries=a,i.sampleSizes=o}if(i.sampleCompositionTimeOffsets.length>0){i.presentationTimestamps=[];for(const s of i.sampleTimingEntries)for(let a=0;a<s.count;a++)i.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(const s of i.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){const o=s.startIndex+a,l=i.presentationTimestamps[o];l&&(l.presentationTimestamp+=s.offset)}i.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),i.presentationTimestampIndexMap=Array(i.presentationTimestamps.length).fill(-1);for(let s=0;s<i.presentationTimestamps.length;s++)i.presentationTimestampIndexMap[i.presentationTimestamps[s].sampleIndex]=s}return i}async readFragment(t){if(this.lastReadFragment?.moofOffset===t)return this.lastReadFragment;let i=this.reader.requestSliceRange(t,ds,Ya);Lt(i)&&(i=await i),M(i);const r=aa(i);M(r?.name==="moof");let n=this.reader.requestSlice(t,r.totalSize);Lt(n)&&(n=await n),M(n),this.traverseBox(n);const s=this.lastReadFragment;M(s&&s.moofOffset===t);for(const[,a]of s.trackData){const o=a.track,{fragmentPositionCache:l}=o;if(!a.startTimestampIsFinal){const c=o.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(c)g1(a,c.timestamp);else{const d=Ze(l,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){const f=l[d];g1(a,f.endTimestamp)}}a.startTimestampIsFinal=!0}const u=Ze(l,a.startTimestamp,c=>c.startTimestamp);if((u===-1||l[u].moofOffset!==s.moofOffset)&&l.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){const c=await jE(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let d=0;d<Math.min(a.samples.length,c.length);d++){const f=c[d];a.samples[d].encryption=f}}}return s}readContiguousBoxes(t){const i=t.filePos;for(;t.filePos-i<=t.length-ds&&this.traverseBox(t););}*iterateContiguousBoxes(t){const i=t.filePos;for(;t.filePos-i<=t.length-ds;){const r=t.filePos,n=aa(t);if(!n)break;yield{boxInfo:n,slice:t},t.filePos=r+n.totalSize}}traverseBox(t){const i=t.filePos,r=aa(t);if(!r)return!1;const n=t.filePos,s=i+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(t.slice(n,r.contentSize));break;case"mvhd":{const a=te(t);t.skip(3),a===1?(t.skip(16),this.movieTimescale=vt(t),this.movieDurationInTimescale=Er(t)):(t.skip(8),this.movieTimescale=vt(t),this.movieDurationInTimescale=vt(t))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...rE,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Xu,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(t.slice(n,r.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){const o=a;a.trackBacking=new LE(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.trackBacking=new $E(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=te(t),u=!!(ca(t)&1);if(a.disposition.default=u,o===0)t.skip(8),a.id=vt(t),t.skip(4),a.durationInMovieTimescale=vt(t);else if(o===1)t.skip(16),a.id=vt(t),t.skip(4),a.durationInMovieTimescale=Er(t);else throw new Error(`Incorrect track header version ${o}.`);t.skip(2*4+2+2+2+2);const c=[Ka(t),Ka(t),d1(t),Ka(t),Ka(t),d1(t),Ka(t),Ka(t),d1(t)],d=Ty(By(OJ(c),90));M(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{const a=this.currentTrack;if(!a)break;const o=te(t);t.skip(3);let l=!1,u=0;const c=vt(t);for(let d=0;d<c;d++){const f=o===1?Er(t):vt(t),h=o===1?WQ(t):io(t),p=Ka(t);if(f!==0){if(l){Jt._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(h===-1){u+=f;continue}if(p!==1){Jt._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=u,a.editListOffset=h,l=!0}}}break;case"mdhd":{const a=this.currentTrack;if(!a)break;const o=te(t);t.skip(3),o===0?(t.skip(8),a.timescale=vt(t),a.durationInMediaTimescale=vt(t)):o===1&&(t.skip(16),a.timescale=vt(t),a.durationInMediaTimescale=Er(t));let l=zi(t);if(l>0){a.languageCode="";for(let u=0;u<3;u++)a.languageCode=String.fromCharCode(96+(l&31))+a.languageCode,l>>=5;zy(a.languageCode)||(a.languageCode=Xu)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;t.skip(8);const o=on(t,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...$5},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=i,this.readContiguousBoxes(t.slice(n,r.contentSize))}break;case"stsd":{const a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;const o=te(t);t.skip(3);const l=vt(t);for(let u=0;u<l;u++){const c=t.filePos,d=aa(t);if(!d)break;a.internalCodecId=d.name;const f=d.name.toLowerCase();if(a.info.type==="video"){t.skip(6*1+2+2+2+3*4),a.info.width=zi(t),a.info.height=zi(t),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,t.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(t.slice(t.filePos,c+d.totalSize-t.filePos));const h=f==="encv"?a.frmaCodecString:f;a.frmaCodecString=null,h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":qa.includes(f)?(a.info.codec="prores",a.info.proresFormat=f):h===null?Jt._warn("Unknown encrypted video codec due to missing frma box."):Jt._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{t.skip(6*1+2);const h=zi(t);t.skip(3*2);let p=zi(t),g=zi(t);t.skip(2*2);let b=vt(t)/65536,w=null;o===0&&h>0&&(h===1?(t.skip(4),g=8*vt(t),t.skip(2*4)):h===2&&(t.skip(4),b=kA(t),p=vt(t),t.skip(4),g=vt(t),w=vt(t),t.skip(2*4))),a.info.numberOfChannels=p,a.info.sampleRate=b,a.frmaCodecString=null,this.readContiguousBoxes(t.slice(t.filePos,c+d.totalSize-t.filePos));const C=f==="enca"?a.frmaCodecString:f;if(a.frmaCodecString=null,C!=="mp4a")if(C==="opus")a.info.codec="opus",a.info.sampleRate=PE;else if(C==="flac")a.info.codec="flac";else if(C==="ulaw")a.info.codec="ulaw";else if(C==="alaw")a.info.codec="alaw";else if(C==="ac-3")a.info.codec="ac3";else if(C==="ec-3")a.info.codec="eac3";else if(Bh.includes(C))a.info.codec="dts",a.info.dtsFormat=C;else if(C==="twos")g===8?a.info.codec="pcm-s8":g===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(Jt._warn(`Unsupported sample size ${g} for codec 'twos'.`),a.info.codec=null);else if(C==="sowt")g===8?a.info.codec="pcm-s8":g===16?a.info.codec="pcm-s16":(Jt._warn(`Unsupported sample size ${g} for codec 'sowt'.`),a.info.codec=null);else if(C==="raw ")a.info.codec="pcm-u8";else if(C==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(C==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(C==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(C==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(C==="ipcm"){const x=a.info.pcmSampleSize;a.info.pcmLittleEndian?x===16?a.info.codec="pcm-s16":x===24?a.info.codec="pcm-s24":x===32?a.info.codec="pcm-s32":(Jt._warn(`Invalid ipcm sample size ${x}.`),a.info.codec=null):x===16?a.info.codec="pcm-s16be":x===24?a.info.codec="pcm-s24be":x===32?a.info.codec="pcm-s32be":(Jt._warn(`Invalid ipcm sample size ${x}.`),a.info.codec=null)}else if(C==="fpcm"){const x=a.info.pcmSampleSize;a.info.pcmLittleEndian?x===32?a.info.codec="pcm-f32":x===64?a.info.codec="pcm-f64":(Jt._warn(`Invalid fpcm sample size ${x}.`),a.info.codec=null):x===32?a.info.codec="pcm-f32be":x===64?a.info.codec="pcm-f64be":(Jt._warn(`Invalid fpcm sample size ${x}.`),a.info.codec=null)}else if(C==="lpcm"&&w!==null){const x=g+7>>3,_=!!(w&1),S=!!(w&2),k=w&4?-1:0;g>0&&g<=64&&(_?g===32&&(a.info.codec=S?"pcm-f32be":"pcm-f32"):k&1<<x-1?x===1?a.info.codec="pcm-s8":x===2?a.info.codec=S?"pcm-s16be":"pcm-s16":x===3?a.info.codec=S?"pcm-s24be":"pcm-s24":x===4&&(a.info.codec=S?"pcm-s32be":"pcm-s32"):x===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&Jt._warn("Unsupported PCM format.")}else C===null?Jt._warn("Unknown encrypted audio codec due to missing frma box."):Jt._warn(`Unsupported audio codec (sample entry type '${d.name}').`)}t.filePos=c+d.totalSize}}break;case"frma":{const a=this.currentTrack;if(!a)break;const l=on(t,4).toLowerCase();a.frmaCodecString=l}break;case"schm":{const a=this.currentTrack;if(!a)break;t.skip(4);const o=on(t,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:Jt._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=te(t);t.skip(3),t.skip(1);const l=te(t);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=l>>4,a.encryptionInfo.defaultSkipByteBlock=l&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=te(t)!==0,a.encryptionInfo.defaultPerSampleIvSize=te(t),a.encryptionInfo.defaultKid=Ku(Ce(t,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const u=te(t),c=new Uint8Array(16);c.set(Ce(t,u),0),a.encryptionInfo.defaultConstantIv=c}}break;case"avcC":{const a=this.currentTrack;if(!a||(M(a.info),r.contentSize===0))break;a.info.codecDescription=Ce(t,r.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a||(M(a.info),r.contentSize===0))break;a.info.codecDescription=Ce(t,r.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="video"),t.skip(4);const o=te(t),l=te(t),u=te(t),c=u>>4,d=u>>1&7,f=u&1,h=te(t),p=te(t),g=te(t);a.info.vp9CodecInfo={profile:o,level:l,bitDepth:c,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:h,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="video"),t.skip(1);const o=te(t),l=o>>5,u=o&31,c=te(t),d=c>>7,f=c>>6&1,h=c>>5&1,p=c>>4&1,g=c>>3&1,b=c>>2&1,w=c&3,C=l===2&&f?h?12:10:f?10:8;t.skip(1);const x=Ce(t,r.contentSize-4),_=a1(x);a.info.av1CodecInfo={profile:l,level:u,tier:d,bitDepth:C,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:b,chromaSamplePosition:w,videoFullRangeFlag:_?.videoFullRangeFlag??0,colourPrimaries:_?.colourPrimaries??2,transferCharacteristics:_?.transferCharacteristics??2,matrixCoefficients:_?.matrixCoefficients??2}}break;case"colr":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="video");const o=on(t,4);if(o!=="nclx"&&o!=="nclc")break;const l=zi(t),u=zi(t),c=zi(t);let d;o==="nclx"&&(d=!!(te(t)&128)),a.info.colorSpace={primaries:Wa[l],transfer:Ha[u],matrix:Ga[c],fullRange:d}}break;case"pasp":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="video");const o=vt(t),l=vt(t);o>0&&l>0&&(o>l?a.info.squarePixelWidth=Math.round(a.info.width*o/l):a.info.squarePixelHeight=Math.round(a.info.height*l/o))}break;case"wave":this.readContiguousBoxes(t.slice(n,r.contentSize));break;case"esds":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),t.skip(4);const o=te(t);M(o===3),f1(t),t.skip(2);const l=te(t),u=(l&128)!==0,c=(l&64)!==0,d=(l&32)!==0;if(u&&t.skip(2),c){const b=te(t);t.skip(b)}d&&t.skip(2);const f=te(t);M(f===4);const h=f1(t),p=t.filePos,g=te(t);if(g===64||g===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:g===103,objectType:null}):g===105||g===107?a.info.codec="mp3":g===221?a.info.codec="vorbis":g===169?a.info.codec="dts":Jt._warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),t.skip(12),h>t.filePos-p){const b=te(t);M(b===5);const w=f1(t);if(a.info.codecDescription=Ce(t,w),a.info.codec==="aac"){const C=Yy(a.info.codecDescription);C.outputNumberOfChannels!==null&&(a.info.numberOfChannels=C.outputNumberOfChannels),C.outputSampleRate!==null&&(a.info.sampleRate=C.outputSampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(zi(t)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),t.skip(4);const o=te(t);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=te(t)}break;case"dOps":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),t.skip(1);const o=te(t),l=zi(t),u=vt(t),c=M1(t),d=te(t);let f;d!==0?f=Ce(t,2+o):f=new Uint8Array(0);const h=new Uint8Array(19+f.byteLength),p=new DataView(h.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,l,!0),p.setUint32(12,u,!0),p.setInt16(16,c,!0),p.setUint8(18,d),h.set(f,19),a.info.codecDescription=h,a.info.numberOfChannels=o}break;case"dfLa":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),t.skip(4);const o=127,l=128,u=t.filePos;for(;t.filePos<s;){const p=te(t),g=ca(t);if((p&o)===l1.STREAMINFO){t.skip(10);const w=vt(t),C=w>>>12,x=(w>>9&7)+1;a.info.sampleRate=C,a.info.numberOfChannels=x,t.skip(20)}else t.skip(g);if(p&l)break}const c=t.filePos;t.filePos=u;const d=Ce(t,c-u),f=new Uint8Array(4+d.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(d,4),a.info.codecDescription=f}break;case"dac3":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio");const o=Ce(t,3),l=new We(o),u=l.readBits(2);l.skipBits(8);const c=l.readBits(3),d=l.readBits(1);u<3&&(a.info.sampleRate=Qy[u]),a.info.numberOfChannels=vE[c]+d}break;case"dec3":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio");const o=Ce(t,r.contentSize),l=KX(o);if(!l){Jt._warn("Invalid dec3 box contents, ignoring.");break}const u=XX(l);u!==null&&(a.info.sampleRate=u),a.info.numberOfChannels=JX(l)}break;case"ddts":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio");const o=Ce(t,Math.min(r.contentSize,u1)),l=hJ(o);if(!l){Jt._warn("Invalid ddts box contents, ignoring.");break}a.info.sampleRate=l.sampleRate,l.numberOfChannels!==null&&(a.info.numberOfChannels=l.numberOfChannels)}break;case"stts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);let l=0,u=0;for(let c=0;c<o;c++){const d=vt(t),f=vt(t);a.sampleTable.sampleTimingEntries.push({startIndex:l,startDecodeTimestamp:u,count:d,delta:f}),l+=d,u+=d*f}}break;case"ctts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);let l=0;for(let u=0;u<o;u++){const c=vt(t),d=io(t);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:l,count:c,offset:d}),l+=c}}break;case"stsz":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t),l=vt(t);if(o===0)for(let u=0;u<l;u++){const c=vt(t);a.sampleTable.sampleSizes.push(c)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4),t.skip(3);const o=te(t),l=vt(t),u=Ce(t,Math.ceil(l*o/8)),c=new We(u);for(let d=0;d<l;d++){const f=c.readBits(o);a.sampleTable.sampleSizes.push(f)}}break;case"stss":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4),a.sampleTable.keySampleIndices=[];const o=vt(t);for(let l=0;l<o;l++){const u=vt(t)-1;a.sampleTable.keySampleIndices.push(u)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);for(let u=0;u<o;u++){const c=vt(t)-1,d=vt(t),f=vt(t);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:c,samplesPerChunk:d,sampleDescriptionIndex:f})}let l=0;for(let u=0;u<a.sampleTable.sampleToChunk.length;u++)if(a.sampleTable.sampleToChunk[u].startSampleIndex=l,u<a.sampleTable.sampleToChunk.length-1){const d=a.sampleTable.sampleToChunk[u+1].startChunkIndex-a.sampleTable.sampleToChunk[u].startChunkIndex;l+=d*a.sampleTable.sampleToChunk[u].samplesPerChunk}}break;case"stco":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);for(let l=0;l<o;l++){const u=vt(t);a.sampleTable.chunkOffsets.push(u)}}break;case"co64":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);for(let l=0;l<o;l++){const u=Er(t);a.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(t.slice(n,r.contentSize));break;case"mehd":{const a=te(t);t.skip(3);const o=a===1?Er(t):vt(t);this.movieDurationInTimescale=o}break;case"trex":{t.skip(4);const a=vt(t),o=vt(t),l=vt(t),u=vt(t),c=vt(t);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:l,defaultSampleSize:u,defaultSampleFlags:c})}break;case"tfra":{const a=te(t);t.skip(3);const o=vt(t),l=this.tracks.find(C=>C.id===o);if(!l)break;const u=vt(t),c=(u&48)>>4,d=(u&12)>>2,f=u&3,h=[te,zi,ca,vt],p=h[c],g=h[d],b=h[f],w=vt(t);for(let C=0;C<w;C++){const x=a===1?Er(t):vt(t),_=a===1?Er(t):vt(t);p(t),g(t),b(t),l.fragmentLookupTable.push({timestamp:x,moofOffset:_})}l.fragmentLookupTable.sort((C,x)=>C.timestamp-x.timestamp);for(let C=0;C<l.fragmentLookupTable.length-1;C++){const x=l.fragmentLookupTable[C],_=l.fragmentLookupTable[C+1];x.timestamp===_.timestamp&&(l.fragmentLookupTable.splice(C+1,1),C--)}}break;case"moof":this.currentFragment={moofOffset:i,moofSize:r.totalSize,implicitBaseDataOffset:i,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(t.slice(n,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(M(this.currentFragment),this.readContiguousBoxes(t.slice(n,r.contentSize)),this.currentTrack){const a=this.currentFragment.trackData.get(this.currentTrack.id);t:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break t}a.presentationTimestamps=a.samples.map((c,d)=>({presentationTimestamp:c.presentationTimestamp,sampleIndex:d})).sort((c,d)=>c.presentationTimestamp-d.presentationTimestamp);for(let c=0;c<a.presentationTimestamps.length;c++){const d=a.presentationTimestamps[c],f=a.samples[d.sampleIndex];if(a.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(a.firstKeyFrameTimestamp=f.presentationTimestamp),c<a.presentationTimestamps.length-1){const p=a.presentationTimestamps[c+1].presentationTimestamp-d.presentationTimestamp;f.duration=p}}const o=a.samples[a.presentationTimestamps[0].sampleIndex],l=a.samples[wi(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=l.presentationTimestamp+l.duration;const{currentFragmentState:u}=this.currentTrack;M(u),u.startTimestamp!==null&&(g1(a,u.startTimestamp),a.startTimestampIsFinal=!0),u.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=u.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;const a=IJ(Ce(t,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{M(this.currentFragment),t.skip(1);const a=ca(t),o=!!(a&1),l=!!(a&2),u=!!(a&8),c=!!(a&16),d=!!(a&32),f=!!(a&65536),h=!!(a&131072),p=vt(t),g=this.tracks.find(w=>w.id===p);if(!g)break;const b=this.fragmentTrackDefaults.find(w=>w.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:b?.defaultSampleDescriptionIndex??null,defaultSampleDuration:b?.defaultSampleDuration??null,defaultSampleSize:b?.defaultSampleSize??null,defaultSampleFlags:b?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?g.currentFragmentState.baseDataOffset=Er(t):h&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),l&&(g.currentFragmentState.sampleDescriptionIndex=vt(t)),u&&(g.currentFragmentState.defaultSampleDuration=vt(t)),c&&(g.currentFragmentState.defaultSampleSize=vt(t)),d&&(g.currentFragmentState.defaultSampleFlags=vt(t)),f&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const a=this.currentTrack;if(!a)break;M(a.currentFragmentState);const o=te(t);t.skip(3);const l=o===0?vt(t):Er(t);a.currentFragmentState.startTimestamp=l}break;case"trun":{const a=this.currentTrack;if(!a)break;M(this.currentFragment),M(a.currentFragmentState);const o=te(t),l=ca(t),u=!!(l&1),c=!!(l&4),d=!!(l&256),f=!!(l&512),h=!!(l&1024),p=!!(l&2048),g=vt(t);let b=null;u&&(b=io(t));let w=null;c&&(w=vt(t));let C;this.currentFragment.trackData.has(a.id)?(C=this.currentFragment.trackData.get(a.id),b!==null&&(C.currentOffset=a.currentFragmentState.baseDataOffset+b)):(C={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(b??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,C));for(let x=0;x<g;x++){let _;d?_=vt(t):(M(a.currentFragmentState.defaultSampleDuration!==null),_=a.currentFragmentState.defaultSampleDuration);let S;f?S=vt(t):(M(a.currentFragmentState.defaultSampleSize!==null),S=a.currentFragmentState.defaultSampleSize);let k;h?k=vt(t):(M(a.currentFragmentState.defaultSampleFlags!==null),k=a.currentFragmentState.defaultSampleFlags),x===0&&w!==null&&(k=w);let F=0;p&&(o===0?F=vt(t):F=io(t));const T=!(k&65536);C.samples.push({presentationTimestamp:C.currentTimestamp+F,duration:_,byteOffset:C.currentOffset,byteSize:S,isKeyFrame:T,encryption:null}),C.currentOffset+=S,C.currentTimestamp+=_}this.currentFragment.implicitBaseDataOffset=C.currentOffset}break;case"saiz":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(t.skip(1),ca(t)&1){const f=on(t,4),h=vt(t);if(f!==a.encryptionInfo.scheme||h!==0)break}const l=te(t),u=vt(t);let c=null;l===0&&u>0&&(c=Ce(t,u));const d=ZE(a);d.defaultSampleInfoSize=l,d.sampleSizes=c,d.sampleCount=u}break;case"saio":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=te(t);if(ca(t)&1){const f=on(t,4),h=vt(t);if(f!==a.encryptionInfo.scheme||h!==0)break}const u=vt(t);if(u===0)break;u>1&&Jt._warn("Multiple saio entries are not supported; using the first offset only.");let c=o===0?vt(t):Number(Er(t));this.currentFragment&&(c+=this.currentFragment.moofOffset);const d=ZE(a);d.offset=c}break;case"senc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;M(this.currentFragment);const o=this.currentFragment.trackData.get(a.id);if(!o)break;t.skip(1);const u=!!(ca(t)&2),c=vt(t),d=a.encryptionInfo.defaultPerSampleIvSize;M(d!==null);for(let f=0;f<Math.min(c,o.samples.length);f++){const h=new Uint8Array(16);d>0?h.set(Ce(t,d),0):h.set(a.encryptionInfo.defaultConstantIv,0);let p=null;if(u){const b=zi(t);p=[];for(let w=0;w<b;w++){const C=zi(t),x=vt(t);p.push({clearLen:C,protectedLen:x})}}const g=o.samples[f];g.encryption={iv:h,subsamples:p}}}break;case"udta":{const a=this.iterateContiguousBoxes(t.slice(n,r.contentSize));for(const{boxInfo:o,slice:l}of a){if(o.name!=="meta"&&!this.currentTrack){const u=l.filePos;this.metadataTags.raw??={},o.name[0]==="©"?this.metadataTags.raw[o.name]??=$n(l):this.metadataTags.raw[o.name]??=Ce(l,o.contentSize),l.filePos=u}switch(o.name){case"meta":l.skip(-o.headerSize),this.traverseBox(l);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=il.decode(Ce(l,o.contentSize)):this.metadataTags.title??=$n(l);break;case"©des":this.currentTrack||(this.metadataTags.description??=$n(l));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=$n(l));break;case"©alb":this.currentTrack||(this.metadataTags.album??=$n(l));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=$n(l));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=$n(l));break;case"©day":if(!this.currentTrack){const u=new Date($n(l));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=$n(l));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=$n(l));break}}}break;case"meta":{if(this.currentTrack)break;const o=vt(t)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(t.slice(n,r.contentSize)):this.readContiguousBoxes(t.slice(n+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;t.skip(4);const a=vt(t);for(let o=0;o<a;o++){const l=vt(t);t.skip(4);const u=il.decode(Ce(t,l-8));this.currentMetadataKeys.set(o+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const a=this.iterateContiguousBoxes(t.slice(n,r.contentSize));for(const{boxInfo:o,slice:l}of a){let u=o.name;const c=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(c)&&(u=this.currentMetadataKeys.get(c));const d=PJ(l);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=d,u){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"©lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){const f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof al?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){const f=d.split("/"),h=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){const f=Me(d),h=f.getUint16(2,!1),p=f.getUint16(4,!1);h>0&&(this.metadataTags.trackNumber??=h),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){const f=Me(d),h=f.getUint16(2,!1),p=f.getUint16(4,!1);h>0&&(this.metadataTags.discNumber??=h),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return t.filePos=s,!0}}class VE{constructor(t){this.internalTrack=t,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const t=this.internalTrack.demuxer,i=this.internalTrack.trackBacking.getType();let r=0;for(const n of t.tracks)if(n.trackBacking.getType()===i&&r++,n===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const t=this.internalTrack;return t.durationInMediaTimescale<=0?null:(M(t.trackBacking),((await t.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+t.durationInMediaTimescale/t.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(t){const i=await this.fetchPacketForSampleIndex(0,t);return i||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,t)}mapTimestampIntoTimescale(t){return Y5(t*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(t,i){const r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=m1(n,r),a=await this.fetchPacketForSampleIndex(s,i);return!UE(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const l=o.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};const u=Ze(l.presentationTimestamps,r,f=>f.presentationTimestamp),c=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<l.endTimestamp;return{sampleIndex:c,correctSampleFound:d}},r,r,i)}async getNextPacket(t,i){const r=this.packetToSampleIndex.get(t);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,i);const n=this.packetToFragmentLocation.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const a=s.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<a.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,i)}async getKeyPacket(t,i){const r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=NJ(n,r),a=await this.fetchPacketForSampleIndex(s,i);return!UE(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const l=o.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};const u=H5(l.presentationTimestamps,f=>l.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=r),c=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<l.endTimestamp;return{sampleIndex:c,correctSampleFound:d}},r,r,i)}async getNextKeyPacket(t,i){const r=this.packetToSampleIndex.get(t);if(r!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=zJ(s,r);return this.fetchPacketForSampleIndex(a,i)}const n=this.packetToFragmentLocation.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const o=s.trackData.get(this.internalTrack.id).samples.findIndex((l,u)=>l.isKeyFrame&&u>n.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(l=>l.isKeyFrame);return M(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,i)}async fetchPacketForSampleIndex(t,i){if(t===-1)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=MJ(r,t);if(!n)return null;let s;if(i.metadataOnly)s=ll;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(Lt(u)&&(u=await u),!u)return null;if(s=Ce(u,n.sampleSize),this.internalTrack.encryptionInfo){let c=null;if(this.internalTrack.encryptionAuxInfo){const d=await jE(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);t<d.length&&(c=d[t])}c??=WE(this.internalTrack.encryptionInfo),c&&(s=await HE(this.internalTrack,c,s,null))}}const a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,l=new fi(s,n.isKeyFrame?"key":"delta",a,o,t,n.sampleSize);return this.packetToSampleIndex.set(l,t),l}async fetchPacketInFragment(t,i,r){if(i===-1)return null;const s=t.trackData.get(this.internalTrack.id).samples[i];M(s);let a;if(r.metadataOnly)a=ll;else{let c=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(Lt(c)&&(c=await c),!c)return null;if(a=Ce(c,s.byteSize),this.internalTrack.encryptionInfo){const d=s.encryption??WE(this.internalTrack.encryptionInfo);d&&(a=await HE(this.internalTrack,d,a,t))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=s.duration/this.internalTrack.timescale,u=new fi(a,s.isKeyFrame?"key":"delta",o,l,t.moofOffset+i,s.byteSize);return this.packetToFragmentLocation.set(u,{fragment:t,sampleIndex:i}),u}async performFragmentedLookup(t,i,r,n,s){const a=this.internalTrack.demuxer;let o=null,l=null,u=-1;if(t){const{sampleIndex:b,correctSampleFound:w}=i(t);if(w)return this.fetchPacketInFragment(t,b,s);b!==-1&&(l=t,u=b)}const c=Ze(this.internalTrack.fragmentLookupTable,r,b=>b.timestamp),d=c!==-1?this.internalTrack.fragmentLookupTable[c]:null,f=Ze(this.internalTrack.fragmentPositionCache,r,b=>b.startTimestamp),h=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max(d?.moofOffset??0,h?.moofOffset??0)||null;let g;for(t?p===null||t.moofOffset>=p?(g=t.moofOffset+t.moofSize,o=t):g=p:g=p??0;;){if(o){const x=o.trackData.get(this.internalTrack.id);if(x&&x.startTimestamp>n)break}let b=a.reader.requestSliceRange(g,ds,Ya);if(Lt(b)&&(b=await b),!b)break;const w=g,C=aa(b);if(!C)break;if(C.name==="moof"){o=await a.readFragment(w);const{sampleIndex:x,correctSampleFound:_}=i(o);if(_)return this.fetchPacketInFragment(o,x,s);x!==-1&&(l=o,u=x)}g=w+C.totalSize}if(d&&(!l||l.moofOffset<d.moofOffset)){const b=this.internalTrack.fragmentLookupTable[c-1];M(!b||b.timestamp<d.timestamp);const w=b?.timestamp??-1/0;return this.performFragmentedLookup(null,i,w,n,s)}return l?this.fetchPacketInFragment(l,u,s):null}}class LE extends VE{constructor(t){super(t),this.decoderConfigPromise=null,this.internalTrack=t}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}getRotation(){return this.internalTrack.rotation}async getColorSpace(){const t=await this.getDecoderConfig();return t?{primaries:t.colorSpace?.primaries,transfer:t.colorSpace?.transfer,matrix:t.colorSpace?.matrix,fullRange:t.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){const i=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=i&&r1(i.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const i=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=i&&s1(i.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!jX(this.internalTrack.info.vp9CodecInfo))){const i=await this.getFirstPacket({}),r=i&&gE(i.data);r&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??r,videoFullRangeFlag:r.videoFullRangeFlag,colourPrimaries:r.colourPrimaries,transferCharacteristics:r.transferCharacteristics,matrixCoefficients:r.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!WX(this.internalTrack.info.av1CodecInfo))){const i=await this.getFirstPacket({}),r=i&&a1(i.data);r&&(this.internalTrack.info.av1CodecInfo=r)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){const i=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=i&&bE(i.data)}if(!Dy(this.internalTrack.info.colorSpace)){const i=IE(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=i.primaries,this.internalTrack.info.colorSpace.transfer??=i.transfer,this.internalTrack.info.colorSpace.matrix??=i.matrix,this.internalTrack.info.colorSpace.fullRange??=i.fullRange}const t={codec:TE(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)&&(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})():null}}class $E extends VE{constructor(t){super(t),this.decoderConfigPromise=null,this.internalTrack=t}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){const t=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=t&&kE(t.data)}return{codec:DE(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const m1=(e,t)=>{if(e.presentationTimestamps){const i=Ze(e.presentationTimestamps,t,r=>r.presentationTimestamp);return i===-1?-1:e.presentationTimestamps[i].sampleIndex}else{const i=Ze(e.sampleTimingEntries,t,n=>n.startDecodeTimestamp);if(i===-1)return-1;const r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},NJ=(e,t)=>{if(!e.keySampleIndices)return m1(e,t);if(e.presentationTimestamps){const i=Ze(e.presentationTimestamps,t,r=>r.presentationTimestamp);if(i===-1)return-1;for(let r=i;r>=0;r--){const n=e.presentationTimestamps[r].sampleIndex;if(j5(e.keySampleIndices,n,a=>a)!==-1)return n}return-1}else{const i=m1(e,t),r=Ze(e.keySampleIndices,i,n=>n);return e.keySampleIndices[r]??-1}},MJ=(e,t)=>{const i=Ze(e.sampleTimingEntries,t,w=>w.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let s=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const a=Ze(e.sampleCompositionTimeOffsets,t,w=>w.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(s+=o.offset);const l=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],u=Ze(e.sampleToChunk,t,w=>w.startSampleIndex),c=e.sampleToChunk[u];M(c);const d=c.startChunkIndex+Math.floor((t-c.startSampleIndex)/c.samplesPerChunk),f=e.chunkOffsets[d],h=c.startSampleIndex+(d-c.startChunkIndex)*c.samplesPerChunk;let p=0,g=f;if(e.sampleSizes.length===1)g+=l*(t-h),p+=l*c.samplesPerChunk;else for(let w=h;w<h+c.samplesPerChunk;w++){const C=e.sampleSizes[w];w<t&&(g+=C),p+=C}let b=r.delta;if(e.presentationTimestamps){const w=e.presentationTimestampIndexMap[t];M(w!==void 0),w<e.presentationTimestamps.length-1&&(b=e.presentationTimestamps[w+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:b,sampleOffset:g,sampleSize:l,chunkOffset:f,chunkSize:p,isKeyFrame:e.keySampleIndices?j5(e.keySampleIndices,t,w=>w)!==-1:!0}},zJ=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=Ze(e.keySampleIndices,t,r=>r);return e.keySampleIndices[i+1]??-1},g1=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const i of e.samples)i.presentationTimestamp+=t;for(const i of e.presentationTimestamps)i.presentationTimestamp+=t},OJ=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},UE=e=>e.sampleSizes.length===0,ZE=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},jE=async(e,t,i)=>{if(i.resolved)return i.resolved;if(i.offset===null||i.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{M(i.sampleSizes);for(let o=0;o<i.sampleCount;o++)r+=i.sampleSizes[o]}let n=e.requestSlice(i.offset,r);if(Lt(n)&&(n=await n),!n)throw new Error("Failed to read auxiliary encryption info.");const s=t.defaultPerSampleIvSize;M(s!==null);const a=[];for(let o=0;o<i.sampleCount;o++){const l=i.defaultSampleInfoSize>0?i.defaultSampleInfoSize:i.sampleSizes[o],u=new Uint8Array(16);s>0?u.set(Ce(n,s),0):u.set(t.defaultConstantIv,0);let c=null;if(l>s){const d=zi(n);c=[];for(let f=0;f<d;f++){const h=zi(n),p=vt(n);c.push({clearLen:h,protectedLen:p})}}a.push({iv:u,subsamples:c})}return i.resolved=a,a},WE=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,HE=async(e,t,i,r)=>{M(e.encryptionInfo);const n=e.encryptionInfo;M(n.defaultKid!==null);const s=n.defaultKid;let a;const o=e.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const l=(async()=>{let u=e.demuxer.psshBoxes;if(r){u=[...u,...r.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(s));for(let d=0;d<u.length-1;d++)for(let f=d+1;f<u.length;f++)DJ(u[d],u[f])&&(u.splice(f,1),f--)}const c=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:u});if(!(typeof c=="string"&&c.length===32&&yX.test(c)||c instanceof Uint8Array&&c.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return c instanceof Uint8Array?c:bX(c)})();e.demuxer.decryptionKeyCache.set(s,l),a=await l}return n.scheme==="cenc"||n.scheme==="cens"?RJ(a,n,t,i):VJ(a,n,t,i)},RJ=async(e,t,i,r)=>{const n=new Uint8Array(16);n.set(i.iv,0);const s=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const g=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,p);return new Uint8Array(g)};if(!i.subsamples)return a(r);M(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);const o=GE(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const p of o)for(const g of p.perSubsample)l+=g.length;const u=new Uint8Array(l);let c=0;for(const p of o)for(const g of p.perSubsample)u.set(r.subarray(g.offset,g.offset+g.length),c),c+=g.length;const d=await a(u),f=new Uint8Array(r);let h=0;for(const p of o)for(const g of p.perSubsample)f.set(d.subarray(h,h+g.length),g.offset),h+=g.length;return f},VJ=(e,t,i,r)=>{const n=new BJ;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(M(s!==null&&a!==null),!i.subsamples){const c=new Uint8Array(r),d=Math.floor(r.length/16);for(let f=0;f<d;f++){const h=f*16;n.in.set(r.subarray(h,h+16)),n.decrypt(),c.set(n.out,h)}return c}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(r),l=GE(i.subsamples,s,a),u=new DataView(i.iv.buffer,i.iv.byteOffset,16);for(const c of l){n.iv[0]=u.getUint32(0,!1),n.iv[1]=u.getUint32(4,!1),n.iv[2]=u.getUint32(8,!1),n.iv[3]=u.getUint32(12,!1);for(const d of c.perSubsample){const f=d.length/16;for(let h=0;h<f;h++){const p=d.offset+h*16;n.in.set(r.subarray(p,p+16)),n.decrypt(),o.set(n.out,p)}}}return o},GE=(e,t,i)=>{const r=[],n=t!==0||i!==0;let s=0;for(const a of e){s+=a.clearLen;const o=[];if(!n)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let l=a.protectedLen,u=s;for(;l>0&&!(l<16*t);){const c=16*t;o.push({offset:u,length:c}),u+=c,l-=c;const d=Math.min(16*i,l);u+=d,l-=d}s+=a.protectedLen}r.push({perSubsample:o})}return r};/*!
|
|
475
|
+
*/class p1 extends ME{constructor(t){super(t),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=t._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(t=>t.trackBacking)}async getMimeType(){await this.readMetadata();const t=await this.getTrackBackings(),i=await Promise.all(t.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return zE({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:i.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let t=0,i=!1,r=!1;for(;;){let n=this.reader.requestSliceRange(t,ds,Ya);if(Lt(n)&&(n=await n),!n)break;const s=t,a=aa(n);if(!a)break;if(a.name==="ftyp"||a.name==="styp"){const o=on(n,4);this.isQuickTime=o==="qt "}else if(a.name==="moov"){let o=this.reader.requestSlice(n.filePos,a.contentSize);if(Lt(o)&&(o=await o),!o)break;this.moovSlice=o,this.readContiguousBoxes(this.moovSlice);for(const l of this.tracks){const u=l.editListPreviousSegmentDurations/this.movieTimescale;l.editListOffset-=Math.round(u*l.timescale)}i=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+a.totalSize,r=!0;break}else if(a.name==="moof"){if(!this.input._initInput)throw new 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),i=!1,r=!0;break}t=s+a.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),i){M(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);Lt(n)&&(n=await n),M(n);const s=vt(n),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-Ya){let o=this.reader.requestSliceRange(a,ds,Ya);if(Lt(o)&&(o=await o),o){const l=aa(o);if(l&&l.name==="mfra"){let u=this.reader.requestSlice(o.filePos,l.contentSize);Lt(u)&&(u=await u),u&&this.readContiguousBoxes(u)}}}}})()}async copyMetadataFromInitInput(t){const i=await t._getDemuxer();if(i.constructor!==p1)throw new Error("Init input must match the input's format.");await i.readMetadata(),this.movieTimescale=i.movieTimescale,this.movieDurationInTimescale=i.movieDurationInTimescale,this.metadataTags=i.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=i.fragmentTrackDefaults,this.psshBoxes=i.psshBoxes;for(const r of i.tracks){const n={id:r.id,demuxer:this,trackBacking:null,disposition:r.disposition,timescale:r.timescale,durationInMediaTimescale:r.durationInMediaTimescale,durationInMovieTimescale:r.durationInMovieTimescale,rotation:r.rotation,internalCodecId:r.internalCodecId,name:r.name,languageCode:r.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:r.editListPreviousSegmentDurations,editListOffset:r.editListOffset,encryptionInfo:r.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:r.info};if(r.trackBacking){if(M(n.info),n.info.type==="video"&&n.info.width!==-1){const s=n;n.trackBacking=new LE(s),this.tracks.push(n)}else if(n.info.type==="audio"&&n.info.numberOfChannels!==-1){const s=n;n.trackBacking=new $E(s),this.tracks.push(n)}}}}getSampleTableForTrack(t){if(t.sampleTable)return t.sampleTable;const i={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(t.sampleTable=i,t.sampleTableByteOffset===null)return i;M(this.moovSlice);const r=this.moovSlice.slice(t.sampleTableByteOffset);if(this.currentTrack=t,this.traverseBox(r),this.currentTrack=null,t.info?.type==="audio"&&t.info.codec&&Hr.includes(t.info.codec)&&i.sampleCompositionTimeOffsets.length===0){M(t.info?.type==="audio");const s=sa(t.info.codec),a=[],o=[];for(let l=0;l<i.sampleToChunk.length;l++){const u=i.sampleToChunk[l],c=i.sampleToChunk[l+1],d=(c?c.startChunkIndex:i.chunkOffsets.length)-u.startChunkIndex;for(let f=0;f<d;f++){const h=u.startSampleIndex+f*u.samplesPerChunk,p=h+u.samplesPerChunk,g=Ze(i.sampleTimingEntries,h,T=>T.startIndex),b=i.sampleTimingEntries[g],w=Ze(i.sampleTimingEntries,p,T=>T.startIndex),C=i.sampleTimingEntries[w],x=b.startDecodeTimestamp+(h-b.startIndex)*b.delta,S=C.startDecodeTimestamp+(p-C.startIndex)*C.delta-x,k=wi(a);k&&k.delta===S?k.count++:a.push({startIndex:u.startChunkIndex+f,startDecodeTimestamp:x,count:1,delta:S});const F=u.samplesPerChunk*s.sampleSize*t.info.numberOfChannels;o.push(F)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}i.sampleTimingEntries=a,i.sampleSizes=o}if(i.sampleCompositionTimeOffsets.length>0){i.presentationTimestamps=[];for(const s of i.sampleTimingEntries)for(let a=0;a<s.count;a++)i.presentationTimestamps.push({presentationTimestamp:s.startDecodeTimestamp+a*s.delta,sampleIndex:s.startIndex+a});for(const s of i.sampleCompositionTimeOffsets)for(let a=0;a<s.count;a++){const o=s.startIndex+a,l=i.presentationTimestamps[o];l&&(l.presentationTimestamp+=s.offset)}i.presentationTimestamps.sort((s,a)=>s.presentationTimestamp-a.presentationTimestamp),i.presentationTimestampIndexMap=Array(i.presentationTimestamps.length).fill(-1);for(let s=0;s<i.presentationTimestamps.length;s++)i.presentationTimestampIndexMap[i.presentationTimestamps[s].sampleIndex]=s}return i}async readFragment(t){if(this.lastReadFragment?.moofOffset===t)return this.lastReadFragment;let i=this.reader.requestSliceRange(t,ds,Ya);Lt(i)&&(i=await i),M(i);const r=aa(i);M(r?.name==="moof");let n=this.reader.requestSlice(t,r.totalSize);Lt(n)&&(n=await n),M(n),this.traverseBox(n);const s=this.lastReadFragment;M(s&&s.moofOffset===t);for(const[,a]of s.trackData){const o=a.track,{fragmentPositionCache:l}=o;if(!a.startTimestampIsFinal){const c=o.fragmentLookupTable.find(d=>d.moofOffset===s.moofOffset);if(c)g1(a,c.timestamp);else{const d=Ze(l,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){const f=l[d];g1(a,f.endTimestamp)}}a.startTimestampIsFinal=!0}const u=Ze(l,a.startTimestamp,c=>c.startTimestamp);if((u===-1||l[u].moofOffset!==s.moofOffset)&&l.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){const c=await jE(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let d=0;d<Math.min(a.samples.length,c.length);d++){const f=c[d];a.samples[d].encryption=f}}}return s}readContiguousBoxes(t){const i=t.filePos;for(;t.filePos-i<=t.length-ds&&this.traverseBox(t););}*iterateContiguousBoxes(t){const i=t.filePos;for(;t.filePos-i<=t.length-ds;){const r=t.filePos,n=aa(t);if(!n)break;yield{boxInfo:n,slice:t},t.filePos=r+n.totalSize}}traverseBox(t){const i=t.filePos,r=aa(t);if(!r)return!1;const n=t.filePos,s=i+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(t.slice(n,r.contentSize));break;case"mvhd":{const a=te(t);t.skip(3),a===1?(t.skip(16),this.movieTimescale=vt(t),this.movieDurationInTimescale=Er(t)):(t.skip(8),this.movieTimescale=vt(t),this.movieDurationInTimescale=vt(t))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...rE,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Xu,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(t.slice(n,r.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){const o=a;a.trackBacking=new LE(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.trackBacking=new $E(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=te(t),u=!!(ca(t)&1);if(a.disposition.default=u,o===0)t.skip(8),a.id=vt(t),t.skip(4),a.durationInMovieTimescale=vt(t);else if(o===1)t.skip(16),a.id=vt(t),t.skip(4),a.durationInMovieTimescale=Er(t);else throw new Error(`Incorrect track header version ${o}.`);t.skip(2*4+2+2+2+2);const c=[Ka(t),Ka(t),d1(t),Ka(t),Ka(t),d1(t),Ka(t),Ka(t),d1(t)],d=Ty(By(OJ(c),90));M(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{const a=this.currentTrack;if(!a)break;const o=te(t);t.skip(3);let l=!1,u=0;const c=vt(t);for(let d=0;d<c;d++){const f=o===1?Er(t):vt(t),h=o===1?WQ(t):io(t),p=Ka(t);if(f!==0){if(l){Jt._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(h===-1){u+=f;continue}if(p!==1){Jt._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=u,a.editListOffset=h,l=!0}}}break;case"mdhd":{const a=this.currentTrack;if(!a)break;const o=te(t);t.skip(3),o===0?(t.skip(8),a.timescale=vt(t),a.durationInMediaTimescale=vt(t)):o===1&&(t.skip(16),a.timescale=vt(t),a.durationInMediaTimescale=Er(t));let l=zi(t);if(l>0){a.languageCode="";for(let u=0;u<3;u++)a.languageCode=String.fromCharCode(96+(l&31))+a.languageCode,l>>=5;zy(a.languageCode)||(a.languageCode=Xu)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;t.skip(8);const o=on(t,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...$5},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=i,this.readContiguousBoxes(t.slice(n,r.contentSize))}break;case"stsd":{const a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;const o=te(t);t.skip(3);const l=vt(t);for(let u=0;u<l;u++){const c=t.filePos,d=aa(t);if(!d)break;a.internalCodecId=d.name;const f=d.name.toLowerCase();if(a.info.type==="video"){t.skip(6*1+2+2+2+3*4),a.info.width=zi(t),a.info.height=zi(t),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,t.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(t.slice(t.filePos,c+d.totalSize-t.filePos));const h=f==="encv"?a.frmaCodecString:f;a.frmaCodecString=null,h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":qa.includes(f)?(a.info.codec="prores",a.info.proresFormat=f):h===null?Jt._warn("Unknown encrypted video codec due to missing frma box."):Jt._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{t.skip(6*1+2);const h=zi(t);t.skip(3*2);let p=zi(t),g=zi(t);t.skip(2*2);let b=vt(t)/65536,w=null;o===0&&h>0&&(h===1?(t.skip(4),g=8*vt(t),t.skip(2*4)):h===2&&(t.skip(4),b=kA(t),p=vt(t),t.skip(4),g=vt(t),w=vt(t),t.skip(2*4))),a.info.numberOfChannels=p,a.info.sampleRate=b,a.frmaCodecString=null,this.readContiguousBoxes(t.slice(t.filePos,c+d.totalSize-t.filePos));const C=f==="enca"?a.frmaCodecString:f;if(a.frmaCodecString=null,C!=="mp4a")if(C==="opus")a.info.codec="opus",a.info.sampleRate=PE;else if(C==="flac")a.info.codec="flac";else if(C==="ulaw")a.info.codec="ulaw";else if(C==="alaw")a.info.codec="alaw";else if(C==="ac-3")a.info.codec="ac3";else if(C==="ec-3")a.info.codec="eac3";else if(Bh.includes(C))a.info.codec="dts",a.info.dtsFormat=C;else if(C==="twos")g===8?a.info.codec="pcm-s8":g===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(Jt._warn(`Unsupported sample size ${g} for codec 'twos'.`),a.info.codec=null);else if(C==="sowt")g===8?a.info.codec="pcm-s8":g===16?a.info.codec="pcm-s16":(Jt._warn(`Unsupported sample size ${g} for codec 'sowt'.`),a.info.codec=null);else if(C==="raw ")a.info.codec="pcm-u8";else if(C==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(C==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(C==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(C==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(C==="ipcm"){const x=a.info.pcmSampleSize;a.info.pcmLittleEndian?x===16?a.info.codec="pcm-s16":x===24?a.info.codec="pcm-s24":x===32?a.info.codec="pcm-s32":(Jt._warn(`Invalid ipcm sample size ${x}.`),a.info.codec=null):x===16?a.info.codec="pcm-s16be":x===24?a.info.codec="pcm-s24be":x===32?a.info.codec="pcm-s32be":(Jt._warn(`Invalid ipcm sample size ${x}.`),a.info.codec=null)}else if(C==="fpcm"){const x=a.info.pcmSampleSize;a.info.pcmLittleEndian?x===32?a.info.codec="pcm-f32":x===64?a.info.codec="pcm-f64":(Jt._warn(`Invalid fpcm sample size ${x}.`),a.info.codec=null):x===32?a.info.codec="pcm-f32be":x===64?a.info.codec="pcm-f64be":(Jt._warn(`Invalid fpcm sample size ${x}.`),a.info.codec=null)}else if(C==="lpcm"&&w!==null){const x=g+7>>3,_=!!(w&1),S=!!(w&2),k=w&4?-1:0;g>0&&g<=64&&(_?g===32&&(a.info.codec=S?"pcm-f32be":"pcm-f32"):k&1<<x-1?x===1?a.info.codec="pcm-s8":x===2?a.info.codec=S?"pcm-s16be":"pcm-s16":x===3?a.info.codec=S?"pcm-s24be":"pcm-s24":x===4&&(a.info.codec=S?"pcm-s32be":"pcm-s32"):x===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&Jt._warn("Unsupported PCM format.")}else C===null?Jt._warn("Unknown encrypted audio codec due to missing frma box."):Jt._warn(`Unsupported audio codec (sample entry type '${d.name}').`)}t.filePos=c+d.totalSize}}break;case"frma":{const a=this.currentTrack;if(!a)break;const l=on(t,4).toLowerCase();a.frmaCodecString=l}break;case"schm":{const a=this.currentTrack;if(!a)break;t.skip(4);const o=on(t,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:Jt._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=te(t);t.skip(3),t.skip(1);const l=te(t);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=l>>4,a.encryptionInfo.defaultSkipByteBlock=l&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=te(t)!==0,a.encryptionInfo.defaultPerSampleIvSize=te(t),a.encryptionInfo.defaultKid=Ku(Ce(t,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const u=te(t),c=new Uint8Array(16);c.set(Ce(t,u),0),a.encryptionInfo.defaultConstantIv=c}}break;case"avcC":{const a=this.currentTrack;if(!a||(M(a.info),r.contentSize===0))break;a.info.codecDescription=Ce(t,r.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a||(M(a.info),r.contentSize===0))break;a.info.codecDescription=Ce(t,r.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="video"),t.skip(4);const o=te(t),l=te(t),u=te(t),c=u>>4,d=u>>1&7,f=u&1,h=te(t),p=te(t),g=te(t);a.info.vp9CodecInfo={profile:o,level:l,bitDepth:c,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:h,transferCharacteristics:p,matrixCoefficients:g}}break;case"av1C":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="video"),t.skip(1);const o=te(t),l=o>>5,u=o&31,c=te(t),d=c>>7,f=c>>6&1,h=c>>5&1,p=c>>4&1,g=c>>3&1,b=c>>2&1,w=c&3,C=l===2&&f?h?12:10:f?10:8;t.skip(1);const x=Ce(t,r.contentSize-4),_=a1(x);a.info.av1CodecInfo={profile:l,level:u,tier:d,bitDepth:C,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:b,chromaSamplePosition:w,videoFullRangeFlag:_?.videoFullRangeFlag??0,colourPrimaries:_?.colourPrimaries??2,transferCharacteristics:_?.transferCharacteristics??2,matrixCoefficients:_?.matrixCoefficients??2}}break;case"colr":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="video");const o=on(t,4);if(o!=="nclx"&&o!=="nclc")break;const l=zi(t),u=zi(t),c=zi(t);let d;o==="nclx"&&(d=!!(te(t)&128)),a.info.colorSpace={primaries:Wa[l],transfer:Ha[u],matrix:Ga[c],fullRange:d}}break;case"pasp":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="video");const o=vt(t),l=vt(t);o>0&&l>0&&(o>l?a.info.squarePixelWidth=Math.round(a.info.width*o/l):a.info.squarePixelHeight=Math.round(a.info.height*l/o))}break;case"wave":this.readContiguousBoxes(t.slice(n,r.contentSize));break;case"esds":{const a=this.currentTrack;if(!a||a.info?.type!=="audio")break;t.skip(4);const o=te(t);M(o===3),f1(t),t.skip(2);const l=te(t),u=(l&128)!==0,c=(l&64)!==0,d=(l&32)!==0;if(u&&t.skip(2),c){const b=te(t);t.skip(b)}d&&t.skip(2);const f=te(t);M(f===4);const h=f1(t),p=t.filePos,g=te(t);if(g===64||g===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:g===103,objectType:null}):g===105||g===107?a.info.codec="mp3":g===221?a.info.codec="vorbis":g===169?a.info.codec="dts":Jt._warn(`Unsupported audio codec (objectTypeIndication ${g}) - discarding track.`),t.skip(12),h>t.filePos-p){const b=te(t);M(b===5);const w=f1(t);if(a.info.codecDescription=Ce(t,w),a.info.codec==="aac"){const C=Yy(a.info.codecDescription);C.outputNumberOfChannels!==null&&(a.info.numberOfChannels=C.outputNumberOfChannels),C.outputSampleRate!==null&&(a.info.sampleRate=C.outputSampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(zi(t)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),t.skip(4);const o=te(t);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=te(t)}break;case"dOps":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),t.skip(1);const o=te(t),l=zi(t),u=vt(t),c=M1(t),d=te(t);let f;d!==0?f=Ce(t,2+o):f=new Uint8Array(0);const h=new Uint8Array(19+f.byteLength),p=new DataView(h.buffer);p.setUint32(0,1332770163,!1),p.setUint32(4,1214603620,!1),p.setUint8(8,1),p.setUint8(9,o),p.setUint16(10,l,!0),p.setUint32(12,u,!0),p.setInt16(16,c,!0),p.setUint8(18,d),h.set(f,19),a.info.codecDescription=h,a.info.numberOfChannels=o}break;case"dfLa":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio"),t.skip(4);const o=127,l=128,u=t.filePos;for(;t.filePos<s;){const p=te(t),g=ca(t);if((p&o)===l1.STREAMINFO){t.skip(10);const w=vt(t),C=w>>>12,x=(w>>9&7)+1;a.info.sampleRate=C,a.info.numberOfChannels=x,t.skip(20)}else t.skip(g);if(p&l)break}const c=t.filePos;t.filePos=u;const d=Ce(t,c-u),f=new Uint8Array(4+d.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(d,4),a.info.codecDescription=f}break;case"dac3":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio");const o=Ce(t,3),l=new We(o),u=l.readBits(2);l.skipBits(8);const c=l.readBits(3),d=l.readBits(1);u<3&&(a.info.sampleRate=Qy[u]),a.info.numberOfChannels=vE[c]+d}break;case"dec3":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio");const o=Ce(t,r.contentSize),l=KX(o);if(!l){Jt._warn("Invalid dec3 box contents, ignoring.");break}const u=XX(l);u!==null&&(a.info.sampleRate=u),a.info.numberOfChannels=JX(l)}break;case"ddts":{const a=this.currentTrack;if(!a)break;M(a.info?.type==="audio");const o=Ce(t,Math.min(r.contentSize,u1)),l=hJ(o);if(!l){Jt._warn("Invalid ddts box contents, ignoring.");break}a.info.sampleRate=l.sampleRate,l.numberOfChannels!==null&&(a.info.numberOfChannels=l.numberOfChannels)}break;case"stts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);let l=0,u=0;for(let c=0;c<o;c++){const d=vt(t),f=vt(t);a.sampleTable.sampleTimingEntries.push({startIndex:l,startDecodeTimestamp:u,count:d,delta:f}),l+=d,u+=d*f}}break;case"ctts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);let l=0;for(let u=0;u<o;u++){const c=vt(t),d=io(t);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:l,count:c,offset:d}),l+=c}}break;case"stsz":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t),l=vt(t);if(o===0)for(let u=0;u<l;u++){const c=vt(t);a.sampleTable.sampleSizes.push(c)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4),t.skip(3);const o=te(t),l=vt(t),u=Ce(t,Math.ceil(l*o/8)),c=new We(u);for(let d=0;d<l;d++){const f=c.readBits(o);a.sampleTable.sampleSizes.push(f)}}break;case"stss":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4),a.sampleTable.keySampleIndices=[];const o=vt(t);for(let l=0;l<o;l++){const u=vt(t)-1;a.sampleTable.keySampleIndices.push(u)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);for(let u=0;u<o;u++){const c=vt(t)-1,d=vt(t),f=vt(t);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:c,samplesPerChunk:d,sampleDescriptionIndex:f})}let l=0;for(let u=0;u<a.sampleTable.sampleToChunk.length;u++)if(a.sampleTable.sampleToChunk[u].startSampleIndex=l,u<a.sampleTable.sampleToChunk.length-1){const d=a.sampleTable.sampleToChunk[u+1].startChunkIndex-a.sampleTable.sampleToChunk[u].startChunkIndex;l+=d*a.sampleTable.sampleToChunk[u].samplesPerChunk}}break;case"stco":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);for(let l=0;l<o;l++){const u=vt(t);a.sampleTable.chunkOffsets.push(u)}}break;case"co64":{const a=this.currentTrack;if(!a||!a.sampleTable)break;t.skip(4);const o=vt(t);for(let l=0;l<o;l++){const u=Er(t);a.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(t.slice(n,r.contentSize));break;case"mehd":{const a=te(t);t.skip(3);const o=a===1?Er(t):vt(t);this.movieDurationInTimescale=o}break;case"trex":{t.skip(4);const a=vt(t),o=vt(t),l=vt(t),u=vt(t),c=vt(t);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:l,defaultSampleSize:u,defaultSampleFlags:c})}break;case"tfra":{const a=te(t);t.skip(3);const o=vt(t),l=this.tracks.find(C=>C.id===o);if(!l)break;const u=vt(t),c=(u&48)>>4,d=(u&12)>>2,f=u&3,h=[te,zi,ca,vt],p=h[c],g=h[d],b=h[f],w=vt(t);for(let C=0;C<w;C++){const x=a===1?Er(t):vt(t),_=a===1?Er(t):vt(t);p(t),g(t),b(t),l.fragmentLookupTable.push({timestamp:x,moofOffset:_})}l.fragmentLookupTable.sort((C,x)=>C.timestamp-x.timestamp);for(let C=0;C<l.fragmentLookupTable.length-1;C++){const x=l.fragmentLookupTable[C],_=l.fragmentLookupTable[C+1];x.timestamp===_.timestamp&&(l.fragmentLookupTable.splice(C+1,1),C--)}}break;case"moof":this.currentFragment={moofOffset:i,moofSize:r.totalSize,implicitBaseDataOffset:i,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(t.slice(n,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(M(this.currentFragment),this.readContiguousBoxes(t.slice(n,r.contentSize)),this.currentTrack){const a=this.currentFragment.trackData.get(this.currentTrack.id);t:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break t}a.presentationTimestamps=a.samples.map((c,d)=>({presentationTimestamp:c.presentationTimestamp,sampleIndex:d})).sort((c,d)=>c.presentationTimestamp-d.presentationTimestamp);for(let c=0;c<a.presentationTimestamps.length;c++){const d=a.presentationTimestamps[c],f=a.samples[d.sampleIndex];if(a.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(a.firstKeyFrameTimestamp=f.presentationTimestamp),c<a.presentationTimestamps.length-1){const p=a.presentationTimestamps[c+1].presentationTimestamp-d.presentationTimestamp;f.duration=p}}const o=a.samples[a.presentationTimestamps[0].sampleIndex],l=a.samples[wi(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=l.presentationTimestamp+l.duration;const{currentFragmentState:u}=this.currentTrack;M(u),u.startTimestamp!==null&&(g1(a,u.startTimestamp),a.startTimestampIsFinal=!0),u.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=u.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;const a=IJ(Ce(t,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{M(this.currentFragment),t.skip(1);const a=ca(t),o=!!(a&1),l=!!(a&2),u=!!(a&8),c=!!(a&16),d=!!(a&32),f=!!(a&65536),h=!!(a&131072),p=vt(t),g=this.tracks.find(w=>w.id===p);if(!g)break;const b=this.fragmentTrackDefaults.find(w=>w.trackId===p);this.currentTrack=g,g.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:b?.defaultSampleDescriptionIndex??null,defaultSampleDuration:b?.defaultSampleDuration??null,defaultSampleSize:b?.defaultSampleSize??null,defaultSampleFlags:b?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?g.currentFragmentState.baseDataOffset=Er(t):h&&(g.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),l&&(g.currentFragmentState.sampleDescriptionIndex=vt(t)),u&&(g.currentFragmentState.defaultSampleDuration=vt(t)),c&&(g.currentFragmentState.defaultSampleSize=vt(t)),d&&(g.currentFragmentState.defaultSampleFlags=vt(t)),f&&(g.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const a=this.currentTrack;if(!a)break;M(a.currentFragmentState);const o=te(t);t.skip(3);const l=o===0?vt(t):Er(t);a.currentFragmentState.startTimestamp=l}break;case"trun":{const a=this.currentTrack;if(!a)break;M(this.currentFragment),M(a.currentFragmentState);const o=te(t),l=ca(t),u=!!(l&1),c=!!(l&4),d=!!(l&256),f=!!(l&512),h=!!(l&1024),p=!!(l&2048),g=vt(t);let b=null;u&&(b=io(t));let w=null;c&&(w=vt(t));let C;this.currentFragment.trackData.has(a.id)?(C=this.currentFragment.trackData.get(a.id),b!==null&&(C.currentOffset=a.currentFragmentState.baseDataOffset+b)):(C={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(b??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,C));for(let x=0;x<g;x++){let _;d?_=vt(t):(M(a.currentFragmentState.defaultSampleDuration!==null),_=a.currentFragmentState.defaultSampleDuration);let S;f?S=vt(t):(M(a.currentFragmentState.defaultSampleSize!==null),S=a.currentFragmentState.defaultSampleSize);let k;h?k=vt(t):(M(a.currentFragmentState.defaultSampleFlags!==null),k=a.currentFragmentState.defaultSampleFlags),x===0&&w!==null&&(k=w);let F=0;p&&(o===0?F=vt(t):F=io(t));const T=!(k&65536);C.samples.push({presentationTimestamp:C.currentTimestamp+F,duration:_,byteOffset:C.currentOffset,byteSize:S,isKeyFrame:T,encryption:null}),C.currentOffset+=S,C.currentTimestamp+=_}this.currentFragment.implicitBaseDataOffset=C.currentOffset}break;case"saiz":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(t.skip(1),ca(t)&1){const f=on(t,4),h=vt(t);if(f!==a.encryptionInfo.scheme||h!==0)break}const l=te(t),u=vt(t);let c=null;l===0&&u>0&&(c=Ce(t,u));const d=ZE(a);d.defaultSampleInfoSize=l,d.sampleSizes=c,d.sampleCount=u}break;case"saio":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=te(t);if(ca(t)&1){const f=on(t,4),h=vt(t);if(f!==a.encryptionInfo.scheme||h!==0)break}const u=vt(t);if(u===0)break;u>1&&Jt._warn("Multiple saio entries are not supported; using the first offset only.");let c=o===0?vt(t):Number(Er(t));this.currentFragment&&(c+=this.currentFragment.moofOffset);const d=ZE(a);d.offset=c}break;case"senc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;M(this.currentFragment);const o=this.currentFragment.trackData.get(a.id);if(!o)break;t.skip(1);const u=!!(ca(t)&2),c=vt(t),d=a.encryptionInfo.defaultPerSampleIvSize;M(d!==null);for(let f=0;f<Math.min(c,o.samples.length);f++){const h=new Uint8Array(16);d>0?h.set(Ce(t,d),0):h.set(a.encryptionInfo.defaultConstantIv,0);let p=null;if(u){const b=zi(t);p=[];for(let w=0;w<b;w++){const C=zi(t),x=vt(t);p.push({clearLen:C,protectedLen:x})}}const g=o.samples[f];g.encryption={iv:h,subsamples:p}}}break;case"udta":{const a=this.iterateContiguousBoxes(t.slice(n,r.contentSize));for(const{boxInfo:o,slice:l}of a){if(o.name!=="meta"&&!this.currentTrack){const u=l.filePos;this.metadataTags.raw??={},o.name[0]==="©"?this.metadataTags.raw[o.name]??=$n(l):this.metadataTags.raw[o.name]??=Ce(l,o.contentSize),l.filePos=u}switch(o.name){case"meta":l.skip(-o.headerSize),this.traverseBox(l);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=il.decode(Ce(l,o.contentSize)):this.metadataTags.title??=$n(l);break;case"©des":this.currentTrack||(this.metadataTags.description??=$n(l));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=$n(l));break;case"©alb":this.currentTrack||(this.metadataTags.album??=$n(l));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=$n(l));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=$n(l));break;case"©day":if(!this.currentTrack){const u=new Date($n(l));Number.isNaN(u.getTime())||(this.metadataTags.date??=u)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=$n(l));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=$n(l));break}}}break;case"meta":{if(this.currentTrack)break;const o=vt(t)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(t.slice(n,r.contentSize)):this.readContiguousBoxes(t.slice(n+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;t.skip(4);const a=vt(t);for(let o=0;o<a;o++){const l=vt(t);t.skip(4);const u=il.decode(Ce(t,l-8));this.currentMetadataKeys.set(o+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const a=this.iterateContiguousBoxes(t.slice(n,r.contentSize));for(const{boxInfo:o,slice:l}of a){let u=o.name;const c=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(c)&&(u=this.currentMetadataKeys.get(c));const d=PJ(l);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=d,u){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"©lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){const f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof al?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){const f=d.split("/"),h=Number.parseInt(f[0],10),p=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){const f=Me(d),h=f.getUint16(2,!1),p=f.getUint16(4,!1);h>0&&(this.metadataTags.trackNumber??=h),p>0&&(this.metadataTags.tracksTotal??=p)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){const f=Me(d),h=f.getUint16(2,!1),p=f.getUint16(4,!1);h>0&&(this.metadataTags.discNumber??=h),p>0&&(this.metadataTags.discsTotal??=p)}break}}}break}return t.filePos=s,!0}}class VE{constructor(t){this.internalTrack=t,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const t=this.internalTrack.demuxer,i=this.internalTrack.trackBacking.getType();let r=0;for(const n of t.tracks)if(n.trackBacking.getType()===i&&r++,n===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const t=this.internalTrack;return t.durationInMediaTimescale<=0?null:(M(t.trackBacking),((await t.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+t.durationInMediaTimescale/t.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(t){const i=await this.fetchPacketForSampleIndex(0,t);return i||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,t)}mapTimestampIntoTimescale(t){return Y5(t*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(t,i){const r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=m1(n,r),a=await this.fetchPacketForSampleIndex(s,i);return!UE(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const l=o.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};const u=Ze(l.presentationTimestamps,r,f=>f.presentationTimestamp),c=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<l.endTimestamp;return{sampleIndex:c,correctSampleFound:d}},r,r,i)}async getNextPacket(t,i){const r=this.packetToSampleIndex.get(t);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,i);const n=this.packetToFragmentLocation.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const a=s.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<a.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,i)}async getKeyPacket(t,i){const r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=NJ(n,r),a=await this.fetchPacketForSampleIndex(s,i);return!UE(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const l=o.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};const u=H5(l.presentationTimestamps,f=>l.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=r),c=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<l.endTimestamp;return{sampleIndex:c,correctSampleFound:d}},r,r,i)}async getNextKeyPacket(t,i){const r=this.packetToSampleIndex.get(t);if(r!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=zJ(s,r);return this.fetchPacketForSampleIndex(a,i)}const n=this.packetToFragmentLocation.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const o=s.trackData.get(this.internalTrack.id).samples.findIndex((l,u)=>l.isKeyFrame&&u>n.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(l=>l.isKeyFrame);return M(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,i)}async fetchPacketForSampleIndex(t,i){if(t===-1)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=MJ(r,t);if(!n)return null;let s;if(i.metadataOnly)s=ll;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(Lt(u)&&(u=await u),!u)return null;if(s=Ce(u,n.sampleSize),this.internalTrack.encryptionInfo){let c=null;if(this.internalTrack.encryptionAuxInfo){const d=await jE(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);t<d.length&&(c=d[t])}c??=WE(this.internalTrack.encryptionInfo),c&&(s=await HE(this.internalTrack,c,s,null))}}const a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,l=new fi(s,n.isKeyFrame?"key":"delta",a,o,t,n.sampleSize);return this.packetToSampleIndex.set(l,t),l}async fetchPacketInFragment(t,i,r){if(i===-1)return null;const s=t.trackData.get(this.internalTrack.id).samples[i];M(s);let a;if(r.metadataOnly)a=ll;else{let c=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(Lt(c)&&(c=await c),!c)return null;if(a=Ce(c,s.byteSize),this.internalTrack.encryptionInfo){const d=s.encryption??WE(this.internalTrack.encryptionInfo);d&&(a=await HE(this.internalTrack,d,a,t))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=s.duration/this.internalTrack.timescale,u=new fi(a,s.isKeyFrame?"key":"delta",o,l,t.moofOffset+i,s.byteSize);return this.packetToFragmentLocation.set(u,{fragment:t,sampleIndex:i}),u}async performFragmentedLookup(t,i,r,n,s){const a=this.internalTrack.demuxer;let o=null,l=null,u=-1;if(t){const{sampleIndex:b,correctSampleFound:w}=i(t);if(w)return this.fetchPacketInFragment(t,b,s);b!==-1&&(l=t,u=b)}const c=Ze(this.internalTrack.fragmentLookupTable,r,b=>b.timestamp),d=c!==-1?this.internalTrack.fragmentLookupTable[c]:null,f=Ze(this.internalTrack.fragmentPositionCache,r,b=>b.startTimestamp),h=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max(d?.moofOffset??0,h?.moofOffset??0)||null;let g;for(t?p===null||t.moofOffset>=p?(g=t.moofOffset+t.moofSize,o=t):g=p:g=p??0;;){if(o){const x=o.trackData.get(this.internalTrack.id);if(x&&x.startTimestamp>n)break}let b=a.reader.requestSliceRange(g,ds,Ya);if(Lt(b)&&(b=await b),!b)break;const w=g,C=aa(b);if(!C)break;if(C.name==="moof"){o=await a.readFragment(w);const{sampleIndex:x,correctSampleFound:_}=i(o);if(_)return this.fetchPacketInFragment(o,x,s);x!==-1&&(l=o,u=x)}g=w+C.totalSize}if(d&&(!l||l.moofOffset<d.moofOffset)){const b=this.internalTrack.fragmentLookupTable[c-1];M(!b||b.timestamp<d.timestamp);const w=b?.timestamp??-1/0;return this.performFragmentedLookup(null,i,w,n,s)}return l?this.fetchPacketInFragment(l,u,s):null}}class LE extends VE{constructor(t){super(t),this.decoderConfigPromise=null,this.internalTrack=t}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}getRotation(){return this.internalTrack.rotation}async getColorSpace(){const t=await this.getDecoderConfig();return t?{primaries:t.colorSpace?.primaries,transfer:t.colorSpace?.transfer,matrix:t.colorSpace?.matrix,fullRange:t.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){const i=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=i&&r1(i.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const i=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=i&&s1(i.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!jX(this.internalTrack.info.vp9CodecInfo))){const i=await this.getFirstPacket({}),r=i&&gE(i.data);r&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??r,videoFullRangeFlag:r.videoFullRangeFlag,colourPrimaries:r.colourPrimaries,transferCharacteristics:r.transferCharacteristics,matrixCoefficients:r.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!WX(this.internalTrack.info.av1CodecInfo))){const i=await this.getFirstPacket({}),r=i&&a1(i.data);r&&(this.internalTrack.info.av1CodecInfo=r)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){const i=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=i&&bE(i.data)}if(!Dy(this.internalTrack.info.colorSpace)){const i=IE(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=i.primaries,this.internalTrack.info.colorSpace.transfer??=i.transfer,this.internalTrack.info.colorSpace.matrix??=i.matrix,this.internalTrack.info.colorSpace.fullRange??=i.fullRange}const t={codec:TE(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)&&(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})():null}}class $E extends VE{constructor(t){super(t),this.decoderConfigPromise=null,this.internalTrack=t}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){const t=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=t&&kE(t.data)}return{codec:DE(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const m1=(e,t)=>{if(e.presentationTimestamps){const i=Ze(e.presentationTimestamps,t,r=>r.presentationTimestamp);return i===-1?-1:e.presentationTimestamps[i].sampleIndex}else{const i=Ze(e.sampleTimingEntries,t,n=>n.startDecodeTimestamp);if(i===-1)return-1;const r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},NJ=(e,t)=>{if(!e.keySampleIndices)return m1(e,t);if(e.presentationTimestamps){const i=Ze(e.presentationTimestamps,t,r=>r.presentationTimestamp);if(i===-1)return-1;for(let r=i;r>=0;r--){const n=e.presentationTimestamps[r].sampleIndex;if(j5(e.keySampleIndices,n,a=>a)!==-1)return n}return-1}else{const i=m1(e,t),r=Ze(e.keySampleIndices,i,n=>n);return e.keySampleIndices[r]??-1}},MJ=(e,t)=>{const i=Ze(e.sampleTimingEntries,t,w=>w.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let s=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const a=Ze(e.sampleCompositionTimeOffsets,t,w=>w.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(s+=o.offset);const l=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],u=Ze(e.sampleToChunk,t,w=>w.startSampleIndex),c=e.sampleToChunk[u];M(c);const d=c.startChunkIndex+Math.floor((t-c.startSampleIndex)/c.samplesPerChunk),f=e.chunkOffsets[d],h=c.startSampleIndex+(d-c.startChunkIndex)*c.samplesPerChunk;let p=0,g=f;if(e.sampleSizes.length===1)g+=l*(t-h),p+=l*c.samplesPerChunk;else for(let w=h;w<h+c.samplesPerChunk;w++){const C=e.sampleSizes[w];w<t&&(g+=C),p+=C}let b=r.delta;if(e.presentationTimestamps){const w=e.presentationTimestampIndexMap[t];M(w!==void 0),w<e.presentationTimestamps.length-1&&(b=e.presentationTimestamps[w+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:b,sampleOffset:g,sampleSize:l,chunkOffset:f,chunkSize:p,isKeyFrame:e.keySampleIndices?j5(e.keySampleIndices,t,w=>w)!==-1:!0}},zJ=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=Ze(e.keySampleIndices,t,r=>r);return e.keySampleIndices[i+1]??-1},g1=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const i of e.samples)i.presentationTimestamp+=t;for(const i of e.presentationTimestamps)i.presentationTimestamp+=t},OJ=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},UE=e=>e.sampleSizes.length===0,ZE=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},jE=async(e,t,i)=>{if(i.resolved)return i.resolved;if(i.offset===null||i.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{M(i.sampleSizes);for(let o=0;o<i.sampleCount;o++)r+=i.sampleSizes[o]}let n=e.requestSlice(i.offset,r);if(Lt(n)&&(n=await n),!n)throw new Error("Failed to read auxiliary encryption info.");const s=t.defaultPerSampleIvSize;M(s!==null);const a=[];for(let o=0;o<i.sampleCount;o++){const l=i.defaultSampleInfoSize>0?i.defaultSampleInfoSize:i.sampleSizes[o],u=new Uint8Array(16);s>0?u.set(Ce(n,s),0):u.set(t.defaultConstantIv,0);let c=null;if(l>s){const d=zi(n);c=[];for(let f=0;f<d;f++){const h=zi(n),p=vt(n);c.push({clearLen:h,protectedLen:p})}}a.push({iv:u,subsamples:c})}return i.resolved=a,a},WE=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,HE=async(e,t,i,r)=>{M(e.encryptionInfo);const n=e.encryptionInfo;M(n.defaultKid!==null);const s=n.defaultKid;let a;const o=e.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const l=(async()=>{let u=e.demuxer.psshBoxes;if(r){u=[...u,...r.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(s));for(let d=0;d<u.length-1;d++)for(let f=d+1;f<u.length;f++)DJ(u[d],u[f])&&(u.splice(f,1),f--)}const c=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:u});if(!(typeof c=="string"&&c.length===32&&yX.test(c)||c instanceof Uint8Array&&c.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return c instanceof Uint8Array?c:bX(c)})();e.demuxer.decryptionKeyCache.set(s,l),a=await l}return n.scheme==="cenc"||n.scheme==="cens"?RJ(a,n,t,i):VJ(a,n,t,i)},RJ=async(e,t,i,r)=>{const n=new Uint8Array(16);n.set(i.iv,0);const s=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const g=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,p);return new Uint8Array(g)};if(!i.subsamples)return a(r);M(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);const o=GE(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const p of o)for(const g of p.perSubsample)l+=g.length;const u=new Uint8Array(l);let c=0;for(const p of o)for(const g of p.perSubsample)u.set(r.subarray(g.offset,g.offset+g.length),c),c+=g.length;const d=await a(u),f=new Uint8Array(r);let h=0;for(const p of o)for(const g of p.perSubsample)f.set(d.subarray(h,h+g.length),g.offset),h+=g.length;return f},VJ=(e,t,i,r)=>{const n=new BJ;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(M(s!==null&&a!==null),!i.subsamples){const c=new Uint8Array(r),d=Math.floor(r.length/16);for(let f=0;f<d;f++){const h=f*16;n.in.set(r.subarray(h,h+16)),n.decrypt(),c.set(n.out,h)}return c}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(r),l=GE(i.subsamples,s,a),u=new DataView(i.iv.buffer,i.iv.byteOffset,16);for(const c of l){n.iv[0]=u.getUint32(0,!1),n.iv[1]=u.getUint32(4,!1),n.iv[2]=u.getUint32(8,!1),n.iv[3]=u.getUint32(12,!1);for(const d of c.perSubsample){const f=d.length/16;for(let h=0;h<f;h++){const p=d.offset+h*16;n.in.set(r.subarray(p,p+16)),n.decrypt(),o.set(n.out,p)}}}return o},GE=(e,t,i)=>{const r=[],n=t!==0||i!==0;let s=0;for(const a of e){s+=a.clearLen;const o=[];if(!n)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let l=a.protectedLen,u=s;for(;l>0&&!(l<16*t);){const c=16*t;o.push({offset:u,length:c}),u+=c,l-=c;const d=Math.min(16*i,l);u+=d,l-=d}s+=a.protectedLen}r.push({perSubsample:o})}return r};/*!
|
|
476
476
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
477
477
|
*
|
|
478
478
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
@@ -538,7 +538,7 @@ ${t.stack}`:t),this.createFallbackGraphic()}}async mountIframe(t){const i=this.c
|
|
|
538
538
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
539
539
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
540
540
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
541
|
-
*/const Qa=e=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.metadataOnly!==void 0&&typeof e.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},to=e=>{if(!Ju(e))throw new TypeError("timestamp must be a number.")},I1=(e,t,i)=>i.verifyKeyPackets?t.then(async r=>{if(!r||r.type==="delta")return r;const n=await e.determinePacketType(r);return n&&(r.type=n),r}):t;class D1{constructor(t){if(!(t instanceof hc))throw new TypeError("track must be an InputTrack.");this._track=t}async getFirstPacket(t={}){if(Qa(t),this._track.input._disposed)throw new ji;return I1(this._track,this._track._backing.getFirstPacket(t),t)}async getFirstKeyPacket(t={}){Qa(t);const i=await this.getFirstPacket(t);return i?i.type==="key"?i:this.getNextKeyPacket(i,t):null}async getPacket(t,i={}){if(to(t),Qa(i),this._track.input._disposed)throw new ji;return I1(this._track,this._track._backing.getPacket(t,i),i)}async getNextPacket(t,i={}){if(!(t instanceof fi))throw new TypeError("packet must be an EncodedPacket.");if(Qa(i),this._track.input._disposed)throw new ji;return I1(this._track,this._track._backing.getNextPacket(t,i),i)}async getKeyPacket(t,i={}){if(to(t),Qa(i),this._track.input._disposed)throw new ji;if(!i.verifyKeyPackets)return this._track._backing.getKeyPacket(t,i);const r=await this._track._backing.getKeyPacket(t,i);return r&&(M(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),i):r)}async getNextKeyPacket(t,i={}){if(!(t instanceof fi))throw new TypeError("packet must be an EncodedPacket.");if(Qa(i),this._track.input._disposed)throw new ji;if(!i.verifyKeyPackets)return this._track._backing.getNextKeyPacket(t,i);const r=await this._track._backing.getNextKeyPacket(t,i);return r&&(M(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,i):r)}packets(t,i,r={}){if(t!==void 0&&!(t instanceof fi))throw new TypeError("startPacket must be an EncodedPacket.");if(t!==void 0&&t.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(i!==void 0&&!(i instanceof fi))throw new TypeError("endPacket must be an EncodedPacket.");if(Qa(r),this._track.input._disposed)throw new ji;const n=[];let{promise:s,resolve:a}=ki(),{promise:o,resolve:l}=ki(),u=!1,c=!1,d=null,f=!1;const h=[],p=()=>Math.max(2,h.length);(async()=>{let b=t??await this.getFirstPacket(r);for(;b&&!c&&!this._track.input._disposed&&!(i&&b.sequenceNumber>=i?.sequenceNumber);){if(n.length>p()){({promise:o,resolve:l}=ki()),await o;continue}n.push(b),a(),{promise:s,resolve:a}=ki(),b=await this.getNextPacket(b,r)}u=!0,a()})().catch(b=>{f||(d=b,f=!0,a())});const g=this._track;return{async next(){for(;;){if(g.input._disposed)throw new ji;if(c)return{value:void 0,done:!0};if(f)throw d;if(n.length>0){const b=n.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return l(),{value:b,done:!1}}else{if(u)return{value:void 0,done:!0};await s}}},async return(){return c=!0,l(),a(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}}class NQ{constructor(t,i){this.onSample=t,this.onError=i}}class MQ{mediaSamplesInRange(t=-1/0,i=1/0,r){to(t),to(i);const n=[];let s=!1,a=null,{promise:o,resolve:l}=ki(),{promise:u,resolve:c}=ki(),d=!1,f=!1,h=!1,p=null,g=null,b=!1;const w={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(P=>{if(c(),P.timestamp>=i&&(f=!0),f){P.close();return}a&&(P.timestamp>t?(n.push(a),s=!0):a.close()),P.timestamp>=t&&(n.push(P),s=!0),a=s?null:P,n.length>0&&(l(),{promise:o,resolve:l}=ki())},P=>{b||(g=P,b=!0,l())});const _=this._createPacketSink(),S=await _.getKeyPacket(t,w)??await _.getFirstKeyPacket(w);let k=S;const T=_.packets(S??void 0,void 0,w);for(await T.next();k&&!f&&!this._track.input._disposed;){const P=yA(n.length);if(n.length+p.getDecodeQueueSize()>P){({promise:u,resolve:c}=ki()),await u;continue}p.decode(k);const I=await T.next();if(I.done)break;k=I.value}await T.return(),!h&&!this._track.input._disposed&&await p.flush(),!s&&a&&n.push(a),d=!0,l()})().catch(_=>{b||(g=_,b=!0,l())}).finally(()=>{p?.close()});const C=this._track,x=()=>{a?.close();for(const _ of n)_.close()};return{async next(){for(;;){if(C.input._disposed)throw x(),new ji;if(h)return{value:void 0,done:!0};if(b)throw x(),g;if(n.length>0){const _=n.shift();return c(),{value:_,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,f=!0,c(),l(),x(),{value:void 0,done:!0}},async throw(_){throw _},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t,i){wX(t);const r=vX(t),n=[],s=[];let{promise:a,resolve:o}=ki(),{promise:l,resolve:u}=ki(),c=!1,d=!1,f=null,h=null,p=!1;const g=x=>{s.push(x),o(),{promise:a,resolve:o}=ki()},b={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(P=>{if(u(),d){P.close();return}let I=0;for(;n.length>0&&P.timestamp-n[0]>-1e-10;)I++,n.shift();if(I>0)for(let O=0;O<I;O++)g(O<I-1?P.clone():P);else P.close()},P=>{p||(h=P,p=!0,o())});const x=this._createPacketSink();let _=null,S=null,k=-1;const F=async()=>{M(S),M(f);let P=S;for(f.decode(P);P.sequenceNumber<k;){const I=yA(s.length);for(;s.length+f.getDecodeQueueSize()>I&&!d;)({promise:l,resolve:u}=ki()),await l;if(d)break;const O=await x.getNextPacket(P,b);M(O),f.decode(O),P=O}k=-1},T=async()=>{M(f),await f.flush();for(let P=0;P<n.length;P++)g(null);n.length=0};for await(const P of r){if(to(P),d||this._track.input._disposed)break;const I=await x.getPacket(P,b),O=I&&await x.getKeyPacket(P,b);if(!O){k!==-1&&(await F(),await T()),g(null),_=null;continue}_&&(O.sequenceNumber!==S.sequenceNumber||I.timestamp<_.timestamp)&&(await F(),await T()),n.push(I.timestamp),k=Math.max(I.sequenceNumber,k),_=I,S=O}!d&&!this._track.input._disposed&&(k!==-1&&await F(),await T()),c=!0,o()})().catch(x=>{p||(h=x,p=!0,o())}).finally(()=>{f?.close()});const w=this._track,C=()=>{for(const x of s)x?.close()};return{async next(){for(;;){if(w.input._disposed)throw C(),new ji;if(d)return{value:void 0,done:!0};if(p)throw C(),h;if(s.length>0){const x=s.shift();return M(x!==void 0),u(),{value:x,done:!1}}else if(!c)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),C(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}}const yA=e=>e===0?40:8;class zQ extends NQ{constructor(t,i,r,n,s,a){super(t,i),this.codec=r,this.decoderConfig=n,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ry,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const o=gA.find(l=>l.supports(r,n));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=n,this.customDecoder.onSample=l=>{if(!(l instanceof Zi))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoder.onError=l=>{i(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>i(l));else{const l=c=>{if(this.alphaQueue.length>0){const d=this.alphaQueue.shift();M(d!==void 0),this.mergeAlpha(c,d)}else this.colorQueue.push(c)};if(Zy()){if(r==="avc"&&this.decoderConfig.description){const c=dE(er(this.decoderConfig.description));if(c&&c.sequenceParameterSets.length>0){const d=n1(c.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}Dy(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:c=>{try{l(c)}catch(d){this.onError(d)}},error:c=>{c.stack=u,this.onError(c)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(M(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(t){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(t.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).catch(i=>this.onError(i)).finally(()=>this.customDecoderQueueSize--);else{if(M(this.decoder),Eh()||W5(this.inputTimestamps,t.timestamp,i=>i),Zy()&&this.currentPacketIndex===0){if(this.codec==="avc"){const i=[];let r=!1;for(const s of uE(t.data,this.decoderConfig)){const a=t1(t.data[s.offset]);if(r||=a>=1&&a<=5,a===Ln.AUD){if(r)break;i.length=0}a>=20&&a<=31||i.push(t.data.subarray(s.offset,s.offset+s.length))}const n=PX(i,this.decoderConfig);t=new fi(n,t.type,t.timestamp,t.duration)}else if(this.codec==="hevc"){const i=UX(t.data,this.decoderConfig);i&&(t=new fi(i,t.type,t.timestamp,t.duration))}}this.decoder.decode(t.toEncodedVideoChunk()),this.decodeAlphaData(t)}this.currentPacketIndex++}decodeAlphaData(t){if(!t.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new OQ),!this.alphaDecoder){const r=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();M(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();M(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},n=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{r(s)}catch(a){this.onError(a)}},error:s=>{s.stack=n,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}const i=o1(this.codec,this.decoderConfig,t.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=i==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(t.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(t.alphaToEncodedVideoChunk(i??t.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(t){for(const i of Dh(t,this.decoderConfig)){const r=ic(t[i.offset]);if(r===$i.RASL_N||r===$i.RASL_R)return!0}return!1}sampleHandler(t){if(Eh()){if(this.sampleQueue.length>0&&t.timestamp>=wi(this.sampleQueue).timestamp){for(const i of this.sampleQueue)this.finalizeAndEmitSample(i);this.sampleQueue.length=0}W5(this.sampleQueue,t,i=>i.timestamp)}else{const i=this.inputTimestamps.shift();M(i!==void 0),t.setTimestamp(i),this.finalizeAndEmitSample(t)}}finalizeAndEmitSample(t){t.setTimestamp(Math.round(t.timestamp*this.timeResolution)/this.timeResolution),t.setDuration(Math.round(t.duration*this.timeResolution)/this.timeResolution),t.setRotation(this.rotation),this.onSample(t)}async mergeAlpha(t,i){const r=ki();this.mergeAlphaPromises.push(r.promise);const n={sample:null};this.finalSamples.push(n);try{if(!i)n.sample=new Zi(t);else{M(this.merger);const s=await this.merger.merge(t,i);n.sample=new Zi(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Py(this.finalSamples,n),this.onError(s)}finally{Py(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(M(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Eh()){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(M(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t?.close()),this.alphaQueue.length=0,this.merger?.close());for(const t of this.sampleQueue)t.close();this.sampleQueue.length=0}}let P1=null;class OQ{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(t,i){if(this.workers.length===0){if(!P1){const o=new Blob([`(${RQ.toString()})()`],{type:"application/javascript"});P1=URL.createObjectURL(o)}const a=di(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const l=new Worker(P1);l.addEventListener("message",u=>{const c=u.data,d=this.pendingRequests.get(c.id);d&&(this.pendingRequests.delete(c.id),"error"in c?d.reject(new Error(c.error)):d.resolve(c.frame))}),l.addEventListener("error",u=>{const c=new Error(u.message||"Color/alpha merge worker error.");for(const d of this.pendingRequests.values())d.reject(c);this.pendingRequests.clear()}),this.workers.push(l)}}const r=this.nextRequestId++,n=ki();this.pendingRequests.set(r,n);const s=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,s.postMessage({id:r,color:t,alpha:i},{transfer:[t,i]}),n.promise}close(){for(const i of this.workers)i.terminate();this.workers.length=0;const t=new Error("Color/alpha merger closed.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}}const RQ=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",l=>{const{id:u,color:c,alpha:d}=l.data;i=i.then(async()=>{try{const f=await r(c,d);self.postMessage({id:u,frame:f},{transfer:[f]})}catch(f){self.postMessage({id:u,error:f.message})}finally{c.close(),d.close()}})});const r=async(l,u)=>{const c=l.format,d=u.format;if(!c||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const f=c.includes("P10"),h=c.includes("P12"),p=d.includes("P10"),g=d.includes("P12");if(p!==f||g!==h)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${c}', alpha: '${d}').`);if(c==="RGBX"||c==="RGBA"||c==="BGRX"||c==="BGRA")return await n(l,u,c);if(c==="I420"||c==="I420P10"||c==="I420P12"||c==="I422"||c==="I422P10"||c==="I422P12"||c==="I444"||c==="I444P10"||c==="I444P12")return await s(l,u,c);if(c==="NV12")return await a(l,u);throw new Error(`CPU color/alpha merging does not support format '${c}'.`)},n=async(l,u,c)=>{const d=l.visibleRect?.width??l.codedWidth,f=l.visibleRect?.height??l.codedHeight,h=d*f,p=new Uint8Array(h*4);await l.copyTo(p);const g=await o(u,d,f,1);for(let C=0,x=3;C<h;C++,x+=4)p[x]=g[C];const w={format:c==="RGBX"||c==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:f,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,w)},s=async(l,u,c)=>{const d=l.visibleRect?.width??l.codedWidth,f=l.visibleRect?.height??l.codedHeight,h=c.includes("P10"),p=c.includes("P12"),g=h||p?2:1;let b,w;c.startsWith("I420")?(b=Math.ceil(d/2),w=Math.ceil(f/2)):c.startsWith("I422")?(b=Math.ceil(d/2),w=f):(b=d,w=f);const C=d*f,x=b*w,_=C*g,S=x*g,k=C*g,F=_+2*S+k,T=new Uint8Array(F);await l.copyTo(T);const P=await o(u,d,f,g),I=_+2*S;T.set(P,I);const z={format:c.slice(0,4)+"A"+c.slice(4),codedWidth:d,codedHeight:f,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[T.buffer]};return new VideoFrame(T,z)},a=async(l,u)=>{const c=l.visibleRect?.width??l.codedWidth,d=l.visibleRect?.height??l.codedHeight,f=c*d,h=Math.ceil(c/2),p=Math.ceil(d/2),g=h*p,b=l.allocationSize();(!t||t.byteLength!==b)&&(t=new Uint8Array(b)),await l.copyTo(t);const w=new Uint8Array(f+2*g+f);w.set(t.subarray(0,f),0);const C=f,x=f+g,_=f;for(let F=0;F<g;F++)w[C+F]=t[_+F*2],w[x+F]=t[_+F*2+1];const S=await o(u,c,d,1);w.set(S,f+2*g);const k={format:"I420A",codedWidth:c,codedHeight:d,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[w.buffer]};return new VideoFrame(w,k)},o=async(l,u,c,d)=>{const f=l.allocationSize();(!e||e.byteLength!==f)&&(e=new Uint8Array(f)),await l.copyTo(e);const h=l.format;if(h==="RGBA"||h==="BGRA"||h==="RGBX"||h==="BGRX"){const p=h==="RGBA"||h==="RGBX"?0:2,g=u*c;for(let b=0;b<g;b++)e[b]=e[b*4+p];return e.subarray(0,g)}else return e.subarray(0,u*c*d)}},bA=e=>{if(!e||typeof e!="object")throw new TypeError("decoderOptions must be an object.");if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class VQ extends MQ{constructor(t,i={}){if(!(t instanceof $h))throw new TypeError("videoTrack must be an InputVideoTrack.");bA(i),super(),this._track=t,this._decoderOptions=i}async _createDecoder(t,i){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(jy("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),n=await this._track.getRotation();let s=await this._track.getDecoderConfig();const a=await this._track.getTimeResolution();return M(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new zQ(t,i,r,s,n,a)}_createPacketSink(){return new D1(this._track)}async getSample(t,i={}){to(t);for await(const r of this.mediaSamplesAtTimestamps([t],i))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,i,r={}){return this.mediaSamplesInRange(t,i,r)}samplesAtTimestamps(t,i={}){return this.mediaSamplesAtTimestamps(t,i)}}class LQ{constructor(t,i={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(t instanceof $h))throw new TypeError("videoTrack must be an InputVideoTrack.");if(i&&typeof i!="object")throw new TypeError("options must be an object.");if(i.alpha!==void 0&&typeof i.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(i.width!==void 0&&(!Number.isInteger(i.width)||i.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(i.height!==void 0&&(!Number.isInteger(i.height)||i.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(i.fit!==void 0&&!["fill","contain","cover"].includes(i.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.width!==void 0&&i.height!==void 0&&i.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(i.rotation!==void 0&&![0,90,180,270].includes(i.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(i.crop!==void 0&&Rh(i.crop,"options."),i.poolSize!==void 0&&(typeof i.poolSize!="number"||!Number.isInteger(i.poolSize)||i.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");i.decoderOptions!==void 0&&bA(i.decoderOptions),this._videoTrack=t,this._alpha=i.alpha??!1,this._options=i,this._fit=i.fit??"fill",this._videoSampleSink=new VQ(t,i.decoderOptions),this._canvasPool=Array.from({length:i.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{const t=this._options,i=this._videoTrack,r=t.rotation??await i.getRotation(),n=await i.getSquarePixelWidth(),s=await i.getSquarePixelHeight(),[a,o]=r%180===0?[n,s]:[s,n];let l=t.crop;l&&(l=A1(l,a,o));let[u,c]=l?[l.width,l.height]:[a,o];const d=u/c;t.width!==void 0&&t.height===void 0?(u=t.width,c=Math.round(u/d)):t.width===void 0&&t.height!==void 0?(c=t.height,u=Math.round(c*d)):t.width!==void 0&&t.height!==void 0&&(u=t.width,c=t.height),this._width=u,this._height=c,this._rotation=r,this._crop=l})()}_videoSampleToWrappedCanvas(t){const i=this._width,r=this._height;let n=this._canvasPool[this._nextCanvasIndex],s=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=i,n.height=r):n=new OffscreenCanvas(i,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=n.getContext("2d",{alpha:this._alpha||$y()});M(a),t._drawWithFitAndMipmapping(n,a,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:s,fillBlack:!this._alpha&&$y()});const o={canvas:n,timestamp:t.timestamp,duration:t.duration};return t.close(),o}async getCanvas(t,i){to(t),await this._ensureInit();const r=await this._videoSampleSink.getSample(t,i);return r&&this._videoSampleToWrappedCanvas(r)}async*canvases(t,i,r){await this._ensureInit(),yield*q5(this._videoSampleSink.samples(t,i,r),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(t,i){await this._ensureInit(),yield*q5(this._videoSampleSink.samplesAtTimestamps(t,i),r=>r&&this._videoSampleToWrappedCanvas(r))}}/*!
|
|
541
|
+
*/const Qa=e=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.metadataOnly!==void 0&&typeof e.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},to=e=>{if(!Ju(e))throw new TypeError("timestamp must be a number.")},I1=(e,t,i)=>i.verifyKeyPackets?t.then(async r=>{if(!r||r.type==="delta")return r;const n=await e.determinePacketType(r);return n&&(r.type=n),r}):t;class D1{constructor(t){if(!(t instanceof hc))throw new TypeError("track must be an InputTrack.");this._track=t}async getFirstPacket(t={}){if(Qa(t),this._track.input._disposed)throw new ji;return I1(this._track,this._track._backing.getFirstPacket(t),t)}async getFirstKeyPacket(t={}){Qa(t);const i=await this.getFirstPacket(t);return i?i.type==="key"?i:this.getNextKeyPacket(i,t):null}async getPacket(t,i={}){if(to(t),Qa(i),this._track.input._disposed)throw new ji;return I1(this._track,this._track._backing.getPacket(t,i),i)}async getNextPacket(t,i={}){if(!(t instanceof fi))throw new TypeError("packet must be an EncodedPacket.");if(Qa(i),this._track.input._disposed)throw new ji;return I1(this._track,this._track._backing.getNextPacket(t,i),i)}async getKeyPacket(t,i={}){if(to(t),Qa(i),this._track.input._disposed)throw new ji;if(!i.verifyKeyPackets)return this._track._backing.getKeyPacket(t,i);const r=await this._track._backing.getKeyPacket(t,i);return r&&(M(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),i):r)}async getNextKeyPacket(t,i={}){if(!(t instanceof fi))throw new TypeError("packet must be an EncodedPacket.");if(Qa(i),this._track.input._disposed)throw new ji;if(!i.verifyKeyPackets)return this._track._backing.getNextKeyPacket(t,i);const r=await this._track._backing.getNextKeyPacket(t,i);return r&&(M(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,i):r)}packets(t,i,r={}){if(t!==void 0&&!(t instanceof fi))throw new TypeError("startPacket must be an EncodedPacket.");if(t!==void 0&&t.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(i!==void 0&&!(i instanceof fi))throw new TypeError("endPacket must be an EncodedPacket.");if(Qa(r),this._track.input._disposed)throw new ji;const n=[];let{promise:s,resolve:a}=ki(),{promise:o,resolve:l}=ki(),u=!1,c=!1,d=null,f=!1;const h=[],p=()=>Math.max(2,h.length);(async()=>{let b=t??await this.getFirstPacket(r);for(;b&&!c&&!this._track.input._disposed&&!(i&&b.sequenceNumber>=i?.sequenceNumber);){if(n.length>p()){({promise:o,resolve:l}=ki()),await o;continue}n.push(b),a(),{promise:s,resolve:a}=ki(),b=await this.getNextPacket(b,r)}u=!0,a()})().catch(b=>{f||(d=b,f=!0,a())});const g=this._track;return{async next(){for(;;){if(g.input._disposed)throw new ji;if(c)return{value:void 0,done:!0};if(f)throw d;if(n.length>0){const b=n.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return l(),{value:b,done:!1}}else{if(u)return{value:void 0,done:!0};await s}}},async return(){return c=!0,l(),a(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}}class NQ{constructor(t,i){this.onSample=t,this.onError=i}}class MQ{mediaSamplesInRange(t=-1/0,i=1/0,r){to(t),to(i);const n=[];let s=!1,a=null,{promise:o,resolve:l}=ki(),{promise:u,resolve:c}=ki(),d=!1,f=!1,h=!1,p=null,g=null,b=!1;const w={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(P=>{if(c(),P.timestamp>=i&&(f=!0),f){P.close();return}a&&(P.timestamp>t?(n.push(a),s=!0):a.close()),P.timestamp>=t&&(n.push(P),s=!0),a=s?null:P,n.length>0&&(l(),{promise:o,resolve:l}=ki())},P=>{b||(g=P,b=!0,l())});const _=this._createPacketSink(),S=await _.getKeyPacket(t,w)??await _.getFirstKeyPacket(w);let k=S;const T=_.packets(S??void 0,void 0,w);for(await T.next();k&&!f&&!this._track.input._disposed;){const P=yA(n.length);if(n.length+p.getDecodeQueueSize()>P){({promise:u,resolve:c}=ki()),await u;continue}p.decode(k);const I=await T.next();if(I.done)break;k=I.value}await T.return(),!h&&!this._track.input._disposed&&await p.flush(),!s&&a&&n.push(a),d=!0,l()})().catch(_=>{b||(g=_,b=!0,l())}).finally(()=>{p?.close()});const C=this._track,x=()=>{a?.close();for(const _ of n)_.close()};return{async next(){for(;;){if(C.input._disposed)throw h=!0,f=!0,x(),new ji;if(h)return{value:void 0,done:!0};if(b)throw h=!0,f=!0,x(),g;if(n.length>0){const _=n.shift();return c(),{value:_,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,f=!0,c(),l(),x(),{value:void 0,done:!0}},async throw(_){throw _},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t,i){wX(t);const r=vX(t),n=[],s=[];let{promise:a,resolve:o}=ki(),{promise:l,resolve:u}=ki(),c=!1,d=!1,f=null,h=null,p=!1;const g=x=>{s.push(x),o(),{promise:a,resolve:o}=ki()},b={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(P=>{if(u(),d){P.close();return}let I=0;for(;n.length>0&&P.timestamp-n[0]>-1e-10;)I++,n.shift();if(I>0)for(let O=0;O<I;O++)g(O<I-1?P.clone():P);else P.close()},P=>{p||(h=P,p=!0,o())});const x=this._createPacketSink();let _=null,S=null,k=-1;const F=async()=>{M(S),M(f);let P=S;for(f.decode(P);P.sequenceNumber<k;){const I=yA(s.length);for(;s.length+f.getDecodeQueueSize()>I&&!d;)({promise:l,resolve:u}=ki()),await l;if(d)break;const O=await x.getNextPacket(P,b);M(O),f.decode(O),P=O}k=-1},T=async()=>{M(f),await f.flush();for(let P=0;P<n.length;P++)g(null);n.length=0};for await(const P of r){if(to(P),d||this._track.input._disposed)break;const I=await x.getPacket(P,b),O=I&&await x.getKeyPacket(P,b);if(!O){k!==-1&&(await F(),await T()),g(null),_=null;continue}_&&(O.sequenceNumber!==S.sequenceNumber||I.timestamp<_.timestamp)&&(await F(),await T()),n.push(I.timestamp),k=Math.max(I.sequenceNumber,k),_=I,S=O}!d&&!this._track.input._disposed&&(k!==-1&&await F(),await T()),c=!0,o()})().catch(x=>{p||(h=x,p=!0,o())}).finally(()=>{f?.close()});const w=this._track,C=()=>{for(const x of s)x?.close()};return{async next(){for(;;){if(w.input._disposed)throw d=!0,C(),new ji;if(d)return{value:void 0,done:!0};if(p)throw d=!0,C(),h;if(s.length>0){const x=s.shift();return M(x!==void 0),u(),{value:x,done:!1}}else if(!c)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),C(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}}const yA=e=>e===0?40:8;class zQ extends NQ{constructor(t,i,r,n,s,a){super(t,i),this.codec=r,this.decoderConfig=n,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ry,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const o=gA.find(l=>l.supports(r,n));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=n,this.customDecoder.onSample=l=>{if(!(l instanceof Zi))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoder.onError=l=>{i(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>i(l));else{const l=c=>{if(this.alphaQueue.length>0){const d=this.alphaQueue.shift();M(d!==void 0),this.mergeAlpha(c,d)}else this.colorQueue.push(c)};if(Zy()){if(r==="avc"&&this.decoderConfig.description){const c=dE(er(this.decoderConfig.description));if(c&&c.sequenceParameterSets.length>0){const d=n1(c.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}Dy(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:c=>{try{l(c)}catch(d){this.onError(d)}},error:c=>{c.stack=u,this.onError(c)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(M(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(t){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(t.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).catch(i=>this.onError(i)).finally(()=>this.customDecoderQueueSize--);else{if(M(this.decoder),Eh()||W5(this.inputTimestamps,t.timestamp,i=>i),Zy()&&this.currentPacketIndex===0){if(this.codec==="avc"){const i=[];let r=!1;for(const s of uE(t.data,this.decoderConfig)){const a=t1(t.data[s.offset]);if(r||=a>=1&&a<=5,a===Ln.AUD){if(r)break;i.length=0}a>=20&&a<=31||i.push(t.data.subarray(s.offset,s.offset+s.length))}const n=PX(i,this.decoderConfig);t=new fi(n,t.type,t.timestamp,t.duration)}else if(this.codec==="hevc"){const i=UX(t.data,this.decoderConfig);i&&(t=new fi(i,t.type,t.timestamp,t.duration))}}this.decoder.decode(t.toEncodedVideoChunk()),this.decodeAlphaData(t)}this.currentPacketIndex++}decodeAlphaData(t){if(!t.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new OQ),!this.alphaDecoder){const r=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();M(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();M(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},n=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{r(s)}catch(a){this.onError(a)}},error:s=>{s.stack=n,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}const i=o1(this.codec,this.decoderConfig,t.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=i==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(t.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(t.alphaToEncodedVideoChunk(i??t.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(t){for(const i of Dh(t,this.decoderConfig)){const r=ic(t[i.offset]);if(r===$i.RASL_N||r===$i.RASL_R)return!0}return!1}sampleHandler(t){if(Eh()){if(this.sampleQueue.length>0&&t.timestamp>=wi(this.sampleQueue).timestamp){for(const i of this.sampleQueue)this.finalizeAndEmitSample(i);this.sampleQueue.length=0}W5(this.sampleQueue,t,i=>i.timestamp)}else{const i=this.inputTimestamps.shift();M(i!==void 0),t.setTimestamp(i),this.finalizeAndEmitSample(t)}}finalizeAndEmitSample(t){t.setTimestamp(Math.round(t.timestamp*this.timeResolution)/this.timeResolution),t.setDuration(Math.round(t.duration*this.timeResolution)/this.timeResolution),t.setRotation(this.rotation),this.onSample(t)}async mergeAlpha(t,i){const r=ki();this.mergeAlphaPromises.push(r.promise);const n={sample:null};this.finalSamples.push(n);try{if(!i)n.sample=new Zi(t);else{M(this.merger);const s=await this.merger.merge(t,i);n.sample=new Zi(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Py(this.finalSamples,n),this.onError(s)}finally{Py(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(M(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Eh()){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(M(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t?.close()),this.alphaQueue.length=0,this.merger?.close());for(const t of this.sampleQueue)t.close();this.sampleQueue.length=0}}let P1=null;class OQ{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(t,i){if(this.workers.length===0){if(!P1){const o=new Blob([`(${RQ.toString()})()`],{type:"application/javascript"});P1=URL.createObjectURL(o)}const a=di(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const l=new Worker(P1);l.addEventListener("message",u=>{const c=u.data,d=this.pendingRequests.get(c.id);d&&(this.pendingRequests.delete(c.id),"error"in c?d.reject(new Error(c.error)):d.resolve(c.frame))}),l.addEventListener("error",u=>{const c=new Error(u.message||"Color/alpha merge worker error.");for(const d of this.pendingRequests.values())d.reject(c);this.pendingRequests.clear()}),this.workers.push(l)}}const r=this.nextRequestId++,n=ki();this.pendingRequests.set(r,n);const s=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,s.postMessage({id:r,color:t,alpha:i},{transfer:[t,i]}),n.promise}close(){for(const i of this.workers)i.terminate();this.workers.length=0;const t=new Error("Color/alpha merger closed.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}}const RQ=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",l=>{const{id:u,color:c,alpha:d}=l.data;i=i.then(async()=>{try{const f=await r(c,d);self.postMessage({id:u,frame:f},{transfer:[f]})}catch(f){self.postMessage({id:u,error:f.message})}finally{c.close(),d.close()}})});const r=async(l,u)=>{const c=l.format,d=u.format;if(!c||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const f=c.includes("P10"),h=c.includes("P12"),p=d.includes("P10"),g=d.includes("P12");if(p!==f||g!==h)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${c}', alpha: '${d}').`);if(c==="RGBX"||c==="RGBA"||c==="BGRX"||c==="BGRA")return await n(l,u,c);if(c==="I420"||c==="I420P10"||c==="I420P12"||c==="I422"||c==="I422P10"||c==="I422P12"||c==="I444"||c==="I444P10"||c==="I444P12")return await s(l,u,c);if(c==="NV12")return await a(l,u);throw new Error(`CPU color/alpha merging does not support format '${c}'.`)},n=async(l,u,c)=>{const d=l.visibleRect?.width??l.codedWidth,f=l.visibleRect?.height??l.codedHeight,h=d*f,p=new Uint8Array(h*4);await l.copyTo(p);const g=await o(u,d,f,1);for(let C=0,x=3;C<h;C++,x+=4)p[x]=g[C];const w={format:c==="RGBX"||c==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:f,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,w)},s=async(l,u,c)=>{const d=l.visibleRect?.width??l.codedWidth,f=l.visibleRect?.height??l.codedHeight,h=c.includes("P10"),p=c.includes("P12"),g=h||p?2:1;let b,w;c.startsWith("I420")?(b=Math.ceil(d/2),w=Math.ceil(f/2)):c.startsWith("I422")?(b=Math.ceil(d/2),w=f):(b=d,w=f);const C=d*f,x=b*w,_=C*g,S=x*g,k=C*g,F=_+2*S+k,T=new Uint8Array(F);await l.copyTo(T);const P=await o(u,d,f,g),I=_+2*S;T.set(P,I);const z={format:c.slice(0,4)+"A"+c.slice(4),codedWidth:d,codedHeight:f,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[T.buffer]};return new VideoFrame(T,z)},a=async(l,u)=>{const c=l.visibleRect?.width??l.codedWidth,d=l.visibleRect?.height??l.codedHeight,f=c*d,h=Math.ceil(c/2),p=Math.ceil(d/2),g=h*p,b=l.allocationSize();(!t||t.byteLength!==b)&&(t=new Uint8Array(b)),await l.copyTo(t);const w=new Uint8Array(f+2*g+f);w.set(t.subarray(0,f),0);const C=f,x=f+g,_=f;for(let F=0;F<g;F++)w[C+F]=t[_+F*2],w[x+F]=t[_+F*2+1];const S=await o(u,c,d,1);w.set(S,f+2*g);const k={format:"I420A",codedWidth:c,codedHeight:d,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[w.buffer]};return new VideoFrame(w,k)},o=async(l,u,c,d)=>{const f=l.allocationSize();(!e||e.byteLength!==f)&&(e=new Uint8Array(f)),await l.copyTo(e);const h=l.format;if(h==="RGBA"||h==="BGRA"||h==="RGBX"||h==="BGRX"){const p=h==="RGBA"||h==="RGBX"?0:2,g=u*c;for(let b=0;b<g;b++)e[b]=e[b*4+p];return e.subarray(0,g)}else return e.subarray(0,u*c*d)}},bA=e=>{if(!e||typeof e!="object")throw new TypeError("decoderOptions must be an object.");if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class VQ extends MQ{constructor(t,i={}){if(!(t instanceof $h))throw new TypeError("videoTrack must be an InputVideoTrack.");bA(i),super(),this._track=t,this._decoderOptions=i}async _createDecoder(t,i){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(jy("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),n=await this._track.getRotation();let s=await this._track.getDecoderConfig();const a=await this._track.getTimeResolution();return M(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new zQ(t,i,r,s,n,a)}_createPacketSink(){return new D1(this._track)}async getSample(t,i={}){to(t);for await(const r of this.mediaSamplesAtTimestamps([t],i))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,i,r={}){return this.mediaSamplesInRange(t,i,r)}samplesAtTimestamps(t,i={}){return this.mediaSamplesAtTimestamps(t,i)}}class LQ{constructor(t,i={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(t instanceof $h))throw new TypeError("videoTrack must be an InputVideoTrack.");if(i&&typeof i!="object")throw new TypeError("options must be an object.");if(i.alpha!==void 0&&typeof i.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(i.width!==void 0&&(!Number.isInteger(i.width)||i.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(i.height!==void 0&&(!Number.isInteger(i.height)||i.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(i.fit!==void 0&&!["fill","contain","cover"].includes(i.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.width!==void 0&&i.height!==void 0&&i.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(i.rotation!==void 0&&![0,90,180,270].includes(i.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(i.crop!==void 0&&Rh(i.crop,"options."),i.poolSize!==void 0&&(typeof i.poolSize!="number"||!Number.isInteger(i.poolSize)||i.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");i.decoderOptions!==void 0&&bA(i.decoderOptions),this._videoTrack=t,this._alpha=i.alpha??!1,this._options=i,this._fit=i.fit??"fill",this._videoSampleSink=new VQ(t,i.decoderOptions),this._canvasPool=Array.from({length:i.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{const t=this._options,i=this._videoTrack,r=t.rotation??await i.getRotation(),n=await i.getSquarePixelWidth(),s=await i.getSquarePixelHeight(),[a,o]=r%180===0?[n,s]:[s,n];let l=t.crop;l&&(l=A1(l,a,o));let[u,c]=l?[l.width,l.height]:[a,o];const d=u/c;t.width!==void 0&&t.height===void 0?(u=t.width,c=Math.round(u/d)):t.width===void 0&&t.height!==void 0?(c=t.height,u=Math.round(c*d)):t.width!==void 0&&t.height!==void 0&&(u=t.width,c=t.height),this._width=u,this._height=c,this._rotation=r,this._crop=l})()}_videoSampleToWrappedCanvas(t){const i=this._width,r=this._height;let n=this._canvasPool[this._nextCanvasIndex],s=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=i,n.height=r):n=new OffscreenCanvas(i,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=n.getContext("2d",{alpha:this._alpha||$y()});M(a),t._drawWithFitAndMipmapping(n,a,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:s,fillBlack:!this._alpha&&$y()});const o={canvas:n,timestamp:t.timestamp,duration:t.duration};return t.close(),o}async getCanvas(t,i){to(t),await this._ensureInit();const r=await this._videoSampleSink.getSample(t,i);return r&&this._videoSampleToWrappedCanvas(r)}async*canvases(t,i,r){await this._ensureInit(),yield*q5(this._videoSampleSink.samples(t,i,r),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(t,i){await this._ensureInit(),yield*q5(this._videoSampleSink.samplesAtTimestamps(t,i),r=>r&&this._videoSampleToWrappedCanvas(r))}}/*!
|
|
542
542
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
543
543
|
*
|
|
544
544
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
@@ -893,7 +893,7 @@ Please check your media files.`}class rT{element;options;currentState=null;curre
|
|
|
893
893
|
<button class="ss-transition-speed-btn" data-speed-increase>+</button>
|
|
894
894
|
</div>
|
|
895
895
|
</div>
|
|
896
|
-
`}bindElements(){this.tabButtons=this.container?.querySelectorAll("[data-tab]")??null,this.effectButtons=this.container?.querySelectorAll("[data-effect]")??null,this.directionRow=this.container?.querySelector("[data-direction-row]")??null,this.directionButtons=this.container?.querySelectorAll("[data-dir]")??null,this.speedLabel=this.container?.querySelector(".ss-transition-speed-value")??null,this.speedDecreaseBtn=this.container?.querySelector("[data-speed-decrease]")??null,this.speedIncreaseBtn=this.container?.querySelector("[data-speed-increase]")??null}setupEvents(){this.events.onAll(this.tabButtons,"click",(t,i)=>{this.state.tab=i.dataset.tab,this.updateUI()}),this.events.onAll(this.effectButtons,"click",(t,i)=>{const r=i.dataset.effect??"";this.setCurrentEffect(r),this.updateUI(),this.emit(this.state)}),this.events.onAll(this.directionButtons,"click",(t,i)=>{const r=i.dataset.dir??"";this.setCurrentDirection(r),this.updateUI(),this.emit(this.state)}),this.events.on(this.speedDecreaseBtn,"click",t=>{t.stopPropagation(),this.stepSpeed(-1)}),this.events.on(this.speedIncreaseBtn,"click",t=>{t.stopPropagation(),this.stepSpeed(1)})}setFromClip(t){const i=this.parseTransitionValue(t?.in??""),r=this.parseTransitionValue(t?.out??"");this.state.inEffect=i.effect,this.state.inDirection=i.direction,this.state.inSpeed=i.speed,this.state.outEffect=r.effect,this.state.outDirection=r.direction,this.state.outSpeed=r.speed,this.updateUI()}getClipValue(){const t=this.buildTransitionValue(this.state.inEffect,this.state.inDirection,this.state.inSpeed),i=this.buildTransitionValue(this.state.outEffect,this.state.outDirection,this.state.outSpeed);if(!t&&!i)return;const r={};return t&&(r.in=t),i&&(r.out=i),r}getState(){return{...this.state}}setCurrentEffect(t){this.state.tab==="in"?(this.state.inEffect=t,this.state.inDirection=this.needsDirection(t)?"Right":""):(this.state.outEffect=t,this.state.outDirection=this.needsDirection(t)?"Right":"")}setCurrentDirection(t){this.state.tab==="in"?this.state.inDirection=t:this.state.outDirection=t}stepSpeed(t){const i=fn.SPEEDS,
|
|
896
|
+
`}bindElements(){this.tabButtons=this.container?.querySelectorAll("[data-tab]")??null,this.effectButtons=this.container?.querySelectorAll("[data-effect]")??null,this.directionRow=this.container?.querySelector("[data-direction-row]")??null,this.directionButtons=this.container?.querySelectorAll("[data-dir]")??null,this.speedLabel=this.container?.querySelector(".ss-transition-speed-value")??null,this.speedDecreaseBtn=this.container?.querySelector("[data-speed-decrease]")??null,this.speedIncreaseBtn=this.container?.querySelector("[data-speed-increase]")??null}setupEvents(){this.events.onAll(this.tabButtons,"click",(t,i)=>{this.state.tab=i.dataset.tab,this.updateUI()}),this.events.onAll(this.effectButtons,"click",(t,i)=>{const r=i.dataset.effect??"";this.setCurrentEffect(r),this.updateUI(),this.emit(this.state)}),this.events.onAll(this.directionButtons,"click",(t,i)=>{const r=i.dataset.dir??"";this.setCurrentDirection(r),this.updateUI(),this.emit(this.state)}),this.events.on(this.speedDecreaseBtn,"click",t=>{t.stopPropagation(),this.stepSpeed(-1)}),this.events.on(this.speedIncreaseBtn,"click",t=>{t.stopPropagation(),this.stepSpeed(1)})}setFromClip(t){const i=this.parseTransitionValue(t?.in??""),r=this.parseTransitionValue(t?.out??"");this.state.inEffect=i.effect,this.state.inDirection=i.direction,this.state.inSpeed=i.speed,this.state.outEffect=r.effect,this.state.outDirection=r.direction,this.state.outSpeed=r.speed,this.updateUI()}getClipValue(){const t=this.buildTransitionValue(this.state.inEffect,this.state.inDirection,this.state.inSpeed),i=this.buildTransitionValue(this.state.outEffect,this.state.outDirection,this.state.outSpeed);if(!t&&!i)return;const r={};return t&&(r.in=t),i&&(r.out=i),r}getState(){return{...this.state}}setCurrentEffect(t){this.state.tab==="in"?(this.state.inEffect=t,this.state.inDirection=this.needsDirection(t)?"Right":""):(this.state.outEffect=t,this.state.outDirection=this.needsDirection(t)?"Right":"")}setCurrentDirection(t){this.state.tab==="in"?this.state.inDirection=t:this.state.outDirection=t}stepSpeed(t){const i=this.state.tab==="in"?this.state.inEffect:this.state.outEffect;if(!this.supportsSpeedVariants(i))return;const r=fn.SPEEDS,n=this.state.tab==="in"?this.state.inSpeed:this.state.outSpeed;let s=r.indexOf(n);s===-1&&(s=r.findIndex(l=>l>=n),s===-1&&(s=r.length-1));const a=Math.max(0,Math.min(r.length-1,s+t)),o=r[a];this.state.tab==="in"?this.state.inSpeed=o:this.state.outSpeed=o,this.updateUI(),this.emit(this.state)}needsDirection(t){return["slide","wipe","carousel"].includes(t)}supportsSpeedVariants(t){return!!t&&t!=="zoom"}updateUI(){const{tab:t}=this.state,i=t==="in"?this.state.inEffect:this.state.outEffect,r=t==="in"?this.state.inDirection:this.state.outDirection,n=t==="in"?this.state.inSpeed:this.state.outSpeed;this.tabButtons?.forEach(l=>{l.classList.toggle("active",l.dataset.tab===t)}),this.effectButtons?.forEach(l=>{l.classList.toggle("active",l.dataset.effect===i)});const s=this.needsDirection(i);this.directionRow?.classList.toggle("visible",s),this.directionButtons?.forEach(l=>{const u=l.dataset.dir??"";l.classList.toggle("hidden",i==="wipe"&&(u==="Up"||u==="Down")),l.classList.toggle("active",u===r)}),this.speedLabel&&(this.speedLabel.textContent=`${n.toFixed(2)}s`);const a=this.supportsSpeedVariants(i),o=fn.SPEEDS.indexOf(n);this.speedDecreaseBtn&&(this.speedDecreaseBtn.disabled=!a||o<=0),this.speedIncreaseBtn&&(this.speedIncreaseBtn.disabled=!a||o>=fn.SPEEDS.length-1)}parseTransitionValue(t){if(!t)return{effect:"",direction:"",speed:1};let i="",r=t;t.endsWith("Fast")?(i="Fast",r=t.slice(0,-4)):t.endsWith("Slow")&&(i="Slow",r=t.slice(0,-4));const n=["Left","Right","Up","Down"];for(const a of n)if(r.endsWith(a)){const o=r.slice(0,-a.length),l=this.suffixToSpeed(i,o);return{effect:o,direction:a,speed:l}}const s=this.suffixToSpeed(i,r);return{effect:r,direction:"",speed:s}}buildTransitionValue(t,i,r){if(!t)return"";const n=this.speedToSuffix(r,t);return this.needsDirection(t)?t+i+n:t+n}speedToSuffix(t,i){if(!this.supportsSpeedVariants(i))return"";if(i==="slide"||i==="carousel"){if(t===.5)return"";if(t===1)return"Slow";if(t===.25)return"Fast";if(t===2)return"Slow"}else{if(t===1)return"";if(t===2)return"Slow";if(t===.5||t===.25)return"Fast"}return""}suffixToSpeed(t,i){if(i==="slide"||i==="carousel"){if(t==="")return .5;if(t==="Slow")return 1;if(t==="Fast")return .25}else{if(t==="")return 1;if(t==="Slow")return 2;if(t==="Fast")return .5}return 1}directionIcon(t){return{Left:"←",Right:"→",Up:"↑",Down:"↓"}[t]??""}}const Mit=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));class Cc{sessions=new Map;start(t,i,r){this.sessions.set(t,{clipId:i,initialState:Mit(r),startTime:Date.now()})}get(t){return this.sessions.get(t)??null}end(t){const i=this.sessions.get(t);return this.sessions.delete(t),i??null}clear(t){if(t)for(const[i,r]of this.sessions.entries())r.clipId===t&&this.sessions.delete(i);else this.sessions.clear()}isDragging(t){return this.sessions.has(t)}}class zit extends ha{constructor(t){super({className:"ss-scrollable-list",...t}),this.listConfig=t,this.groups=t.groups,this.height=t.height??300,this.selectedValue=t.selectedValue}viewport=null;selectedValue;groups;height;mount(t){super.mount(t),this.container&&(this.container.style.height=`${this.height}px`)}render(){return`
|
|
897
897
|
<div class="ss-scrollable-list-body">
|
|
898
898
|
<div class="ss-scrollable-list-viewport">
|
|
899
899
|
${this.renderGroups()}
|
package/package.json
CHANGED
package/readme.md
CHANGED
|
@@ -16,6 +16,28 @@ Try Shotstack Studio in your preferred framework:
|
|
|
16
16
|
[](https://stackblitz.com/fork/github/shotstack/shotstack-studio-sdk-demos/tree/master/angular)
|
|
17
17
|
[](https://stackblitz.com/fork/github/shotstack/shotstack-studio-sdk-demos/tree/master/nextjs)
|
|
18
18
|
|
|
19
|
+
## Create a new project
|
|
20
|
+
|
|
21
|
+
The fastest way to get started is to scaffold a project. This creates a small app with the Studio SDK already set up, including the canvas, timeline, and controls.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm create video-editor@latest
|
|
25
|
+
# or
|
|
26
|
+
npx create-video-editor
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
You'll be asked for a project name and a framework. The CLI then scaffolds the app, installs dependencies, starts the dev server, and opens a live editor in your browser.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
npx create-video-editor my-video-editor
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
To skip the prompts, pass the project directory and framework directly:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npx create-video-editor my-editor --template react --yes
|
|
39
|
+
```
|
|
40
|
+
|
|
19
41
|
## Features
|
|
20
42
|
|
|
21
43
|
- Template-driven editing with undo/redo command model
|
|
@@ -26,6 +48,8 @@ Try Shotstack Studio in your preferred framework:
|
|
|
26
48
|
|
|
27
49
|
## Installation
|
|
28
50
|
|
|
51
|
+
To add the SDK to an existing app, install it directly:
|
|
52
|
+
|
|
29
53
|
```bash
|
|
30
54
|
npm install @shotstack/shotstack-studio
|
|
31
55
|
```
|