1var Ki=Object.defineProperty;var Xi=(n,a,h)=>a in n?Ki(n,a,{enumerable:!0,configurable:!0,writable:!0,value:h}):n[a]=h;var Se=(n,a,h)=>Xi(n,typeof a!="symbol"?a+"":a,h);import{r as ut,j as y}from"./react-CBsl08bt.js";import{c as Jt,B as qt,ax as Zi,_ as Qi}from"./index-Znlz9Whf.js";import{S as Ji}from"./switch-Bbk9eQq_.js";import{br as tr,a7 as er,d as gi,c as oi,D as he,bu as ir,S as rr,b as nr,aj as yi,a5 as sr,r as Te,bM as ar,R as or}from"./icons-CgIhAgVC.js";import{f as je,a as Fe,l as lr}from"./ffmpegCore-CrM75I6F.js";const hr=[{id:"vugola",name:"Vugola Bold",position:"bottom",uppercase:!0,textClassName:"font-extrabold text-white text-2xl sm:text-3xl tracking-tight",textStyle:{WebkitTextStroke:"2px #000",textShadow:"0 4px 14px rgba(0,0,0,0.85)"},canvas:{fontScale:.072,weight:800,fill:"#FFFFFF",stroke:"#000000",strokeScale:.12,shadowBlurScale:.25,shadowColor:"rgba(0,0,0,0.85)"}},{id:"karaoke",name:"Karaoke Pop",position:"bottom",uppercase:!0,karaoke:!0,textClassName:"font-extrabold text-white text-2xl sm:text-3xl tracking-tight",textStyle:{WebkitTextStroke:"2px #000",textShadow:"0 3px 12px rgba(0,0,0,0.8)"},highlightStyle:{color:"#FACC15",WebkitTextStroke:"2px #000"},canvas:{fontScale:.072,weight:800,fill:"#FFFFFF",stroke:"#000000",strokeScale:.12,shadowBlurScale:.22,shadowColor:"rgba(0,0,0,0.8)",highlightFill:"#FACC15"}},{id:"neon",name:"Neon",position:"bottom",textClassName:"font-bold text-cyan-300 text-2xl sm:text-3xl",textStyle:{textShadow:"0 0 8px #22d3ee, 0 0 20px #06b6d4"},canvas:{fontScale:.066,weight:700,fill:"#67E8F9",glow:!0,shadowBlurScale:.4,shadowColor:"#06b6d4"}},{id:"minimal",name:"Minimal",position:"bottom",textClassName:"font-semibold text-white text-xl sm:text-2xl",textStyle:{textShadow:"0 2px 10px rgba(0,0,0,0.95)"},canvas:{fontScale:.058,weight:600,fill:"#FFFFFF",shadowBlurScale:.3,shadowColor:"rgba(0,0,0,0.95)"}},{id:"highlight-box",name:"Highlight Box",position:"bottom",uppercase:!0,karaoke:!0,boxColor:"#EC4899",boxActiveWordOnly:!0,textClassName:"font-extrabold text-white text-2xl sm:text-3xl tracking-tight",textStyle:{WebkitTextStroke:"1.5px #000",textShadow:"0 3px 10px rgba(0,0,0,0.7)"},highlightStyle:{color:"#FFFFFF"},canvas:{fontScale:.07,weight:800,fill:"#FFFFFF",stroke:"#000000",strokeScale:.09,shadowBlurScale:.18,shadowColor:"rgba(0,0,0,0.7)",boxColor:"#EC4899",boxActiveWordOnly:!0,highlightFill:"#FFFFFF"}},{id:"hive-brand",name:"Hive Brand",position:"bottom",uppercase:!0,karaoke:!0,boxColor:"#A4123C",boxColorAlt:"#F2B33A",boxActiveWordOnly:!0,textClassName:"font-extrabold italic text-white text-2xl sm:text-3xl tracking-tight",textStyle:{fontStyle:"italic",WebkitTextStroke:"2px #0A0204",textShadow:"0 4px 14px rgba(0,0,0,0.85)"},highlightStyle:{color:"#F2B33A",WebkitTextStroke:"2px #0A0204"},highlightStyleAlt:{color:"#3D0512",WebkitTextStroke:"2px #0A0204"},canvas:{fontScale:.072,weight:800,italic:!0,fill:"#FFFFFF",stroke:"#0A0204",strokeScale:.13,shadowBlurScale:.22,shadowColor:"rgba(0,0,0,0.85)",boxColor:"#A4123C",boxColorAlt:"#F2B33A",highlightFill:"#F2B33A",highlightFillAlt:"#3D0512",boxActiveWordOnly:!0}},{id:"pop-yellow",name:"Pop Yellow",position:"bottom",uppercase:!0,karaoke:!0,textClassName:"font-extrabold text-white text-2xl sm:text-3xl tracking-tight",textStyle:{WebkitTextStroke:"2px #000",textShadow:"0 3px 12px rgba(0,0,0,0.85)"},highlightStyle:{color:"#FACC15",WebkitTextStroke:"2px #000"},canvas:{fontScale:.072,weight:800,fill:"#FFFFFF",stroke:"#000000",strokeScale:.12,shadowBlurScale:.22,shadowColor:"rgba(0,0,0,0.85)",highlightFill:"#FACC15"}}],dr=[{id:"top",name:"Top",frac:.16},{id:"center",name:"Middle",frac:.5},{id:"bottom",name:"Bottom",frac:.84}],Ue=n=>1-Math.pow(1-Math.min(1,Math.max(0,n)),3),Be=[{id:"pop",name:"Pop",className:"animate-in zoom-in-95 fade-in duration-200",canvas:n=>({scale:.82+.18*Ue(n),dy:0,opacity:Math.min(1,n*3)})},{id:"fade",name:"Fade",className:"animate-in fade-in duration-300",canvas:n=>({scale:1,dy:0,opacity:Math.min(1,n*2)})},{id:"slide-up",name:"Slide Up",className:"animate-in slide-in-from-bottom-4 fade-in duration-300",canvas:n=>({scale:1,dy:(1-Ue(n))*.6,opacity:Math.min(1,n*2.5)})}
1,{id:"bounce",name:"Bounce",className:"animate-in zoom-in-50 fade-in duration-300",canvas:n=>{const a=Ue(n),h=Math.sin(Math.min(1,n)*Math.PI)*.12;return{scale:.7+.3*a+h,dy:0,opacity:Math.min(1,n*3)}}},{id:"pop-word",name:"Word Pop",className:"animate-in fade-in duration-150",perWord:!0,canvas:n=>({scale:1,dy:0,opacity:Math.min(1,n*4)})},{id:"none",name:"None",className:"",canvas:()=>({scale:1,dy:0,opacity:1})}];function xi(n){return Be.find(a=>a.id===n)??Be[0]}function vi(n){const a=n.trim().split(/\s+/).filter(Boolean),h=[];let l=[],f=0;for(const d of a)(l.length>=5||f+d.length+1>42&&l.length>0)&&(h.push(l),l=[],f=0),l.push(d),f+=d.length+1,/[.,!?;:]$/.test(d)&&l.length>=2&&(h.push(l),l=[],f=0);return l.length&&h.push(l),h}function Cs(n){const a=[];let h=[],l=0;const f=()=>{h.length&&(a.push({words:h.map(d=>d.word),start:h[0].start,end:h[h.length-1].end}),h=[],l=0)};for(const d of n)(h.length>=5||l+d.word.length+1>42&&h.length>0)&&f(),h.push(d),l+=d.word.length+1,/[.,!?;:]$/.test(d.word)&&h.length>=2&&f();return f(),a}function be(n,a){const h=vi(n),l=h.map(p=>p.join(" ").length||1),f=l.reduce((p,r)=>p+r,0)||1;let d=0;return h.map((p,r)=>{const b=d/f*a;return d+=l[r],{words:p,start:b,end:d/f*a}})}const li=({script:n,currentTime:a,duration:h,style:l,font:f,position:d,animationId:p,timedChunks:r})=>{const b=ut.useMemo(()=>isFinite(h)&&h>0?h:r&&r.length?r[r.length-1].end:0,[h,r]),S=ut.useMemo(()=>r&&r.length?r:be(n,b),[r,n,b]);if(!n.trim()&&!S.length||!b||S.length===0)return null;let g=S.findIndex(u=>a>=u.start&&a<u.end);g===-1&&(g=a>=b?S.length-1:0);const U=S[g];if(!U)return null;const t=(a-U.start)/Math.max(.001,U.end-U.start),e=Math.min(U.words.length-1,Math.max(0,Math.floor(t*U.words.length))),i=xi(p??"pop"),s=d??(l.position==="center"?"center":"bottom"),o=s==="top"?"top-[14%]":s==="center"?"top-1/2 -translate-y-1/2":"bottom-[14%]";return y.jsx("div",{className:Jt("pointer-events-none absolute inset-x-0 px-4 flex justify-center",o),children:y.jsx("p",{className:Jt("max-w-[90%] text-center leading-tight",i.className,l.uppercase&&"uppercase",l.textClassName),style:{paintOrder:"stroke",...l.textStyle,...f?{fontFamily:f.family,fontWeight:f.weight,letterSpacing:f.letterSpacing}:{}},children:U.words.map((u,c)=>{const m=c===e,x=l.karaoke&&m,w=!!l.boxColorAlt&&e%2===1,v=w?l.boxColorAlt:l.boxColor,E=w&&l.highlightStyleAlt?l.highlightStyleAlt:l.highlightStyle,F=!i.perWord||c<=e,N=v&&(!l.boxActiveWordOnly||m)?{backgroundColor:v,padding:"0.05em 0.2em",borderRadius:"0.12em",boxDecorationBreak:"clone",WebkitBoxDecorationBreak:"clone"}:{};return y.jsxs("span",{className:Jt(i.perWord&&"inline-block transition-all duration-150",!F&&"opacity-0 scale-90"),style:{...x?E:void 0,...N},children:[u,c<U.words.length-1?" ":""]},c)})},`${g}-${i.id}`)})},lt="https://raw.githubusercontent.com/google/fonts/main",Gt=[{id:1,name:"Bebas Neue",google:"Bebas+Neue",family:"'Bebas Neue', sans-serif",weight:400,letterSpacing:"0.05em",category:"CONDENSED",vibe:"Hype / Sports",use:"High-energy content, gym, sports reels",sample:"LET'S GO!",accent:"#FF4D4D",ttfUrl:`${lt}/ofl/bebasneue/BebasNeue-Regular.ttf`},{id:2,name:"Anton",google:"Anton",family:"'Anton', sans-serif",weight:400,letterSpacing:"0.02em",category:"IMPACT",vibe:"Bold / Viral",use:"News-style captions, memes, reactions",sample:"BREAKING NEWS",accent:"#FFDD00",ttfUrl:`${lt}/ofl/anton/Anton-Regular.ttf`},{id:3,name:"Oswald",google:"Oswald:wght@700",family:"'Oswald', sans-serif",weight:700,category:"CONDENSED",vibe:"Clean / Modern",use:"Vlogs, talking-head videos, tutorials",sample:"Today I learned",accent:"#60A5FA",ttfUrl:`${lt}/ofl/oswald/Oswald%5Bwght%5D.ttf`},{id:4,name:"Black Han Sans",google:"Black+Han+Sans",family:"'Black Han Sans', sans-serif",weight:400,category:"DISPLAY",vibe:"K-content / Punchy",use:"K-style edits, beauty, lifestyle",sample:"OMG WAIT",accent:"#F472B6",ttfUrl:`${lt}/ofl/blackhansans/BlackHanSans-Regular.ttf`},{id:5,name:"Righteous",google:"Righteous",family:"'Righteous', sans-serif",weight:400,category:"RETRO",vibe:"Fun / 70s",use:"Comedy, food, travel content",sample:"Good vibes",accent:"#FB923C",ttfUrl:`${lt}/ofl/righteous/Righteous-Regular.ttf`},{id:6,name:"Barlow Condensed",google:"Barlow+Condensed:wght@800",family:"'Barlow Condensed', sans-serif",weight:800,category:"CONDENSED",vibe:"Tech / Minimal",use:"Tech reviews, product demos",sample:"THE NEW STANDARD",accent:"#A3E635",ttfUrl:`${lt}/ofl/barlowcondensed/BarlowCondensed-ExtraBold.ttf`},{id:7,name:"Permanent Marker",google:"Permanent+Marker",family:"'Permanent Marker', cursive",weight:400,category:"HANDWRITE",vibe:"Raw / Authentic",use:"Authentic UGC, personal stories, POV",sample:"real talk",accent:"#FDE68A",ttfUrl:`${lt}
1/apache/permanentmarker/PermanentMarker-Regular.ttf`},{id:8,name:"Lilita One",google:"Lilita+One",family:"'Lilita One', sans-serif",weight:400,category:"DISPLAY",vibe:"Playful / Kids",use:"Family content, cartoons, lifestyle",sample:"So much fun!",accent:"#C084FC",ttfUrl:`${lt}/ofl/lilitaone/LilitaOne-Regular.ttf`},{id:9,name:"Teko",google:"Teko:wght@700",family:"'Teko', sans-serif",weight:700,letterSpacing:"0.04em",category:"CONDENSED",vibe:"Military / Action",use:"Fitness, action, survival content",sample:"NO EXCUSES",accent:"#6EE7B7",ttfUrl:`${lt}/ofl/teko/Teko%5Bwght%5D.ttf`},{id:10,name:"Alfa Slab One",google:"Alfa+Slab+One",family:"'Alfa Slab One', serif",weight:400,category:"SLAB",vibe:"Western / Bold",use:"Western, outdoor, rugged brands",sample:"HOWDY",accent:"#FCA5A5",ttfUrl:`${lt}/ofl/alfaslabone/AlfaSlabOne-Regular.ttf`},{id:11,name:"Boogaloo",google:"Boogaloo",family:"'Boogaloo', sans-serif",weight:400,category:"CASUAL",vibe:"Chill / Friendly",use:"Comedy, casual vlogs, pet content",sample:"hey friends",accent:"#67E8F9",ttfUrl:`${lt}/ofl/boogaloo/Boogaloo-Regular.ttf`},{id:12,name:"Saira Condensed",google:"Saira+Condensed:wght@800",family:"'Saira Condensed', sans-serif",weight:800,category:"CONDENSED",vibe:"Corporate / Sleek",use:"Business, finance, news clips",sample:"Q4 RESULTS",accent:"#E2E8F0",ttfUrl:`${lt}/ofl/sairacondensed/SairaCondensed-ExtraBold.ttf`},{id:13,name:"Russo One",google:"Russo+One",family:"'Russo One', sans-serif",weight:400,category:"DISPLAY",vibe:"Gaming / Esports",use:"Gaming clips, esports, tech drops",sample:"GG WP",accent:"#818CF8",ttfUrl:`${lt}/ofl/russoone/RussoOne-Regular.ttf`},{id:14,name:"Fugaz One",google:"Fugaz+One",family:"'Fugaz One', sans-serif",weight:400,category:"DISPLAY",vibe:"Latino / Fiesta",use:"Latin music, culture, dance content",sample:"¡VAMOS!",accent:"#FCD34D",ttfUrl:`${lt}/ofl/fugazone/FugazOne-Regular.ttf`},{id:15,name:"Squada One",google:"Squada+One",family:"'Squada One', sans-serif",weight:400,letterSpacing:"0.06em",category:"GEOMETRIC",vibe:"Futurist / Sci-fi",use:"Tech, AI content, cyberpunk edits",sample:"THE FUTURE",accent:"#34D399",ttfUrl:`${lt}/ofl/squadaone/SquadaOne-Regular.ttf`}],fr={CONDENSED:"#60A5FA",IMPACT:"#FFDD00",DISPLAY:"#F472B6",RETRO:"#FB923C",HANDWRITE:"#FDE68A",SLAB:"#FCA5A5",CASUAL:"#67E8F9",GEOMETRIC:"#34D399"},cr=3;function ur(n){return Gt.find(a=>a.id===n)??Gt[2]}const pr="https://fonts.googleapis.com/css2?family="+Gt.map(n=>n.google).join("&family=")+"&display=swap";let Ce=!1;function bi(){if(Ce||typeof document>"u")return;if(document.getElementById("hive-caption-fonts")){Ce=!0;return}const n=document.createElement("link");n.id="hive-caption-fonts",n.rel="stylesheet",n.href=pr,document.head.appendChild(n),Ce=!0}function mr(){const[n,a]=ut.useState(!1);return ut.useEffect(()=>{bi();let h=!1;const l=document.fonts;return l!=null&&l.ready?l.ready.then(()=>{h||a(!0)}):a(!0),()=>{h=!0}},[]),n}async function _r(n,a){bi();try{"fonts"in document&&(await document.fonts.load(`${n.weight} ${a}px ${n.family}`),await document.fonts.ready)}catch{}}const hi={photorealistic:["professional","corporate","business","finance","fintech","luxury","premium","trust","clean","minimal","elegant","medical","health","law","real estate","consulting","enterprise","b2b","sophisticated","serious","authoritative"],animated:["playful","fun","friendly","kids","family","cartoon","colorful","colourful","cheerful","education","edutainment","casual","approachable","whimsical","lifestyle","food","travel","gaming","creative","quirky","bright"],punk:["bold","edgy","rebel","rebellious","street","urban","music","fashion","youth","alternative","grunge","punk","gritty","raw","underground","nightlife","skate","tattoo","disruptive","loud","energetic","hype"]};function ke(n){return[...n.vibe_keywords??[],...n.tone_adjectives??[],n.industry??"",n.brand_positioning??""].join(" ").toLowerCase().split(/[^a-z]+/).filter(Boolean)}function Es(n){if(!n||n.is_default)return{category:"photorealistic",score:0};const a=new Set(ke(n)),h={photorealistic:0,animated:0,punk:0};
1Object.keys(hi).forEach(f=>{for(const d of hi[f])d.includes(" ")?ke(n).join(" ").includes(d)&&(h[f]+=2):a.has(d)&&(h[f]+=1)});let l="photorealistic";for(const f of Object.keys(h))h[f]>h[l]&&(l=f);return{category:l,score:h[l]}}function gr(n){var a,h,l,f;return!n||n.is_default?null:((h=(a=n.primary_colors)==null?void 0:a[0])==null?void 0:h.hex)??((f=(l=n.secondary_colors)==null?void 0:l[0])==null?void 0:f.hex)??null}function Ge(n){let a=(n||"").trim().replace("#","");return a.length===3&&(a=a.split("").map(h=>h+h).join("")),/^[0-9a-fA-F]{6}$/.test(a)?{r:parseInt(a.slice(0,2),16),g:parseInt(a.slice(2,4),16),b:parseInt(a.slice(4,6),16)}:null}function Rt(n){const a=Ge(n);return a?(.299*a.r+.587*a.g+.114*a.b)/255:0}function wi(n){const a=Ge(n);if(!a)return{h:0,s:0,l:0};const h=a.r/255,l=a.g/255,f=a.b/255,d=Math.max(h,l,f),p=Math.min(h,l,f),r=(d+p)/2,b=d-p;let S=0,g=0;return b!==0&&(S=r>.5?b/(2-d-p):b/(d+p),d===h?g=(l-f)/b+(l<f?6:0):d===l?g=(f-h)/b+2:g=(h-l)/b+4,g*=60),{h:g,s:S,l:r}}function yr(n,a){const h=Math.abs(n-a)%360;return h>180?360-h:h}function xr(n){if(!n)return[];const a=[...n.primary_colors??[],...n.secondary_colors??[]].map(h=>h==null?void 0:h.hex).filter(h=>!!h&&!!Ge(h));return Array.from(new Set(a.map(h=>h.toLowerCase())))}function Si(n){if(!n||n.is_default)return null;const a=xr(n);if(!a.length)return null;const h=a.map(d=>({hex:d,...wi(d),lum:Rt(d)})).filter(d=>d.s>=.18&&d.lum>.06&&d.lum<.96);if(!h.length)return{primary:gr(n)??a[0],secondary:null};h.sort((d,p)=>p.s-d.s);const l=h[0],f=h.slice(1).find(d=>
1yr(d.h,l.h)>25)??null;return{primary:l.hex,secondary:(f==null?void 0:f.hex)??null}}function As(n){var a;return((a=Si(n))==null?void 0:a.primary)??null}function Ui(n){return Rt(n)>.6?"#000000":"#FFFFFF"}function Ts(n){const a=Si(n);if(!a)return null;let h=a.primary,l=a.secondary;if(l&&Rt(l)<Rt(h)){const d=h;h=l,l=d}const f=l&&Math.abs(Rt(l)-Rt(h))>=.3?l:Ui(h);return{id:"brand",name:`${(n==null?void 0:n.name)??"Brand"}`,position:"bottom",uppercase:!0,karaoke:!0,boxColor:h,boxActiveWordOnly:!0,textClassName:"font-extrabold text-white text-2xl sm:text-3xl tracking-tight",textStyle:{WebkitTextStroke:"1.5px #000",textShadow:"0 3px 10px rgba(0,0,0,0.7)"},highlightStyle:{color:f},canvas:{fontScale:.07,weight:800,fill:"#FFFFFF",stroke:"#000000",strokeScale:.09,shadowBlurScale:.18,shadowColor:"rgba(0,0,0,0.7)",boxColor:h,boxActiveWordOnly:!0,highlightFill:f}}}const Fs={photorealistic:"Photorealistic",animated:"Animated",punk:"Punk"};function Bs(n){var l;if(!n||n.is_default)return[];const a=new Set,h=[];for(const f of[...n.primary_colors??[],...n.secondary_colors??[]]){const d=(l=f==null?void 0:f.hex)==null?void 0:l.toLowerCase();!d||a.has(d)||(a.add(d),h.push({hex:f.hex,name:f.name||f.hex}))}return h.map((f,d)=>({c:f,i:d,s:wi(f.hex).s})).sort((f,d)=>d.s-f.s||f.i-d.i).map(f=>f.c)}const vr=[{words:["corporate","business","finance","fintech","professional","enterprise","b2b","consulting","law","bank","insurance"],fontId:12},{words:["tech","technology","saas","software","ai","startup","product","minimal","modern","clean"],fontId:6},{words:["luxury","premium","elegant","sophisticated","fashion","beauty","editorial"],fontId:3},{words:["playful","fun","kids","family","cartoon","friendly","cheerful","whimsical"],fontId:8},{words:["bold","viral","news","breaking","hype","sports","gym","fitness","loud","energetic"],fontId:2},{words:["gaming","esports","cyber","cyberpunk","futuristic","sci-fi","crypto","web3"],fontId:13},{words:["authentic","ugc","personal","raw","street","urban","grunge","punk","rebel","tattoo"],fontId:7},{words:["retro","vintage","food","travel","comedy","70s"],fontId:5}];function ks(n){var d,p;if(!n||n.is_default)return null;const a=[(d=n.typography)==null?void 0:d.primary,(p=n.typography)==null?void 0:p.secondary].filter(Boolean).map(r=>String(r).toLowerCase());for(const r of a){const b=Gt.find(S=>{const g=S.name.toLowerCase();return g===r||r.includes(g)||g.includes(r)});if(b)return b.id}const h=ke(n),l=h.join(" "),f=new Set(h);for(const r of vr)if(r.words.some(b=>f.has(b)||l.includes(b)))return r.fontId;return cr}function br(n,a){if(!a||!a.text&&!a.accent)return n;const h={...n,textStyle:{...n.textStyle},highlightStyle:{...n.highlightStyle},canvas:{...n.canvas}};if(a.text&&(h.canvas.fill=a.text,h.textStyle={...h.textStyle,color:a.text}),a.accent)if(!!(n.boxColor||n.canvas.boxColor)){h.boxColor=a.accent,h.canvas.boxColor=a.accent;const f=Ui(a.accent);h.canvas.highlightFill=f,h.highlightStyle={...h.highlightStyle,color:f}}else h.canvas.highlightFill=a.accent,h.highlightStyle={...h.highlightStyle,color:a.accent};return h}const wr="Hi, welcome to Design Hive â today I'll show you how to create stunning brand visuals in minutes.",Sr=[{icon:sr,phase:"Transcribe",desc:"We already know the words â your script â so no speech-to-text is needed for the preview."},{icon:yi,phase:"Chunk",desc:"The script is split into short, readable caption groups (â¤5 words, breaking on punctuation)."},{icon:Te,phase:"Style",desc:"Pick a caption look â font, stroke, colour, glow and animation."},{icon:ar,phase:"Sync",desc:"Captions are timed across the clip and animate in, with karaoke word highlighting."}],Mt=({step:n,title:a,hint:h})=>y.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[y.jsxs("p",{className:"flex items-center gap-2 text-[11px] font-semibold tracking-[0.12em] uppercase text-muted-foreground",children:[y.jsx("span",{className:"flex items-center justify-center w-4 h-4 rounded-full bg-primary/15 text-primary text-[9px] font-bold",children:n}),a]}),h&&y.jsx("span",{className:"text-[10px] text-muted-foreground normal-case tracking-normal",children:h})]}),Ee=({hex:n,selected:a,onSelect:h,title:l})=>y.jsx("button",{type:"button",title:l||n,onClick:h,className:`w-7 h-7 rounded-md border transition-transform hover:scale-110 ${a?"ring-2 ring-primary ring-offset-1 ring-offset-background border-primary":"border-white/20"}`,style:{background:n}}),Ur=["#FACC15","#F97316","#EC4899","#EF4444","#22D3EE","#34D399","#A78BFA","#3B82F6"],Cr=["#FFFFFF","#000000","#FACC15","#22D3EE"],Er=({brandPalette:n,colors:a,onColorsChange:h})=>{if(!h)return null;const l=a==null?void 0:a.accent,f=a==null?void 0:a.text,d=p=>h({...a||{},...p});return y.jsxs("div",{className:"space-y-3 rounded-xl border border-border bg-card p-3",children:[n.length>0&&y.jsxs("div",{children:[y.jsx("p",{className:"mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase text-hive-gold",children:"Brand colours"}),y.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(p=>y.jsx(Ee,{hex:p.hex,title:p.name,selected:(l==null?void 0:l.toLowerCase())===p.hex.toLowerCase(),onSelect:()=>d({accent:p.hex})},p.hex))})]}),y.jsxs("div",{children:[y.jsx("p",{className:"mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase text-muted-foreground",children:"Highlight"}),y.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[Ur.map(p=>y.jsx(Ee,{hex:p,selected:(l==null?void 0:l.toLowerCase())===p.toLowerCase(),onSelect:()=>d({accent:p})},p)),y.jsxs("label",{className:"relative w-7 h-7 rounded-md border border-dashed border-white/30 flex items-center justify-center cursor-pointer hover:border-hive-gold/60",title:"Custom highlight colour",children:[y.jsx(Te,{className:"w-3.5 h-3.5 text-muted-foreground"}),y.jsx("input",{type:"color",value:l||"#FACC15",onChange:p=>d({accent:p.target.value}),className:"absolute inset-0 opacity-0 cursor-pointer"})]})]})]}),y.jsxs("div",{children:[y.jsx("p",{className:"mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase text-muted-foreground",children:"Text"}),y.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[Cr.map(p=>y.jsx(Ee,{hex:p,selected:(f==null?void 0:f.toLowerCase())===p.toLowerCase(),onSelect:()=>d({text:p})},p)),y.jsxs("label",{className:"relative w-7 h-7 rounded-md border border-dashed border-white/30 flex items-center justify-center cursor-pointer hover:border-hive-gold/60",title:"Custom text colour",children:[y.jsx(Te,{className:"w-3.5 h-3.5 text-muted-foreground"}),y.jsx("input",{type:"color",value:f||"#FFFFFF",onChange:p=>d({text:p.target.value}),className:"absolute inset-0 opacity-0 cursor-pointer"})]})]})]}),(l||f)&&y.jsx("button",{type:"button",onClick:()=>h(null),className:"text-[11px] text-muted-foreground underline hover:text-foreground",children:"Reset to style colours"})]})},Ar=({script:n,enabled:a,style:h,font:l,position:f,animationId:d,videoUrl:p,videoTime:r,onLoadedMetadata:b,onTimeUpdate:S,timedChunks:g,trim:U,zoom:t,focusPoint:e,outputAspect:i})=>{const s=(i||"16:9").replace(":","/"),o=ut.useMemo(()=>{const m=vi(n).length||1;return Math.max(4,m*1.2)},[n]),[u,c]=ut.useState(0);return ut.useEffect(()=>{if(p||!a)return;let m=0;const x=performance.now(),w=v=>{c((v-x)/1e3%o),m=requestAnimationFrame(w)};return m=requestAnimationFrame(w),()=>cancelAnimationFrame(m)},[p,a,o]),y.jsx("div",{className:"relative w-full aspect-video rounded-2xl border border-border overflow-hidden bg-gradient-to-br from-zinc-800 to-zinc-950 flex items-center justify-center",children:p?y.jsxs("div",{className:"relative h-full overflow-hidden bg-black",style:{aspectRatio:s},children:[y.jsx("video",{src:p,controls:!0,loop:!0,autoPlay:!0,muted:!0,onLoadedMetadata:m=>{const x=m.currentTarget.duration;b(isFinite(x)&&x>0?x:0)},onTimeUpdate:m=>{const x=m.currentTarget;if(U&&(x.currentTime>=U.end||x.currentTime<U.start-.1))try{x.currentTime=U.start}catch{}S(x.currentTime)},onDurationChange:m=>{const x=m.currentTarget.duration;isFinite(x)&&x>0&&b(x)},className:"w-full h-full object-cover transition-transform",style:t&&t>1?{transform:`scale(${t}) translate(${(.5-((e==null?void 0:e.x)??.5))*100}%, ${(.5-((e==null?void 0:e.y)??.5))*100}%)`}:void 0}),a&&y.jsx(li,{script:n,currentTime:r.current,duration:r.duration,style:h,font:l,position:f,animationId:d,timedChunks:g})]}):y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"text-xs text-muted-foreground",children:"Generate an avatar to preview captions on your video"}),a&&y.jsx(li,{script:n,currentTime:u,duration:o,style:h,font:l,position:f,animationId:d})]})})},di=[{id:"auto",label:"Auto"},{id:"top",label:"Top"},{id:"center",label:"Middle"},{id:"bottom",label:"Bottom"}],Tr={auto:{x:.5,y:.5},top:{x:.5,y:.28},center:{x:.5,y:.5},bottom:{x:.5,y:.72}},Fr=[1,1.5,2],Is=({script:n,enabled:a,onEnabledChange:h,timedChunks:l,trim:f,onTrimChange:d,focusMode:p="auto",onFocusModeChange:r,zoom:b=1,onZoomChange:S,outputAspect:g,sourcePanel:U,styles:t=hr,styleId:e,onStyleChange:i,brandName:s,brandColor:o,fontId:u,onFontChange:c,brandPalette:m=[],colors:x=null,onColorsChange:w,position:v,onPositionChange:E,animationId:F,onAnimationChange:C,videoUrl:N,videoTime:z,onLoadedMetadata:H,onTimeUpdate:j,onDownloadCaptioned:X,onDownloadPlain:V,onDownloadSrt:M,onDownloadAss:Y,onDownloadAudio:Q,audioBusy:P,burning:$,burnPct:k})=>{var _t;const ht=n.trim()||wr,pt=t.find(T=>T.id===e)??t[0],At=ut.useMemo(()=>br(pt,x),[pt,x]),Ft=ur(u),wt=T=>{h(!0),i(T)},Wt=T=>{h(!0),E(T)},tt=T=>{h(!0),C(T)},mt=T=>{h(!0),c(T)},ot=mr();return y.jsxs("div",{className:"space-y-6",children:[U,o&&y.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border border-border bg-card",children:[y.jsx("span",{className:"w-6 h-6 rounded-md border border-white/20 shrink-0",style:{background:o}}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Synced to ",y.jsx("span",{className:"font-semibold text-foreground",children:s||"your brand"})," â captions match your brand colours and font automatically. Tweak the colour or pick another",y.jsxs("span",{className:"font-semibold text-foreground",children:[" ",s||"Brand"]})," style below anytime."]})]}),y.jsxs("div",{className:"flex items-center justify-between gap-3 p-3.5 rounded-xl border border-border bg-card",children:[y.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[y.jsx("div",{className:"w-9 h-9 rounded-lg bg-hive-gold/15 flex items-center justify-center shrink-0",children:y.jsx(tr,{className:"w-4 h-4 text-hive-gold"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Creative captions"}),y.jsx("p",{className:"text-xs text-muted-foreground",children:"Animated, styled subtitles synced to your script â works on every avatar."})]})]}),y.jsx(Ji,{checked:a,onCheckedChange:h,"aria-label":"Creative captions"})]}),y.jsx("div",{className:"sticky top-2 z-10",children:y.jsx(Ar,{script:ht,enabled:a,style:At,font:Ft,position:v,animationId:F,videoUrl:N,videoTime:z,onLoadedMetadata:H,onTimeUpdate:j,timedChunks:l,trim:f,zoom:b,focusPoint:Tr[p],outputAspect:g})}),(r||S)&&N&&y.jsxs("div",{children:[y.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[y.jsxs("p",{className:"flex items-center gap-2 text-[11px] font-semibold tracking-[0.12em] uppercase text-muted-foreground",children:[y.jsx(er,{className:"w-3.5 h-3.5"})," Framing"]}),y.jsx("span",{className:"text-[10px] text-muted-foreground normal-case tracking-normal",children:b>1?`${b}à · ${(_t=di.find(T=>T.id===p))==null?void 0:_t.label}`:"No zoom"})]}),y.jsxs("div",{className:"rounded-xl border border-border bg-card p-3 space-y-3",children:[S&&y.jsxs("div",{children:[y.jsx("p",{className:"mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase text-muted-foreground",children:"Zoom"}),y.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Fr.map(T=>y.jsx("button",{type:"button",onClick:()=>{h(!0),S(T)},className:`h-9 rounded-lg border text-[11px] font-semibold transition-colors ${b===T?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:text-foreground hover:border-hive-gold/50"}`,children:T===1?"None (1Ã)":`${T}Ã`},T))})]}),r&&b>1&&y.jsxs("div",{children:[y.jsx("p",{className:"mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase text-muted-foreground",children:"Focus â what to keep in frame"}),y.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:di.map(T=>y.jsx("button",{type:"button",onClick:()=>{h(!0),r(T.id)},className:`h-9 rounded-lg border text-[11px] font-semibold transition-colors ${p===T.id?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:text-foreground hover:border-hive-gold/50"}`,children:T.label},T.id))}),y.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:"âAutoâ tracks the speakerâs face; Top/Middle/Bottom keep that part of the frame."})]})]})]}),d&&N&&z.duration>0&&y.jsx(kr,{duration:z.duration,current:z.current,trim:f??null,onTrimChange:d}),y.jsxs("div",{children:[y.jsx(Mt,{step:1,title:"Caption style"}),y.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(T=>y.jsx(Br,{style:T,selected:T.id===e,onSelect:()=>wt(T.id)},T.id))})]}),y.jsxs("div",{children:[y.jsx(Mt,{step:2,title:"Font",hint:ot?`${Gt.length} fonts`:"Loading fontsâ¦"}),y.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-80 overflow-y-auto pr-1","data-fonts-ready":ot,children:Gt.map(T=>{const Tt=T.id===u,L=fr[T.category]||"#888";return y.jsxs("button",{type:"button",onClick:()=>mt(T.id),className:`group flex flex-col overflow-hidden rounded-xl border text-left transition-all ${Tt?"border-primary ring-2 ring-primary/40":"border-border hover:border-hive-gold/50"}`,children:[y.jsxs("div",{className:"relative h-16 flex items-center justify-center px-2 bg-gradient-to-br from-zinc-900 to-black",children:[y.jsx("span",{className:"text-center leading-none",style:{fontFamily:T.family,fontWeight:T.weight,letterSpacing:T.letterSpacing,fontSize:T.sample.length>12?"1.05rem":"1.5rem",color:T.accent,textShadow:"0 1px 3px rgba(0,0,0,0.9), 0 0 10px rgba(0,0,0,0.5)"},children:T.sample}),Tt&&y.jsx("span",{className:"absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-primary flex items-center justify-center",children:y.jsx(gi,{className:"w-2.5 h-2.5 text-white"})})]}),y.jsxs("div",{className:"flex items-center justify-between gap-1 px-2.5 py-1.5 bg-card",children:[y.jsx("span",{className:"text-xs font-semibold text-foreground truncate",children:T.name}),y.jsx("span",{className:"text-[8px] font-bold tracking-wider px-1 py-0.5 rounded shrink-0",style:{color:L,background:`${L}22`},children:T.category})]})]},T.id)})})]}),y.jsxs("div",{children:[y.jsx(Mt,{step:3,title:"Colour",hint:m.length?"Brand palette synced":void 0}),y.jsx(Er,{brandPalette:m,colors:x,onColorsChange:w})]}),y.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[y.jsxs("div",{children:[y.jsx(Mt,{step:4,title:"Position"}),y.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:dr.map(T=>y.jsxs("button",{type:"button",onClick:()=>Wt(T.id),className:`relative h-12 rounded-xl border transition-colors overflow-hidden ${v===T.id?"border-primary bg-primary/10":"border-border bg-card hover:border-hive-gold/50"}`,children:[y.jsx("span",{className:"absolute inset-x-2 top-1.5 bottom-4 rounded-md bg-muted-foreground
1/10",children:y.jsx("span",{className:`absolute left-1/2 -translate-x-1/2 w-5 h-1 rounded-full ${v===T.id?"bg-primary":"bg-muted-foreground/60"} ${T.id==="top"?"top-1":T.id==="center"?"top-1/2 -translate-y-1/2":"bottom-1"}`})}),y.jsx("span",{className:`absolute bottom-1 left-0 right-0 text-center text-[9px] font-semibold ${v===T.id?"text-primary":"text-muted-foreground"}`,children:T.name})]},T.id))})]}),y.jsxs("div",{children:[y.jsx(Mt,{step:5,title:"Animation"}),y.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Be.map(T=>y.jsx("button",{type:"button",onClick:()=>tt(T.id),className:`h-12 rounded-xl border text-[11px] font-semibold transition-colors ${F===T.id?"border-primary bg-primary/10 text-primary":"border-border bg-card text-muted-foreground hover:text-foreground hover:border-hive-gold/50"}`,children:T.name},T.id))})]})]}),y.jsxs("div",{children:[y.jsx(Mt,{step:5,title:"Export"}),N?y.jsxs("div",{children:[y.jsxs("div",{className:"flex flex-wrap gap-2",children:[y.jsx(qt,{onClick:X,disabled:$,className:"rounded-full bg-gradient-primary text-white hover:opacity-95",children:$?y.jsxs(y.Fragment,{children:[y.jsx(oi,{className:"w-4 h-4 mr-2 animate-spin"})," Rendering⦠",Math.round(k),"%"]}):y.jsxs(y.Fragment,{children:[y.jsx(he,{className:"w-4 h-4 mr-2"})," Download with captions"]})}),V&&y.jsxs(qt,{onClick:V,disabled:$,variant:"outline",className:"rounded-full",children:[y.jsx(he,{className:"w-4 h-4 mr-2"})," Download (no captions)"]}),y.jsxs(qt,{onClick:M,disabled:$,variant:"outline",className:"rounded-full",children:[y.jsx(he,{className:"w-4 h-4 mr-2"})," .srt"]}),y.jsxs(qt,{onClick:Y,disabled:$,variant:"outline",className:"rounded-full",children:[y.jsx(he,{className:"w-4 h-4 mr-2"})," .ass (styled)"]}),Q&&y.jsx(qt,{onClick:Q,disabled:$||P,variant:"outline",className:"rounded-full",children:P?y.jsxs(y.Fragment,{children:[y.jsx(oi,{className:"w-4 h-4 mr-2 animate-spin"})," Extractingâ¦"]}):y.jsxs(y.Fragment,{children:[y.jsx(ir,{className:"w-4 h-4 mr-2"})," Audio (MP3)"]})})]}),$&&y.jsxs("div",{className:"mt-3",children:[y.jsx(Zi,{value:k,className:"h-2"}),y.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Burning captions into your video â this can take up to a minute. Keep this tab open."})]})]}):y.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-dashed border-border bg-muted/30 px-3.5 py-3",children:[y.jsx(rr,{className:"w-4 h-4 text-hive-gold
1shrink-0"}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Generate an avatar in the ",y.jsx("span",{className:"font-semibold text-foreground",children:"Avatar"})," tab, then download it with captions (or as .srt / .ass) right here. Your style choices are saved for the export."]})]})]}),y.jsxs("details",{className:"group rounded-xl border border-border bg-card",children:[y.jsxs("summary",{className:"flex items-center justify-between gap-2 px-3.5 py-3 cursor-pointer list-none",children:[y.jsx("span",{className:"text-[11px] font-semibold tracking-[0.12em] uppercase text-muted-foreground",children:"How captions work"}),y.jsx(nr,{className:"w-4 h-4 text-muted-foreground transition-transform group-open:rotate-180"})]}),y.jsx("div",{className:"px-3.5 pb-3.5 space-y-2",children:Sr.map((T,Tt)=>y.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-xl border border-border bg-background/50",children:[y.jsx("div",{className:"w-8 h-8 rounded-lg bg-muted flex items-center justify-center shrink-0",children:y.jsx(T.icon,{className:"w-4 h-4 text-foreground/70"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsxs("p",{className:"text-sm font-semibold text-foreground",children:[y.jsx("span",{className:"text-muted-foreground mr-1.5 tabular-nums",children:String(Tt+1).padStart(2,"0")}),T.phase]}),y.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:T.desc})]})]},T.phase))})]})]})},Br=({style:n,selected:a,onSelect:h})=>{const l=n.canvas,f={color:l.fill,fontStyle:l.italic?"italic":void 0,WebkitTextStroke:l.stroke?`0.6px ${l.stroke}`:void 0,textShadow:l.glow?`0 0 6px ${l.shadowColor}, 0 0 12px ${l.shadowColor}`:l.shadowColor?`0 2px 6px ${l.shadowColor}`:void 0},d=l.boxColor?{backgroundColor:l.boxColor,padding:"0 0.18em",borderRadius:"0.14em",color:l.highlightFill||"#fff"}:l.highlightFill?{color:l.highlightFill}:{},p=l.boxColorAlt?{backgroundColor:l.boxColorAlt,padding:"0 0.18em",borderRadius:"0.14em",color:l.highlightFillAlt||"#fff"}:null;return y.jsxs("button",{type:"button",onClick:h,className:Jt("group flex flex-col overflow-hidden rounded-xl border transition-all",a?"border-primary ring-2 ring-primary/40":"border-border hover:border-hive-gold/50"),children:[y.jsxs("div",{className:"relative h-16 flex items-center justify-center bg-gradient-to-br from-zinc-700 to-zinc-900",children:[y.jsx("span",{className:Jt("text-xl font-extrabold leading-none",n.uppercase&&"uppercase"),style:f,children:p?y.jsxs(y.Fragment,{children:[y.jsx("span",{style:d,children:"Aa"})," ",y.jsx("span",{style:p,children:"Bb"})]}):n.karaoke||l.boxColor?y.jsxs(y.Fragment,{children:[y.jsx("span",{style:d,children:"Aa"})," Bb"]}):"Aa Bb"}),a&&y.jsx("span",{className:"absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-primary flex items-center justify-center",children:y.jsx(gi,{className:"w-2.5 h-2.5 text-white"})})]}),y.jsx("div",{className:"px-2.5 py-1.5 bg-card",children:y.jsx("span",{className:"text-xs font-semibold text-foreground",children:n.name})})]})},Kt=n=>{(!isFinite(n)||n<0)&&(n=0);const a=Math.floor(n/60),h=Math.floor(n%60);return`${a}:${String(h).padStart(2,"0")}`},kr=({duration:n,current:a,trim:h,onTrimChange:l})=>{const d=(h==null?void 0:h.start)??0,p=(h==null?void 0:h.end)??n,r=ut.useRef(null),b=ut.useRef(null),S=ut.useCallback((x,w,v)=>{const E=v??b.current;let F=Math.max(0,Math.min(x,n)),C=Math.max(0,Math.min(w,n));E==="start"?F=Math.max(0,Math.min(F,C-.5)):E==="end"?C=Math.min(n,Math.max(C,F+.5)):C-F<.5&&(C=Math.min(n,F+.5)),F<=.05&&C>=n-.05?l(null):l({start:F,end:Math.max(C,F+.5)})},[n,l]),g=x=>{const w=r.current;if(!w)return 0;const v=w.getBoundingClientRect(),E=v.width>0?(x-v.left)/v.width:0;return Math.min(1,Math.max(0,E))*n},U=x=>w=>{w.preventDefault(),w.stopPropagation(),b.current=x;try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}},t=x=>{if(!b.current)return;const w=g(x.clientX);b.current==="start"?S(w,p):S(d,w)},e=x=>{if(b.current){b.current=null;try{x.currentTarget.releasePointerCapture(x.pointerId)}catch{}}},i=x=>{const w=g(x.clientX),v=Math.abs(w-d)<=Math.abs(w-p)?"start":"end";b.current=v,v==="start"?S(w,p,"start"):S(d,w,"end")},s=x=>w=>{const v=w.shiftKey?1:.1;let E=0;if(w.key==="ArrowLeft")E=-v;else if(w.key==="ArrowRight")E=v;else return;w.preventDefault(),x==="start"?S(d+E,p,"start"):S(d,p+E,"end")},o=x=>`${Math.min(n,Math.max(0,x))/n*100}%`,u=p-d,c=!!h,m=(x,w)=>y.jsx("div",{role:"slider",tabIndex:0,"aria-label":x==="start"?"Trim start":"Trim end","aria-valuemin":0,"aria-valuemax":Math.round(n),"aria-valuenow":Math.round(w),"aria-valuetext":Kt(w),onPointerDown:U(x),onPointerMove:t,onPointerUp:e,onKeyDown:s(x),className:"absolute top-1/2 -translate-y-1/2 -translate-x-1/2 z-20 flex h-[calc(100%+10px)] w-5 cursor-ew-resize touch-none items-center justify-center rounded-md bg-primary shadow-md ring-2 ring-background focus:outline-none focus:ring-2 focus:ring-hive-gold",style:{left:o(w)},children:y.jsx("span",{className:"h-4 w-[3px] rounded-full bg-white/90"})},x);return y.jsxs("div",{children:[y.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[y.jsxs("p",{className:"flex items-center gap-2 text-[11px] font-semibold tracking-[0.12em] uppercase text-muted-foreground",children:[y.jsx(yi,{className:"w-3.5 h-3.5"})," Trim"]}),y.jsx("span",{className:"text-[11px] font-semibold text-primary tabular-nums",children:c?`Keeping ${Kt(u)}`:`Full clip · ${Kt(n)}`})]}),y.jsxs("div",{className:"rounded-xl border border-border bg-card p-3 space-y-3",children:[y.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:"Drag the handles to keep only the part you want. Just that slice gets captioned and exported â the dimmed ends are cut."}),y.jsxs("div",{ref:r,onPointerDown:i,className:"relative h-10 w-full cursor-pointer touch-none select-none rounded-lg bg-muted",children:[y.jsx("div",{className:"absolute inset-y-0 left-0 rounded-l-lg bg-background/70",style:{width:o(d)}}),y.jsx("div",{className:"absolute inset-y-0 right-0 rounded-r-lg bg-background/70",style:{left:o(p)}}),y.jsx("div",{className:"absolute inset-y-0 border-y-2 border-primary bg-primary/25",style:{left:o(d),right:`${100-p/n*100}%`}}),a>0&&y.jsx("div",{className:"absolute inset-y-0 z-10 w-[2px] -translate-x-1/2 bg-hive-gold",style:{left:o(a)}}),m("start",d),m("end",p)]}),y.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[y.jsxs("div",{className:"flex items-center gap-2 text-[11px] tabular-nums",children:[y.jsxs("button",{type:"button",onClick:()=>S(a,p,"start"),className:"rounded-md border border-border bg-background px-2 py-1 font-medium text-muted-foreground hover:text-foreground hover:border-hive-gold/50",title:"Set the start to the current preview frame",children:["In ",y.jsx("span",{className:"text-foreground",children:Kt(d)})]}),y.jsxs("button",{type:"button",onClick:()=>S(d,a,"end"),className:"rounded-md border border-border bg-background px-2 py-1 font-medium text-muted-foreground hover:text-foreground hover:border-hive-gold/50",title:"Set the end to the current preview frame",children:["Out ",y.jsx("span",{className:"text-foreground",children:Kt(p)})]})]}),c&&y.jsx("button",{type:"button",onClick:()=>l(null),className:"text-[11px] text-muted-foreground underline hover:text-foreground",children:"Reset to full clip"})]})]})]})};class zs extends ut.Component{constructor(){super(...arguments);Se(this,"state",{hasError:!1,message:null});Se(this,"handleRetry",()=>this.setState({hasError:!1,message:null}))}static getDerivedStateFromError(h){return{hasError:!0,message:(h==null?void 0:h.message)??"
1Unknown error"}}componentDidCatch(h,l){console.error(`[SectionErrorBoundary${this.props.name?`: ${this.props.name}`:""}]`,h,l)}render(){return this.state.hasError?y.jsxs("div",{className:"mb-6 flex items-center justify-between gap-3 rounded-2xl border border-border bg-card p-4 text-sm text-muted-foreground",children:[y.jsx("span",{children:"This section hit a hiccup. Your download (if any) completed â the rest of the page still works."}),y.jsxs("button",{type:"button",onClick:this.handleRetry,className:"inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-border px-2.5 h-8 text-[12px] font-semibold text-foreground/80 transition-colors hover:text-foreground hover:border-hive-gold/40",children:[y.jsx(or,{className:"w-3.5 h-3.5",strokeWidth:2.5}),"Reload section"]})]}):this.props.children}}async function He(n){return isFinite(n.duration)&&n.duration>0?n.duration:new Promise(a=>{let h=!1;const l=d=>{if(!h){h=!0,n.removeEventListener("seeked",f);try{n.currentTime=0}catch{}a(isFinite(d)&&d>0?d:0)}},f=()=>l(n.duration);n.addEventListener("seeked",f),setTimeout(()=>l(n.duration),3e3);try{n.currentTime=1e7}catch{l(0)}})}function Ir(n,a,h){const l=[];let f="";for(const d of a){const p=f?`${f} ${d}`:d;n.measureText(p).width>h&&f?(l.push(f),f=d):f=p}return f&&l.push(f),l.slice(0,2)}async function Ci(n){const{width:a,height:h,duration:l,script:f,style:d,font:p,position:r,animationId:b,timedChunks:S,focus:g,zoom:U}=n,t=g?Math.min(1,Math.max(0,g.x)):.5,e=g?Math.min(1,Math.max(0,g.y)):.5,i=U&&U>0?U:1,s=S&&S.length?S:be(f,l),o=Math.round(h*d.canvas.fontScale),u=(p==null?void 0:p.weight)??d.canvas.weight,c=(p==null?void 0:p.family)??"'Montserrat', 'DM Sans', system-ui, sans-serif",m=r??(d.position==="center"?"center":"bottom"),x=m==="top"?.16:m==="center"?.5:.84,w=xi(b??"pop");return p&&await _r(p,o),(v,E,F)=>{const C=E.videoWidth||E.width||a,N=E.videoHeight||E.height||h;if(C&&N){const tt=Math.max(a/C,h/N)*i,mt=C*tt,ot=N*tt,_t=Math.min(0,Math.max(a-mt,a/2-t*mt)),T=Math.min(0,Math.max(h-ot,h/2-e*ot));v.drawImage(E,_t,T,mt,ot)}else v.drawImage(E,0,0,a,h);let z=s.findIndex(tt=>F>=tt.start&&F<tt.end);z===-1&&F>=l&&s.length&&(z=s.length-1);const H=z>=0?s[z]:null;if(!H)return;v.save(),v.font=`${d.canvas.italic?"italic ":""}${u} ${o}px ${c}`,v.textAlign="center",v.textBaseline="middle";const j=d.uppercase?H.words.map(tt=>tt.toUpperCase()):H.words,X=Ir(v,j,a*.86),V=o*1.18,M=X.length*V,Y=x,Q=h*Y-M/2+V/2,P=a/2,$=(F-H.start)/Math.max(.001,H.end-H.start),k=Math.min(j.length-1,Math.max(0,Math.floor($*j.length))),ht=!!d.canvas.boxColorAlt&&k%2===1,pt=ht?d.canvas.boxColorAlt:d.canvas.boxColor,At=ht&&d.canvas.highlightFillAlt?d.canvas.highlightFillAlt:d.canvas.highlightFill,Ft=Math.min(1,(F-H.start)/.32),wt=w.canvas?w.canvas(Ft):{scale:1,dy:0,opacity:1};if(v.globalAlpha=wt.opacity,wt.scale!==1){const tt=h*Y;v.translate(P,tt),v.scale(wt.scale,wt.scale),v.translate(-P,-tt)}const Wt=wt.dy*o;X.forEach((tt,mt)=>{const ot=Q+mt*V+Wt;d.canvas.shadowColor&&(v.shadowColor=d.canvas.shadowColor,v.shadowBlur=o*(d.canvas.shadowBlurScale??.25));const _t=!!d.canvas.highlightFill||w.perWord;if(d.canvas.glow&&!_t&&(v.fillStyle=d.canvas.fill,v.fillText(tt,P,ot)),d.canvas.stroke&&!_t&&(v.lineWidth=o*(d.canvas.strokeScale??.12),v.strokeStyle=d.canvas.stroke,v.lineJoin="round",v.strokeText(tt,P,ot)),_t){v.shadowBlur=d.canvas.shadowColor?o*(d.canvas.shadowBlurScale??.2):0;const T=tt.split(" "),Tt=v.measureText(tt).width;let L=P-Tt/2;const W=v.measureText(" ").width,q=X.slice(0,mt).reduce((J,gt)=>J+gt.split(" ").length,0);T.forEach((J,gt)=>{const K=v.measureText(J).width,Yt=q+gt;if(w.perWord&&Yt>k){L+=K+W;return}if(v.textAlign="left",d.canvas.boxColor&&(!d.canvas.boxActiveWordOnly||Yt===k)){const si=o*.18,ai=o*.12,qi=v.shadowBlur;v.shadowBlur=0,v.fillStyle=pt??d.canvas.boxColor;const $t=o*.12,St=L-si,Ut=ot-o/2-ai,oe=K+si*2,le=o+ai*2;v.beginPath(),v.moveTo(St+$t,Ut),v.arcTo(St+oe,Ut,St+oe,Ut+le,$t),v.arcTo(St+oe,Ut+le,St,Ut+le,$t),v.arcTo(St,Ut+le,St,Ut,$t),v.arcTo(St,Ut,St+oe,Ut,$t),v.fill(),v.shadowBlur=qi}d.canvas.stroke&&(v.lineWidth=o*(d.canvas.strokeScale??.12),v.strokeStyle=d.canvas.stroke,v.lineJoin="round",v.strokeText(J,L,ot)),v.fillStyle=At&&Yt===k?At:d.canvas.fill,v.fillText(J,L,ot),L+=K+W}),v.textAlign="center"}else v.fillStyle=d.canvas.fill,v.fillText(tt,P,ot)}
1),v.restore()}}function fi(n){const a=Math.max(0,Math.round(n*1e3)),h=Math.floor(a/36e5),l=Math.floor(a%36e5/6e4),f=Math.floor(a%6e4/1e3),d=a%1e3,p=(r,b=2)=>String(r).padStart(b,"0");return`${p(h)}:${p(l)}:${p(f)},${p(d,3)}`}function Ls(n,a,h){return(h&&h.length?h:be(n,a)).map((f,d)=>`${d+1} 2${fi(f.start)} --> ${fi(f.end)} 3${f.words.join(" ")} 4`).join(` 5`)}function ci(n){const a=Math.max(0,Math.round(n*100)),h=Math.floor(a/36e4),l=Math.floor(a%36e4/6e3),f=Math.floor(a%6e3/100),d=a%100,p=r=>String(r).padStart(2,"0");return`${h}:${p(l)}:${p(f)}.${p(d)}`}function ui(n,a="#FFFFFF"){const h=(n||a).replace("#",""),l=h.slice(0,2)||"FF",f=h.slice(2,4)||"FF";return`&H00${h.slice(4,6)||"FF"}${f}${l}`.toUpperCase()}function zr(n,a,h,l,f=1080,d,p){const r=p&&p.length?p:be(n,a),b=(l==null?void 0:l.name)??"Montserrat",S=Math.round(f*h.canvas.fontScale),g=ui(h.canvas.highlightFill||h.canvas.fill),U=ui(h.canvas.stroke||"#000000"),t=Math.max(1,Math.round(S*(h.canvas.strokeScale??.1))),e=((l==null?void 0:l.weight)??h.canvas.weight)>=700?-1:0,i=h.canvas.italic?-1:0,s=d??(h.position==="center"?"center":"bottom"),o=s==="top"?8:s==="center"?5:2,u=s==="center"?0:Math.round(f*.12),c=`[Script Info] 6ScriptType: v4.00+ 7PlayResY: ${f} 8WrapStyle: 2 9 10[V4+ Styles] 11Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, Italic, Outline, Shadow, Alignment, MarginL, MarginR, MarginV 12Style: Caption,${b},${S},${g},${U},&H00000000,${e},${i},${t},1,${o},40,40,${u} 13 14[Events] 15Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text 16`,m=r.map(x=>{const w=(h.uppercase?x.words.join(" ").toUpperCase():x.words.join(" ")).replace(/\n/g," ");return`Dialogue: 0,${ci(x.start)},${ci(x.end)},Caption,,0,0,0,,${w}`}).join(` 17`);return c+m+` 18`}function Ns(n,a){const h=URL.createObjectURL(n),l=document.createElement("a");l.href=h,l.download=a,document.body.appendChild(l),l.click(),l.remove(),setTimeout(()=>URL.revokeObjectURL(h),1e3)}function Ei(){if(typeof MediaRecorder>"u")return null;const n=[{mimeType:"video/mp4;codecs=h264,aac",ext:"mp4"},{mimeType:"video/mp4",ext:"mp4"},{mimeType:"video/webm;codecs=vp9,opus",ext:"webm"},{mimeType:"video/webm;codecs=vp8,opus",ext:"webm"},{mimeType:"video/webm",ext:"webm"}];for(const a of n)if(MediaRecorder.isTypeSupported(a.mimeType))return a;return null}function Ds(){return typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.captureStream=="function"&&Ei()!==null}async function Ms({videoUrl:n,script:a,style:h,font:l,position:f,animationId:d,timedChunks:p,output:r,focus:b,trim:S,zoom:g,onProgress:U,signal:t}){const e=Ei();if(!e)throw new Error("This browser cannot record video. Use the .srt download instead.");let i=null;try{const M=await fetch(n,{mode:"cors"});if(!M.ok)throw new Error(`Could not fetch the video (${M.status}).`);i=URL.createObjectURL(await M.blob())}catch{throw new Error("Could not load the video for captioning. Please try again.")}const s=document.createElement("video");s.src=i,s.muted=!1,s.playsInline=!0,s.setAttribute("playsinline",""),s.style.cssText="position:fixed;left:-99999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none;",document.body.appendChild(s),await new Promise((M,Y)=>{s.onloadedmetadata=()=>M(),s.onerror=()=>Y(new Error("Could not load the video for captioning."))});const o=(r==null?void 0:r.width)||s.videoWidth||1080,u=(r==null?void 0:r.height)||s.videoHeight||1920,c=await He(s);if(!c)throw new Error("Video has no readable duration.");const m=S?Math.max(0,Math.min(S.start,c)):0,x=S?Math.min(c,Math.max(S.end,m+.1)):c,w=S?Math.max(.1,x-m):c,v=document.createElement("canvas");v.width=o,v.height=u,v.style.cssText="position:fixed;left:-99999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none;",document.body.appendChild(v);const E=v.getContext("2d");if(!E)throw v.remove(),new Error("Canvas 2D context unavailable.");const F=await Ci({width:o,height:u,duration:w,script:a,style:h,font:l,position:f,animationId:d,timedChunks:p,focus:b,zoom:g}),C=v.captureStream(0),N=C.getVideoTracks()[0],z=new MediaStream(C.getVideoTracks());try{const M=window.AudioContext||window.webkitAudioContext;if(M){const Y=new M,Q=Y.createMediaElementSource(s),P=Y.createMediaStreamDestination();Q.connect(P),Q.connect(Y.destination),P.stream.getAudioTracks().forEac
18h($=>z.addTrack($))}}catch{}const H=Math.min(48e6,Math.max(12e6,Math.round(o*u*30*.16))),j=new MediaRecorder(z,{mimeType:e.mimeType,videoBitsPerSecond:H,audioBitsPerSecond:192e3}),X=[];j.ondataavailable=M=>{M.data.size>0&&X.push(M.data)};const V=()=>{var Y;const M=Math.max(0,s.currentTime-m);F(E,s,M);try{(Y=N==null?void 0:N.requestFrame)==null||Y.call(N)}catch{}U==null||U(Math.min(99,M/w*100))};return new Promise((M,Y)=>{let Q=0;const P=()=>{cancelAnimationFrame(Q),i&&(URL.revokeObjectURL(i),i=null),v.remove(),s.remove()},$=()=>{if(t!=null&&t.cancelled){j.state!=="inactive"&&j.stop(),s.pause(),P(),Y(new Error("Captioning cancelled."));return}if(V(),S&&s.currentTime>=x){j.state!=="inactive"&&j.stop();try{s.pause()}catch{}return}Q=requestAnimationFrame($)};j.onstop=()=>{P(),U==null||U(100),M({blob:new Blob(X,{type:e.mimeType}),ext:e.ext})},j.onerror=()=>{P(),Y(new Error("Recording failed."))},s.onended=()=>{j.state!=="inactive"&&j.stop()};let k=!1;const ht=()=>{k||(k=!0,s.play().then(()=>{j.start(100),Q=requestAnimationFrame($)}).catch(()=>{P(),Y(new Error("Autoplay blocked â tap the video once, then retry."))}))};if(m>0){const pt=()=>{s.removeEventListener("seeked",pt),ht()};s.addEventListener("seeked",pt);try{s.currentTime=m}catch{ht()}setTimeout(ht,1500)}else ht()})}var Ve=(n,a,h)=>{if(!a.has(n))throw TypeError("Cannot "+h)},_=(n,a,h)=>(Ve(n,a,"read from private field"),h?h.call(n):a.get(n)),D=(n,a,h)=>{if(a.has(n))throw TypeError("Cannot add the same private member more than once");a instanceof WeakSet?a.add(n):a.set(n,h)},st=(n,a,h,l)=>(Ve(n,a,"write to private field"),a.set(n,h),h),Lr=(n,a,h,l)=>({set _(f){st(n,a,f)},get _(){return _(n,a,l)}}),R=(n,a,h)=>(Ve(n,a,"access private method"),h),O=new Uint8Array(8),bt=new DataView(O.buffer),it=n=>[(n%256+256)%256],G=n=>(bt.setUint16(0,n,!1),[O[0],O[1]]),Nr=n=>(bt.setInt16(0,n,!1),[O[0],O[1]]),Ai=n=>(bt.setUint32(0,n,!1),[O[1],O[2],O[3]]),A=n=>(bt.setUint32(0,n,!1),[O[0],O[1],O[2],O[3]]),Dr=n=>(bt.setInt32(0,n,!1),[O[0],O[1],O[2],O[3]]),Dt=n=>(bt.setUint32(0,Math.floor(n/2**32),!1),bt.setUint32(4,n,!1),[O[0],O[1],O[2],O[3],O[4],O[5],O[6],O[7]]),We=n=>(bt.setInt16(0,2**8*n,!1),[O[0],O[1]]),xt=n=>(bt.setInt32(0,2**16*n,!1),[O[0],O[1],O[2],O[3]]),Ae=n=>(bt.setInt32(0,2**30*n,!1),[O[0],O[1],O[2],O[3]]),ct=(n,a=!1)=>{let h=Array(n.length).fill(null).map((l,f)=>n.charCodeAt(f));return a&&h.push(0),h},me=n=>n&&n[n.length-1],Ye=n=>{let a;for(let h of n)(!a||h.presentationTimestamp>a.presentationTimestamp)&&(a=h);return a},vt=(n,a,h=!0)=>{let l=n*a;return h?Math.round(l):l},Ti=n=>{let a=n*(Math.PI/180),h=Math.cos(a),l=Math.sin(a);return[h,l,0,-l,h,0,0,0,1]},Fi=Ti(0),Bi=n=>[xt(n[0]),xt(n[1]),Ae(n[2]),xt(n[3]),xt(n[4]),Ae(n[5]),xt(n[6]),xt(n[7]),Ae(n[8])],te=n=>!n||typeof n!="object"?n:Array.isArray(n)?n.map(te):Object.fromEntries(Object.entries(n).map(([a,h])=>[a,te(h)])),Ht=n=>n>=0&&n<2**32,et=(n,a,h)=>({type:n,contents:a&&new Uint8Array(a.flat(10)),children:h}),Z=(n,a,h,l,f)=>et(n,[it(a),Ai(h),l??[]],f),Mr=n=>{let a=512;return n.fragmented?et("ftyp",[ct("iso5"),A(a),ct("iso5"),ct("iso6"),ct("mp41")]):et("ftyp",[ct("isom"),A(a),ct("isom"),n.holdsAvc?ct("avc1"):[],ct("mp41")])},Ie=n=>({type:"mdat",largeSize:n}),Pr=n=>({type:"free",size:n}),de=(n,a,h=!1)=>et("moov",null,[Rr(a,n),...n.map(l=>Or(l,a)),h?yn(n):null]),Rr=(n,a)=>{let h=vt(Math.max(0,...a.filter(p=>p.samples.length>0).map(p=>{const r=Ye(p.samples);return r.presentationTimestamp+r.duration})),Ne),l=Math.max(...a.map(p=>p.id))+1,f=!Ht(n)||!Ht(h),d=f?Dt:A;return Z("mvhd",+f,0,[d(n),d(n),A(Ne),d(h),xt(1),We(1),Array(10).fill(0),Bi(Fi),Array(24).fill(0),A(l)])},Or=(n,a)=>et("trak",null,[jr(n,a),Gr(n,a)]),jr=(n,a)=>{let h=Ye(n.samples),l=vt(h?h.presentationTimestamp+h.duration:0,Ne),f=!Ht(a)||!Ht(l),d=f?Dt:A,p;return n.info.type==="video"?p=typeof n.info.rotation=="number"?Ti(n.info.rotation):n.info.rotation:p=Fi,Z("tkhd",+f,3,[d(a),d(a),A(n.id),A(0),d(l),Array(8).fill(0),G(0),G(0),We(n.info.type==="audio"?1:0),G(0),Bi(p),xt(n.info.type==="video"?n.info.width:0),xt(n.info.type==="video"?n.info.height:0)])},Gr=(n,a)=>et("mdia",null,[Hr(n,a),Vr(n.info.type==="video"?"vide":"soun"),Wr(n)]),Hr=(n,a)=>{let h=Ye(n.samples),l=vt(h?h.presentationTimestamp+h.duration:0,n.timescale),f=!Ht(a)||!Ht(l),d=f?Dt:A;return Z("mdhd",+f,0,[d(a),d(a),A(n.timescale),d(l),G(21956),G(0)])},Vr=n=>Z("hdlr",0,0,[ct("mhlr"),ct(n),A(0),A(0),A(0),ct("mp4-muxer-hdlr",!0)]),Wr=n=>et("minf",null,[n.info.type==="video"?Yr():$r(),qr(),Zr(n)]),Yr=()=>Z("vmhd",0,1,[G(0),G(0),G(0),G(0)]),$r=()=>Z("smhd",0,0,[G(0),G(0)]),qr=()=>et("dinf",null,[Kr()]),Kr=()=>Z("dref",0,0,[A(1)],[Xr()]),Xr=()=>Z("url ",0,1),Zr=n=>{const a=n.compositionTimeOffsetTable.length>1||n.compositionTimeOffsetTable.some(h=>h.sampleCompositionTimeOffset!==0);return et("stbl",null,[Qr(n),cn(n),un(n),pn(n),mn(n),_n(n),a?gn(n):null])},Qr=n=>Z("stsd",0,0,[A(1)],[n.info.type==="video"?Jr(Tn[n.info.codec],n):hn(Bn[n.info.codec],n)]),Jr=(n,a)=>et(n,[Array(6).fill(0),G(1),G(0),G(0),Array(12).fill(0),G(a.info.width),G(a.info.height),A(4718592),A(4718592),A(0),G(1),Array(32).fill(0),G(24),Nr(65535)],[Fn[a.info.codec](a),a.info.decoderConfig.colorSpace?nn(a):null]),tn={bt709:1,bt470bg:5,smpte170m:6},en={bt709:1,smpte170m:6,"iec61966-2-1":13},rn={rgb:0,bt709:1,bt470bg:5,smpte170m:6},nn=n=>et("colr",[ct("nclx"),G(tn[n.info.decoderConfig.colorSpace.primaries]),G(en[n.info.decoderConfig.colorSpace.transfer]),G(rn[n.info.decoderConfig.colorSpace.matrix]),it((n.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),sn=n=>n.info.decoderConfig&&et("avcC",[...new Uint8Array(n.info.decoderConfig.description)]),an=n=>n.info.decoderConfig&&et("hvcC",[...new Uint8Array(n.info.decoderConfig.description)]),on=n=>{if(!n.info.decoderConfig)return null;let a=n.info.decoderConfig;if(!a.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let h=a.codec.split("."),l=Number(h[1]),f=Number(h[2]),r=(Number(h[3])<<4)+(0<<1)+Number(a.colorSpace.fullRange);return Z("vpcC",1,0,[it(l),it(f),it(r),it(2),it(2),it(2),G(0)])},ln=()=>{let h=(1<<7)+1;return et("av1C",[h,0,0,0])},hn=(n,a)=>et(n,[Array(6).fill(0),G(1),G(0),G(0),A(0),G(a.info.numberOfChannels),G(16),G(0),G(0),xt(a.info.sampleRate)],[kn[a.info.codec](a)]),dn=n=>{let a=new Uint8Array(n.info.decoderConfig.description);return Z("esds",0,0,[A(58753152),it(32+a.byteLength),G(1),it(0),A(75530368),it(18+a.byteLength),it(64),it(21),Ai(0),A(130071),A(130071),A(92307584),it(a.byteLength),...a,A(109084800),it(1),it(2)])},fn=n=>{var f;let a=3840,h=0;const l=(f=n.info.decoderConfig)==null?void 0:f.description;if(l){if(l.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");const d=ArrayBuffer.isView(l)?new DataView(l.buffer,l.byteOffset,l.byteLength):new DataView(l);a=d.getUint16(10,!0),h=d.getInt16(14,!0)}return et("dOps",[it(0),it(n.info.numberOfChannels),G(a),A(n.info.sampleRate),We(h),it(0)])},cn=n=>
18Z("stts",0,0,[A(n.timeToSampleTable.length),n.timeToSampleTable.map(a=>[A(a.sampleCount),A(a.sampleDelta)])]),un=n=>{if(n.samples.every(h=>h.type==="key"))return null;let a=[...n.samples.entries()].filter(([,h])=>h.type==="key");return Z("stss",0,0,[A(a.length),a.map(([h])=>A(h+1))])},pn=n=>Z("stsc",0,0,[A(n.compactlyCodedChunkTable.length),n.compactlyCodedChunkTable.map(a=>[A(a.firstChunk),A(a.samplesPerChunk),A(1)])]),mn=n=>Z("stsz",0,0,[A(0),A(n.samples.length),n.samples.map(a=>A(a.size))]),_n=n=>n.finalizedChunks.length>0&&me(n.finalizedChunks).offset>=2**32?Z("co64",0,0,[A(n.finalizedChunks.length),n.finalizedChunks.map(a=>Dt(a.offset))]):Z("stco",0,0,[A(n.finalizedChunks.length),n.finalizedChunks.map(a=>A(a.offset))]),gn=n=>Z("ctts",0,0,[A(n.compositionTimeOffsetTable.length),n.compositionTimeOffsetTable.map(a=>[A(a.sampleCount),A(a.sampleCompositionTimeOffset)])]),yn=n=>et("mvex",null,n.map(xn)),xn=n=>Z("trex",0,0,[A(n.id),A(1),A(0),A(0),A(0)]),pi=(n,a)=>et("moof",null,[vn(n),...a.map(bn)]),vn=n=>Z("mfhd",0,0,[A(n)]),ki=n=>{let a=0,h=0,l=0,f=0,d=n.type==="delta";return h|=+d,d?a|=1:a|=2,a<<24|h<<16|l<<8|f},bn=n=>et("traf",null,[wn(n),Sn(n),Un(n)]),wn=n=>{let a=0;a|=8,a|=16,a|=32,a|=131072;let h=n.currentChunk.samples[1]??n.currentChunk.samples[0],l={duration:h.timescaleUnitsToNextSample,size:h.size,flags:ki(h)};return Z("tfhd",0,a,[A(n.id),A(l.duration),A(l.size),A(l.flags)])},Sn=n=>Z("tfdt",1,0,[Dt(vt(n.currentChunk.startTimestamp,n.timescale))]),Un=n=>{let a=n.currentChunk.samples.map(s=>s.timescaleUnitsToNextSample),h=n.currentChunk.samples.map(s=>s.size),l=n.currentChunk.samples.map(ki),f=n.currentChunk.samples.map(s=>vt(s.presentationTimestamp-s.decodeTimestamp,n.timescale)),d=new Set(a),p=new Set(h),r=new Set(l),b=new Set(f),S=r.size===2&&l[0]!==l[1],g=d.size>1,U=p.size>1,t=!S&&r.size>1,e=b.size>1||[...b].some(s=>s!==0),i=0;return i|=1,i|=4*+S,i|=256*+g,i|=512*+U,i|=1024*+t,i|=2048*+e,Z("trun",1,i,[A(n.currentChunk.samples.length),A(n.currentChunk.offset-n.currentChunk.moofOffset||0),S?A(l[0]):[],n.currentChunk.samples.map((s,o)=>[g?A(a[o]):[],U?A(h[o]):[],t?A(l[o]):[],e?Dr(f[o]):[]])])},Cn=n=>et("mfra",null,[...n.map(En),An()]),En=(n,a)=>Z("tfra",1,0,[A(n.id),A(63),A(n.finalizedChunks.length),n.finalizedChunks.map(l=>[Dt(vt(l.startTimestamp,n.timescale)),Dt(l.moofOffset),A(a+1),A(1),A(1)])]),An=()=>Z("mfro",0,0,[A(0)]),Tn={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},Fn={avc:sn,hevc:an,vp9:on,av1:ln},Bn={aac:"mp4a",opus:"Opus"},kn={aac:dn,opus:fn},we=class{},$e=class extends we{constructor(){super(...arguments),this.buffer=null}},Ii=class extends we{constructor(n){if(super(),this.options=n,typeof n!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(n.onData){if(typeof n.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(n.onData.length<2)throw new TypeError("options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs.")}if(n.chunked!==void 0&&typeof n.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(n.chunkSize!==void 0&&(!Number.isInteger(n.chunkSize)||n.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.")}},In=class extends we{constructor(n,a){if(super(),this.stream=n,this.options=a,!(n instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(a!==void 0&&typeof a!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(a&&a.chunkSize!==void 0&&(!Number.isInteger(a.chunkSize)||a.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},Bt,Pt,zi=class{constructor(){this.pos=0,D(this,Bt,new Uint8Array(8)),D(this,Pt,new DataView(_(this,Bt).buffer)),this.offsets=new WeakMap}seek(n){this.pos=n}writeU32(n){_(this,Pt).setUint32(0,n,!1),this.write(_(this,Bt).subarray(0,4))}writeU64(n){_(this,Pt).setUint32(0,Math.floor(n/2**32),!1),_(this,Pt).setUint32(4,n,!1),this.write(_(this,Bt).subarray(0,8))}writeAscii(n){for(let a=0;a<n.length;
18a++)_(this,Pt).setUint8(a%8,n.charCodeAt(a)),a%8===7&&this.write(_(this,Bt));n.length%8!==0&&this.write(_(this,Bt).subarray(0,n.length%8))}writeBox(n){if(this.offsets.set(n,this.pos),n.contents&&!n.children)this.writeBoxHeader(n,n.size??n.contents.byteLength+8),this.write(n.contents);else{let a=this.pos;if(this.writeBoxHeader(n,0),n.contents&&this.write(n.contents),n.children)for(let f of n.children)f&&this.writeBox(f);let h=this.pos,l=n.size??h-a;this.seek(a),this.writeBoxHeader(n,l),this.seek(h)}}writeBoxHeader(n,a){this.writeU32(n.largeSize?1:a),this.writeAscii(n.type),n.largeSize&&this.writeU64(a)}measureBoxHeader(n){return 8+(n.largeSize?8:0)}patchBox(n){let a=this.pos;this.seek(this.offsets.get(n)),this.writeBox(n),this.seek(a)}measureBox(n){if(n.contents&&!n.children)return this.measureBoxHeader(n)+n.contents.byteLength;{let a=this.measureBoxHeader(n);if(n.contents&&(a+=n.contents.byteLength),n.children)for(let h of n.children)h&&(a+=this.measureBox(h));return a}}};Bt=new WeakMap;Pt=new WeakMap;var fe,Nt,se,Zt,ce,ze,zn=class extends zi{constructor(n){super(),D(this,ce),D(this,fe,void 0),D(this,Nt,new ArrayBuffer(2**16)),D(this,se,new Uint8Array(_(this,Nt))),D(this,Zt,0),st(this,fe,n)}write(n){R(this,ce,ze).call(this,this.pos+n.byteLength),_(this,se).set(n,this.pos),this.pos+=n.byteLength,st(this,Zt,Math.max(_(this,Zt),this.pos))}finalize(){R(this,ce,ze).call(this,this.pos),_(this,fe).buffer=_(this,Nt).slice(0,Math.max(_(this,Zt),this.pos))}};fe=new WeakMap;Nt=new WeakMap;se=new WeakMap;Zt=new WeakMap;ce=new WeakSet;ze=function(n){let a=_(this,Nt).byteLength;for(;a<n;)a*=2;if(a===_(this,Nt).byteLength)return;let h=new ArrayBuffer(a),l=new Uint8Array(h);l.set(_(this,se),0),st(this,Nt,h),st(this,se,l)};var Ln=2**24,Nn=2,ee,kt,Qt,Et,ft,_e,Le,qe,Li,Ke,Ni,ie,ge,Xe=class extends zi{constructor(n){var a,h;super(),D(this,_e),D(this,qe),D(this,Ke),D(this,ie),D(this,ee,void 0),D(this,kt,[]),D(this,Qt,void 0),D(this,Et,void 0),D(this,ft,[]),st(this,ee,n),st(this,Qt,((a=n.options)==null?void 0:a.chunked)??!1),st(this,Et,((h=n.options)==null?void 0:h.chunkSize)??Ln)}write(n){_(this,kt).push({data:n.slice(),start:this.pos}),this.pos+=n.byteLength}flush(){var h,l;if(_(this,kt).length===0)return;let n=[],a=[..._(this,kt)].sort((f,d)=>f.start-d.start);n.push({start:a[0].start,size:a[0].data.byteLength});for(let f=1;f<a.length;f++){let d=n[n.length-1],p=a[f];p.start<=d.start+d.size?d.size=Math.max(d.size,p.start+p.data.byteLength-d.start):n.push({start:p.start,size:p.data.byteLength})}for(let f of n){f.data=new Uint8Array(f.size);for(let d of _(this,kt))f.start<=d.start&&d.start<f.start+f.size&&f.data.set(d.data,d.start-f.start);_(this,Qt)?(R(this,_e,Le).call(this,f.data,f.start),R(this,ie,ge).call(this)):(l=(h=_(this,ee).options).onData)==null||l.call(h,f.data,f.start)}_(this,kt).length=0}finalize(){_(this,Qt)&&R(this,ie,ge).call(this,!0)}};ee=new WeakMap;kt=new WeakMap;Qt=new WeakMap;Et=new WeakMap;ft=new WeakMap;_e=new WeakSet;Le=function(n,a){let h=_(this,ft).findIndex(r=>r.start<=a&&a<r.start+_(this,Et));h===-1&&(h=R(this,Ke,Ni).call(this,a));let l=_(this,ft)[h],f=a-l.start,d=n.subarray(0,Math.min(_(this,Et)-f,n.byteLength));l.data.set(d,f);let p={start:f,end:f+d.byteLength};if(R(this,qe,Li).call(this,l,p),l.written[0].start===0&&l.written[0].end===_(this,Et)&&(l.shouldFlush=!0),_(this,ft).length>Nn){for(let r=0;r<_(this,ft).length-1;r++)_(this,ft)[r].shouldFlush=!0;R(this,ie,ge).call(this)}d.byteLength<n.byteLength&&R(this,_e,Le).call(this,n.subarray(d.byteLength),a+d.byteLength)};qe=new WeakSet;Li=function(n,a){let h=0,l=n.written.length-1,f=-1;for(;h<=l;){let d=Math.floor(h+(l-h+1)/2);n.written[d].start<=a.start?(h=d+1,f=d):l=d-1}for(n.written.splice(f+1,0,a),(f===-1||n.written[f].end<a.start)&&f++;f<n.written.length-1&&n.written[f].end>=n.written[f+1].start;)n.written[f].end=Math.max(n.written[f].end,n.written[f+1].end),n.written.splice(f+1,1)};Ke=new WeakSet;Ni=function(n){let h={start:Math.floor(n/_(this,Et))*_(this,Et),data:new Uint8Array(_(this,Et)),written:[],shouldFlush:!1};return _(this,ft).push(h),_(this,ft).sort((l,f)=>l.start-f.start),_(this,ft).indexOf(h)};ie=new WeakSet;ge=function(n=!1){var a,h;for(let l=0;l<_(this,ft).length;l++){let f=_(this,ft)[l];if(!(!f.shouldFlush&&!n)){for(let d of f.written)(h=(a=_(this,ee).options).onData)==null||h.call(a,f.data.subarray(d.start,d.end),f.start+d.start);_(this,ft).splice(l--,1)}}};var Dn=class extends Xe{constructor(n){var a;super(new Ii({onData:(h,l)=>n.stream.write({type:"write",data:h,position:l}),chunked:!0,chunkSize:(a=n.options)==null?void 0:a.chunkSize}))}},Ne=1e3,Mn=["avc","hevc","vp9","av1"],Pn=["aac","opus"],Rn=2082844800,On=["strict","offset","cross-track-offset"],B,I,ye,dt,at,nt,Ot,jt,Ze,It,zt,re,De,Di,Me,Mi,Qe,Pi,Pe,Ri,Je,Oi,ue,Re,yt,Ct,ti,ji,ne,xe,ve,ei,Vt,ae,pe,Oe,Gi=class{constructor(n){if(D(this,De),D(this,Me),D(this,Qe),D(this,Pe),D(this,Je),D(this,ue),D(this,yt),D(this,ti),D(this,ne),D(this,ve),D(this,Vt),D(this,pe),D(this,B,void 0),D(this,I,void 0),D(this,ye,void 0),D(this,dt,void 0),D(this,at,null),D(this,nt,null),D(this,Ot,Math.floor(Date.now()/1e3)+Rn),D(this,jt,[]),D(this,Ze,1),D(this,It,[]),D(this,zt,[]),D(this,re,!1),R(this,De,Di).call(this,n),n.video=te(n.video),n.audio=te(n.audio),n.fastStart=te(n.fastStart),this.target=n.target,st(this,B,{firstTimestampBehavior:"strict",...n}),n.target instanceof $e)st(this,I,new zn(n.target));else if(n.target instanceof Ii)st(this,I,new Xe(n.target));else if(n.target instanceof In)st(this,I,new Dn(n.target));else throw new Error(`Invalid target: ${n.target}`);R(this,Pe,Ri).call(this),R(this,Me,Mi).call(this)}addVideoChunk(n,a,h,l){if(!(n instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");if(a&&typeof a!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(h!==void 0&&(!Number.isFinite(h)||h<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");if(l!==void 0&&!Number.isFinite(l))throw new TypeError("addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number.");let f=new Uint8Array(n.byteLength);n.copyTo(f),this.addVideoChunkRaw(f,n.type,h??n.timestamp,n.duration,a,l)}addVideoChunkRaw(n,a,h,l,f,d){if(!(n instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(a!=="key"&&a!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(h)||h<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(l)||l<0)throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");if(f&&typeof f!="object")throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");if(d!==void 0&&!Number.isFinite(d))throw new TypeError("addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number.");if(R(this,pe,Oe).call(this),!_(this,B).video)throw new Error("No video track declared.");
18if(typeof _(this,B).fastStart=="object"&&_(this,at).samples.length===_(this,B).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${_(this,B).fastStart.expectedVideoChunks}).`);let p=R(this,ue,Re).call(this,_(this,at),n,a,h,l,f,d);if(_(this,B).fastStart==="fragmented"&&_(this,nt)){for(;_(this,zt).length>0&&_(this,zt)[0].decodeTimestamp<=p.decodeTimestamp;){let r=_(this,zt).shift();R(this,yt,Ct).call(this,_(this,nt),r)}p.decodeTimestamp<=_(this,nt).lastDecodeTimestamp?R(this,yt,Ct).call(this,_(this,at),p):_(this,It).push(p)}else R(this,yt,Ct).call(this,_(this,at),p)}addAudioChunk(n,a,h){if(!(n instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");if(a&&typeof a!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(h!==void 0&&(!Number.isFinite(h)||h<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let l=new Uint8Array(n.byteLength);n.copyTo(l),this.addAudioChunkRaw(l,n.type,h??n.timestamp,n.duration,a)}addAudioChunkRaw(n,a,h,l,f){if(!(n instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(a!=="key"&&a!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(h)||h<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(l)||l<0)throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");if(f&&typeof f!="object")throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");if(R(this,pe,Oe).call(this),!_(this,B).audio)throw new Error("No audio track declared.");if(typeof _(this,B).fastStart=="object"&&_(this,nt).samples.length===_(this,B).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${_(this,B).fastStart.expectedAudioChunks}).`);let d=R(this,ue,Re).call(this,_(this,nt),n,a,h,l,f);if(_(this,B).fastStart==="fragmented"&&_(this,at)){for(;_(this,It).length>0&&_(this,It)[0].decodeTimestamp<=d.decodeTimestamp;){let p=_(this,It).shift();R(this,yt,Ct).call(this,_(this,at),p)}d.decodeTimestamp<=_(this,at).lastDecodeTimestamp?R(this,yt,Ct).call(this,_(this,nt),d):_(this,zt).push(d)}else R(this,yt,Ct).call(this,_(this,nt),d)}finalize(){if(_(this,re))throw new Error("Cannot finalize a muxer more than once.");if(_(this,B).fastStart==="fragmented"){for(let a of _(this,It))R(this,yt,Ct).call(this,_(this,at),a);for(let a of _(this,zt))R(this,yt,Ct).call(this,_(this,nt),a);R(this,ve,ei).call(this,!1)}else _(this,at)&&R(this,ne,xe).call(this,_(this,at)),_(this,nt)&&R(this,ne,xe).call(this,_(this,nt));let n=[_(this,at),_(this,nt)].filter(Boolean);if(_(this,B).fastStart==="in-memory"){let a;for(let l=0;l<2;l++){let f=de(n,_(this,Ot)),d=_(this,I).measureBox(f);a=_(this,I).measureBox(_(this,dt));let p=_(this,I).pos+d+a;for(let r of _(this,jt)){r.offset=p;for(let{data:b}of r.samples)p+=b.byteLength,a+=b.byteLength}if(p<2**32)break;a>=2**32&&(_(this,dt).largeSize=!0)}let h=de(n,_(this,Ot));_(this,I).writeBox(h),_(this,dt).size=a,_(this,I).writeBox(_(this,dt));for(let l of _(this,jt))for(let f of l.samples)_(this,I).write(f.data),f.data=null}else if(_(this,B).fastStart==="fragmented"){let a=_(this,I).pos,h=Cn(n);_(this,I).writeBox(h);let l=_(this,I).pos-a;_(this,I).seek(_(this,I).pos-4),_(this,I).writeU32(l)}else{let a=_(this,I).offsets.get(_(this,dt)),h=_(this,I).pos-a;_(this,dt).size=h,_(this,dt).largeSize=h>=2**32,_(this,I).patchBox(_(this,dt));let l=de(n,_(this,Ot));if(typeof _(this,B).fastStart=="object"){_(this,I).seek(_(this,ye)),_(this,I).writeBox(l);let f=a-_(this,I).pos;_(this,I).writeBox(Pr(f))}else _(this,I).writeBox(l)}R(this,Vt,ae).call(this),_(this,I).finalize(),st(this,re,!0)}};B=new WeakMap;I=new WeakMap;ye=new WeakMap;dt=new WeakMap;at=new WeakMap;nt=new WeakMap;Ot=new WeakMap;jt=new WeakMap;Ze=new WeakMap;It=new WeakMap;zt=new WeakMap;re=new WeakMap;De=new WeakSet;Di=function(n){if(typeof n!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(n.target instanceof we))throw new TypeError("The target must be provided and an instance of Target.");if(n.video){if(!Mn.includes(n.video.codec))throw new TypeError(`Unsupported video codec: ${n.video.codec}`);if(!Number.isInteger(n.video.width)||n.video.width<=0)throw new TypeError(`Invalid video width: ${n.video.width}. Must be a positive integer.`);if(!Number.isInteger(n.video.height)||n.video.height<=0)throw new TypeError(`Invalid video height: ${n.video.height}. Must be a positive integer.`);const a=n.video.rotation;if(typeof a=="number"&&![0,90,180,270].includes(a))throw new TypeError(`Invalid video rotation: ${a}. Has to be 0, 90, 180 or 270.`);if(Array.isArray(a)&&(a.length!==9||a.some(h=>typeof h!="number")))throw new TypeError(`Invalid video transformation matrix: ${a.join()}`);if(n.video.frameRate!==void 0&&(!Number.isInteger(n.video.frameRate)||n.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${n.video.frameRate}. Must be a positive integer.`)}if(n.audio){if(!Pn.includes(n.audio.codec))throw new TypeError(`Unsupported audio codec: ${n.audio.codec}`);if(!Number.isInteger(n.audio.numberOfChannels)||n.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${n.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(n.audio.sampleRate)||n.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${n.audio.sampleRate}. Must be a positive integer.`)}if(n.firstTimestampBehavior&&!On.includes(n.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${n.firstTimestampBehavior}`);if(typeof n.fastStart=="object"){if(n.video){if(n.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(n.fastStart.expectedVideoChunks)||n.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(n.audio){if(n.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(n.fastStart.expectedAudioChunks)||n.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(n.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");if(n.minFragmentDuration!==void 0&&(!Number.isFinite(n.minFragmentDuration)||n.minFragmentDuration<0))throw new TypeError("'minFragmentDuration' must be a non-negative number.")};Me=new WeakSet;Mi=function(){var n;if(_(this,I).writeBox(Mr({holdsAvc:((n=_(this,B).video)==null?void 0:n.codec)==="avc",fragmented:_(this,B).fastStart==="fragmented"})),st(this,ye,_(this,I).pos),_(this,B).fastStart==="in-memory")st(this,dt,Ie(!1));else if(_(this,B).fastStart!=="fragmented"){if(typeof _(this,B).fastStart=="object"){let a=R(this,Qe,Pi).call(this);_(this,I).seek(_(this,I).pos+a)}st(this,dt,Ie(!0)),_(this,I).writeBox(_(this,dt))}R(this,Vt,ae).call(this)};Qe=new WeakSet;Pi=function(){if(typeof _(this,B).fastStart!="object")return;let n=0,a=[_(this,B).fastStart.expectedVideoChunks,_(this,B).fastStart.expectedAudioChunks];for(let h of a)h&&(n+=8*Math.ceil(2/3*h),n+=4*h,n+=12*Math.ceil(2/3*h),n+=4*h,n+=8*h);return n+=4096,n};Pe=new WeakSet;Ri=function(){if(_(this,B).video&&st(this,at,{id:1,info:{type:"video",codec:_(this,B).video.codec,width:_(this,B).video.width,height:_(this,B).video.height,rotation:_(this,B).video.rotation??0,decoderConfig:null},timescale:_(this,B).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),_(this,B).audio&&(st(this,nt,{id:_(this,B).video?2:1,info:{type:"audio",codec:_(this,B).audio.codec,numberOfChannels:_(this,B).audio.numberOfChannels,sampleRate:_(this,B).audio.sampleRate,decoderConfig:null},timescale:_(this,B).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),_(this,B).audio.codec==="aac")){let n=R(this,Je,Oi).call(this,2,_(this,B).audio.sampleRate,_
18(this,B).audio.numberOfChannels);_(this,nt).info.decoderConfig={codec:_(this,B).audio.codec,description:n,numberOfChannels:_(this,B).audio.numberOfChannels,sampleRate:_(this,B).audio.sampleRate}}};Je=new WeakSet;Oi=function(n,a,h){let f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(a),d=h,p="";p+=n.toString(2).padStart(5,"0"),p+=f.toString(2).padStart(4,"0"),f===15&&(p+=a.toString(2).padStart(24,"0")),p+=d.toString(2).padStart(4,"0");let r=Math.ceil(p.length/8)*8;p=p.padEnd(r,"0");let b=new Uint8Array(p.length/8);for(let S=0;S<p.length;S+=8)b[S/8]=parseInt(p.slice(S,S+8),2);return b};ue=new WeakSet;Re=function(n,a,h,l,f,d,p){let r=l/1e6,b=(l-(p??0))/1e6,S=f/1e6,g=R(this,ti,ji).call(this,r,b,n);return r=g.presentationTimestamp,b=g.decodeTimestamp,d!=null&&d.decoderConfig&&(n.info.decoderConfig===null?n.info.decoderConfig=d.decoderConfig:Object.assign(n.info.decoderConfig,d.decoderConfig)),{presentationTimestamp:r,decodeTimestamp:b,duration:S,data:a,size:a.byteLength,type:h,timescaleUnitsToNextSample:vt(S,n.timescale)}};yt=new WeakSet;Ct=function(n,a){_(this,B).fastStart!=="fragmented"&&n.samples.push(a);const h=vt(a.presentationTimestamp-a.decodeTimestamp,n.timescale);if(n.lastTimescaleUnits!==null){let f=vt(a.decodeTimestamp,n.timescale,!1),d=Math.round(f-n.lastTimescaleUnits);if(n.lastTimescaleUnits+=d,n.lastSample.timescaleUnitsToNextSample=d,_(this,B).fastStart!=="fragmented"){let p=me(n.timeToSampleTable);p.sampleCount===1?(p.sampleDelta=d,p.sampleCount++):p.sampleDelta===d?p.sampleCount++:(p.sampleCount--,n.timeToSampleTable.push({sampleCount:2,sampleDelta:d}));const r=me(n.compositionTimeOffsetTable);r.sampleCompositionTimeOffset===h?r.sampleCount++:n.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:h})}}else n.lastTimescaleUnits=0,_(this,B).fastStart!=="fragmented"&&(n.timeToSampleTable.push({sampleCount:1,sampleDelta:vt(a.duration,n.timescale)}),n.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:h}));n.lastSample=a;let l=!1;if(!n.currentChunk)l=!0;else{let f=a.presentationTimestamp-n.currentChunk.startTimestamp;if(_(this,B).fastStart==="fragmented"){let d=_(this,at)??_(this,nt);const p=_(this,B).minFragmentDuration??1;n===d&&a.type==="key"&&f>=p&&(l=!0,R(this,ve,ei).call(this))}else l=f>=.5}l&&(n.currentChunk&&R(this,ne,xe).call(this,n),n.currentChunk={startTimestamp:a.presentationTimestamp,samples:[]}),n.currentChunk.samples.push(a)};ti=new WeakSet;ji=function(n,a,h){var p,r;const l=_(this,B).firstTimestampBehavior==="strict",f=h.lastDecodeTimestamp===-1;if(l&&f&&a!==0)throw new Error(`The first chunk for your media track must have a timestamp of 0 (received DTS=${a}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want. 19 20If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options. 21`);if(_(this,B).firstTimestampBehavior==="offset"||_(this,B).firstTimestampBehavior==="cross-track-offset"){h.firstDecodeTimestamp===void 0&&(h.firstDecodeTimestamp=a);let b;_(this,B).firstTimestampBehavior==="offset"?b=h.firstDecodeTimestamp:b=Math.min(((p=_(this,at))==null?void 0:p.firstDecodeTimestamp)??1/0,((r=_(this,nt))==null?void 0:r.firstDecodeTimestamp)??1/0),a-=b,n-=b}if(a<h.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (DTS went from ${h.lastDecodeTimestamp*1e6} to ${a*1e6}).`);return h.lastDecodeTimestamp=a,{presentationTimestamp:n,decodeTimestamp:a}};ne=new WeakSet;xe=function(n){if(_(this,B).fastStart==="fragmented")throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");if(n.currentChunk){if(n.finalizedChunks.push(n.currentChunk),_(this,jt).push(n.currentChunk),(n.compactlyCodedChunkTable.length===0||me(n.compactlyCodedChunkTable).samplesPerChunk!==n.currentChunk.samples.length)&&n.compactlyCodedChunkTable.push({firstChunk:n.finalizedChunks.length,samplesPerChunk:n.currentChunk.samples.length}),_(this,B).fastStart==="in-memory"){n.currentChunk.offset=0;return}n.currentChunk.offset=_(this,I).pos;for(let a of n.currentChunk.samples)_(this,I).write(a.data),a.data=null;R(this,Vt,ae).call(this)}};ve=new WeakSet;ei=function(n=!0){if(_(this,B).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let a=[_(this,at),_(this,nt)].filter(r=>r&&r.currentChunk);if(a.length===0)return;let h=Lr(this,Ze)._++;if(h===1){let r=de(a,_(this,Ot),!0);_(this,I).writeBox(r)}let l=_(this,I).pos,f=pi(h,a);_(this,I).writeBox(f);{let r=Ie(!1),b=0;for(let g of a)for(let U of g.currentChunk.samples)b+=U.size;let S=_(this,I).measureBox(r)+b;S>=2**32&&(r.largeSize=!0,S=_(this,I).measureBox(r)+b),r.size=S,_(this,I).writeBox(r)}for(let r of a){r.currentChunk.offset=_(this,I).pos,r.currentChunk.moofOff
21set=l;for(let b of r.currentChunk.samples)_(this,I).write(b.data),b.data=null}let d=_(this,I).pos;_(this,I).seek(_(this,I).offsets.get(f));let p=pi(h,a);_(this,I).writeBox(p),_(this,I).seek(d);for(let r of a)r.finalizedChunks.push(r.currentChunk),_(this,jt).push(r.currentChunk),r.currentChunk=null;n&&R(this,Vt,ae).call(this)};Vt=new WeakSet;ae=function(){_(this,I)instanceof Xe&&_(this,I).flush()};pe=new WeakSet;Oe=function(){if(_(this,re))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};var Hi={};(function(n){var a=function(){var t=new Date,e=4,i=3,s=2,o=1,u=e,c={setLogLevel:function(m){m==this.debug?u=o:m==this.info?u=s:m==this.warn?u=i:(m==this.error,u=e)},debug:function(m,x){console.debug===void 0&&(console.debug=console.log),o>=u&&(""+a.getDurationString(new Date-t,1e3),""+m)},log:function(m,x){this.debug(m.msg)},info:function(m,x){s>=u&&(""+a.getDurationString(new Date-t,1e3),""+m)},warn:function(m,x){i>=u&&console.warn("["+a.getDurationString(new Date-t,1e3)+"]","["+m+"]",x)},error:function(m,x){e>=u&&console.error("["+a.getDurationString(new Date-t,1e3)+"]","["+m+"]",x)}};return c}();a.getDurationString=function(t,e){var i;function s(w,v){for(var E=""+w,F=E.split(".");F[0].length<v;)F[0]="0"+F[0];return F.join(".")}t<0?(i=!0,t=-t):i=!1;var o=e||1,u=t/o,c=Math.floor(u/3600);u-=c*3600;var m=Math.floor(u/60);u-=m*60;var x=u*1e3;return u=Math.floor(u),x-=u*1e3,x=Math.floor(x),(i?"-":"")+c+":"+s(m,2)+":"+s(u,2)+"."+s(x,3)},a.printRanges=function(t){var e=t.length;if(e>0){for(var i="",s=0;s<e;s++)s>0&&(i+=","),i+="["+a.getDurationString(t.start(s))+","+a.getDurationString(t.end(s))+"]";return i}else return"(empty)"},n.Log=a;var h=function(t){if(t instanceof ArrayBuffer)this.buffer=t,this.dataview=new DataView(t);else throw"Needs an array buffer";this.position=0};h.prototype.getPosition=function(){return this.position},h.prototype.getEndPosition=function(){return this.buffer.byteLength},h.prototype.getLength=function(){return this.buffer.byteLength},h.prototype.seek=function(t){var e=Math.max(0,Math.min(this.buffer.byteLength,t));return this.position=isNaN(e)||!isFinite(e)?0:e,!0},h.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},h.prototype.readAnyInt=function(t,e){var i=0;if(this.position+t<=this.buffer.byteLength){switch(t){case 1:e?i=this.dataview.getInt8(this.position):i=this.dataview.getUint8(this.position);break;case 2:e?i=this.dataview.getInt16(this.position):i=this.dataview.getUint16(this.position);break;case 3:if(e)throw"No method for reading signed 24 bits values";i=this.dataview.getUint8(this.position)<<16,i|=this.dataview.getUint8(this.position+1)<<8,i|=this.dataview.getUint8(this.position+2);break;case 4:e?i=this.dataview.getInt32(this.position):i=this.dataview.getUint32(this.position);break;case 8:if(e)throw"No method for reading signed 64 bits values";i=this.dataview.getUint32(this.position)<<32,i|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+t}return this.position+=t,i}else throw"Not enough bytes in buffer"},h.prototype.readUint8=function(){return this.readAnyInt(1,!1)},h.prototype.readUint16=function(){return this.readAnyInt(2,!1)},h.prototype.readUint24=function(){return this.readAnyInt(3,!1)},h.prototype.readUint32=function(){return this.readAnyInt(4,!1)},h.prototype.readUint64=function(){return this.readAnyInt(8,!1)},h.prototype.readString=function(t){if(this.position+t<=this.buffer.byteLength){for(var e="",i=0;i<t;i++)e+=String.fromCharCode(this.readUint8());return e}else throw"Not enough bytes in buffer"},h.prototype.readCString=function(){for(var t=[];;){var e=this.readUint8();if(e!==0)t.push(e);else break}return String.fromCharCode.apply(null,t)},h.prototype.readInt8=function(){return this.readAnyInt(1,!0)},h.prototype.readInt16=function(){return this.readAnyInt(2,!0)},h.prototype.readInt32=function(){return this.readAnyInt(4,!0)},h.prototype.readInt64=function(){return this.readAnyInt(8,!1)},h.prototype.readUint8Array=function(t){for(var e=new Uint8Array(t),i=0;i<t;i++)e[i]=this.readUint8();return e},h.prototype.readInt16Array=function(t){for(var e=new Int16Array(t),i=0;i<t;i++)e[i]=this.readInt16();return e},h.prototype.readUint16Array=function(t){for(var e=new Int16Array(t),i=0;i<t;i++)e[i]=this.readUint16();return e},h.prototype.readUint32Array=function(t){for(var e=new Uint32Array(t),i=0;i<t;i++)e[i]=this.readUint32();return e},h.prototype.readInt32Array=function(t){for(var e=new Int32Array(t),i=0;i<t;i++)e[i]=this.readInt32();return e}
21,n.MP4BoxStream=h;var l=function(t,e,i){this._byteOffset=e||0,t instanceof ArrayBuffer?this.buffer=t:typeof t=="object"?(this.dataView=t,e&&(this._byteOffset+=e)):this.buffer=new ArrayBuffer(t||0),this.position=0,this.endianness=i??l.LITTLE_ENDIAN};l.prototype={},l.prototype.getPosition=function(){return this.position},l.prototype._realloc=function(t){if(this._dynamicSize){var e=this._byteOffset+this.position+t,i=this._buffer.byteLength;if(e<=i){e>this._byteLength&&(this._byteLength=e);return}for(i<1&&(i=1);e>i;)i*=2;var s=new ArrayBuffer(i),o=new Uint8Array(this._buffer),u=new Uint8Array(s,0,o.length);u.set(o),this.buffer=s,this._byteLength=e}},l.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var t=new ArrayBuffer(this._byteLength),e=new Uint8Array(t),i=new Uint8Array(this._buffer,0,e.length);e.set(i),this.buffer=t}},l.BIG_ENDIAN=!1,l.LITTLE_ENDIAN=!0,l.prototype._byteLength=0,Object.defineProperty(l.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(l.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(t){this._buffer=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(l.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(t){this._byteOffset=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(l.prototype,"dataView",{get:function(){return this._dataView},set:function(t){this._byteOffset=t.byteOffset,this._buffer=t.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+t.byteLength}}),l.prototype.seek=function(t){var e=Math.max(0,Math.min(this.byteLength,t));this.position=isNaN(e)||!isFinite(e)?0:e},l.prototype.isEof=function(){return this.position>=this._byteLength},l.prototype.mapUint8Array=function(t){this._realloc(t*1);var e=new Uint8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=t*1,e},l.prototype.readInt32Array=function(t,e){t=t??this.byteLength-this.position/4;var i=new Int32Array(t);return l.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),l.arrayToNative(i,e??this.endianness),this.position+=i.byteLength,i},l.prototype.readInt16Array=function(t,e){t=t??this.byteLength-this.position/2;var i=new Int16Array(t);return l.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),l.arrayToNative(i,e??this.endianness),this.position+=i.byteLength,i},l.prototype.readInt8Array=function(t){t=t??this.byteLength-this.position;var e=new Int8Array(t);return l.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},l.prototype.readUint32Array=function(t,e){t=t??this.byteLength-this.position/4;var i=new Uint32Array(t);return l.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),l.arrayToNative(i,e??this.endianness),this.position+=i.byteLength,i},l.prototype.readUint16Array=function(t,e){t=t??this.byteLength-this.position/2;var i=new Uint16Array(t);return l.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),l.arrayToNative(i,e??this.endianness),this.position+=i.byteLength,i},l.prototype.readUint8Array=function(t){t=t??this.byteLength-this.position;var e=new Uint8Array(t);return l.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},l.prototype.readFloat64Array=function(t,e){t=t??this.byteLength-this.position/8;var i=new Float64Array(t);return l.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),l.arrayToNative(i,e??this.endianness),this.position+=i.byteLength,i},l.prototype.readFloat32Array=function(t,e){t=t??this.byteLength-this.position/4;var i=new Float32Array(t);return l.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),l.arrayToNative(i,e??this.endianness),this.position+=i.byteLength,i},l.prototype.readInt32=function(t){var e=this._dataView.getInt32(this.position,t??this.endianness);return this.position+=4,e},l.prototype.readInt16=function(t){var e=this._dataView.getInt16(this.position,t??this.endianness);return this.position+=2,e},l.prototype.readInt8=function(){var t=this._dataView.getInt8(this.position);return this.position+=1,t},l.prototype.readUint32=function(t){var e=this._dataView.getUint32(this.position,t??this.endianness);return this.position+=4,e},l.prototype.readUint16=function(t){var e=this._dataView.getUint16(this.position,t??this.endianness);return this.position+=2,e},l.prototype.readUint8=function(){var t=this._dataView.getUint8(this.position);return this.position+=1,t},l.prototype.readFloat32=function(t){var e=this._dataView.getFloat32(this.position,t??this.endianness);return this.position+=4,e},l.prototype.readFloat64=function(t){var e=this._dataView.getFloat64(this.position,t??this.endianness);return this.position+=8,e},l.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>
210,l.memcpy=function(t,e,i,s,o){var u=new Uint8Array(t,e,o),c=new Uint8Array(i,s,o);u.set(c)},l.arrayToNative=function(t,e){return e==this.endianness?t:this.flipArrayEndianness(t)},l.nativeToEndian=function(t,e){return this.endianness==e?t:this.flipArrayEndianness(t)},l.flipArrayEndianness=function(t){for(var e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=0;i<t.byteLength;i+=t.BYTES_PER_ELEMENT)for(var s=i+t.BYTES_PER_ELEMENT-1,o=i;s>o;s--,o++){var u=e[o];e[o]=e[s],e[s]=u}return t},l.prototype.failurePosition=0,String.fromCharCodeUint8=function(t){for(var e=[],i=0;i<t.length;i++)e[i]=t[i];return String.fromCharCode.apply(null,e)},l.prototype.readString=function(t,e){return e==null||e=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(t??this.byteLength-this.position)]):new TextDecoder(e).decode(this.mapUint8Array(t))},l.prototype.readCString=function(t){var e=this.byteLength-this.position,i=new Uint8Array(this._buffer,this._byteOffset+this.position),s=e;t!=null&&(s=Math.min(t,e));for(var o=0;o<s&&i[o]!==0;o++);var u=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(o)]);return t!=null?this.position+=s-o:o!=e&&(this.position+=1),u};var f=Math.pow(2,32);l.prototype.readInt64=function(){return this.readInt32()*f+this.readUint32()},l.prototype.readUint64=function(){return this.readUint32()*f+this.readUint32()},l.prototype.readInt64=function(){return this.readUint32()*f+this.readUint32()},l.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},n.DataStream=l,l.prototype.save=function(t){var e=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.setAttribute("href",i),s.setAttribute("download",t),s.setAttribute("target","_self"),s.click(),window.URL.revokeObjectURL(i)}else throw"DataStream.save: Can't create object URL."},l.prototype._dynamicSize=!0,Object.defineProperty(l.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(t){t||this._trimAlloc(),this._dynamicSize=t}}),l.prototype.shift=function(t){var e=new ArrayBuffer(this._byteLength-t),i=new Uint8Array(e),s=new Uint8Array(this._buffer,t,i.length);i.set(s),this.buffer=e,this.position-=t},l.prototype.writeInt32Array=function(t,e){if(this._realloc(t.length*4),t instanceof Int32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)l.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeInt32(t[i],e)},l.prototype.writeInt16Array=function(t,e){if(this._realloc(t.length*2),t instanceof Int16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)l.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt16Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeInt16(t[i],e)},l.prototype.writeInt8Array=function(t){if(this._realloc(t.length*1),t instanceof Int8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)l.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt8Array(t.length);else for(var e=0;e<t.length;e++)this.writeInt8(t[e])},l.prototype.writeUint32Array=function(t,e){if(this._realloc(t.length*4),t instanceof Uint32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)l.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeUint32(t[i],e)},l.prototype.writeUint16Array=function(t,e){if(this._realloc(t.length*2),t instanceof Uint16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)l.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint16Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeUint16(t[i],e)},l.prototype.writeUint8Array=function(t){if(this._realloc(t.length*1),t instanceof Uint8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)l.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint8Array(t.length);else for(var e=0;e<t.length;e++)this.writeUint8(t[e])},l.prototype.writeFloat64Array=function(t,e){if(this._realloc(t.length*8),t instanceof Float64Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)l.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat64Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeFloat64(t[i],e)},l.prototype.writeFloat32Array=function(t,e){if(this._realloc(t.length*4),t instanceof Float32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)l.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeFloat32(t[i],e)},l.prototype.writeInt32=function(t,e){this._realloc(4),this._dataView.setInt32(this.position,t,e??this.endianness),this.position+=4},l.prototype.writeInt16=function(t,e){this._realloc(2),this._dataView.setInt16(this.position,t,e??this.endianness),this.position+=2},l.prototype.writeInt8=function(t){this._realloc(1),this._dataView.setInt8(this.position,t),this.position+=1},l.prototype.writeUint32=function(t,e){this._realloc(4),this._dataView.setUint32(this.position,t,e??this.endianness),this.position+=4},l.prototype.writeUint16=function(t,e){this._realloc(2),this._dataView.setUint16(this.position,t,e??this.endianness),this.position+=2},l.prototype.writeUint8=function(t){this._realloc(1),this._dataView.setUint8(this.position,t),this.position+=1},l.prototype.writeFloat32=function(t,e){this._realloc(4),this._dataView.setFloat32(this.position,t,e??this.endianness),this.position+=4},l.prototype.writeFloat64=function(t,e){this._realloc(8),this._dataView.setFloat64(this.position,t,e??this.endianness),this.position+=8}
21,l.prototype.writeUCS2String=function(t,e,i){i==null&&(i=t.length);for(var s=0;s<t.length&&s<i;s++)this.writeUint16(t.charCodeAt(s),e);for(;s<i;s++)this.writeUint16(0)},l.prototype.writeString=function(t,e,i){var s=0;if(e==null||e=="ASCII")if(i!=null){var o=Math.min(t.length,i);for(s=0;s<o;s++)this.writeUint8(t.charCodeAt(s));for(;s<i;s++)this.writeUint8(0)}else for(s=0;s<t.length;s++)this.writeUint8(t.charCodeAt(s));else this.writeUint8Array(new TextEncoder(e).encode(t.substring(0,i)))},l.prototype.writeCString=function(t,e){var i=0;if(e!=null){var s=Math.min(t.length,e);for(i=0;i<s;i++)this.writeUint8(t.charCodeAt(i));for(;i<e;i++)this.writeUint8(0)}else{for(i=0;i<t.length;i++)this.writeUint8(t.charCodeAt(i));this.writeUint8(0)}},l.prototype.writeStruct=function(t,e){for(var i=0;i<t.length;i+=2){var s=t[i+1];this.writeType(s,e[t[i]],e)}},l.prototype.writeType=function(t,e,i){var s;if(typeof t=="function")return t(this,e);if(typeof t=="object"&&!(t instanceof Array))return t.set(this,e,i);var o=null,u="ASCII",c=this.position;switch(typeof t=="string"&&/:/.test(t)&&(s=t.split(":"),t=s[0],o=parseInt(s[1])),typeof t=="string"&&/,/.test(t)&&(s=t.split(","),t=s[0],u=parseInt(s[1])),t){case"uint8":this.writeUint8(e);break;case"int8":this.writeInt8(e);break;case"uint16":this.writeUint16(e,this.endianness);break;case"int16":this.writeInt16(e,this.endianness);break;case"uint32":this.writeUint32(e,this.endianness);break;case"int32":this.writeInt32(e,this.endianness);break;case"float32":this.writeFloat32(e,this.endianness);break;case"float64":this.writeFloat64(e,this.endianness);break;case"uint16be":this.writeUint16(e,l.BIG_ENDIAN);break;case"int16be":this.writeInt16(e,l.BIG_ENDIAN);break;case"uint32be":this.writeUint32(e,l.BIG_ENDIAN);break;case"int32be":this.writeInt32(e,l.BIG_ENDIAN);break;case"float32be":this.writeFloat32(e,l.BIG_ENDIAN);break;case"float64be":this.writeFloat64(e,l.BIG_ENDIAN);break;case"uint16le":this.writeUint16(e,l.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(e,l.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(e,l.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(e,l.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(e,l.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(e,l.LITTLE_ENDIAN);break;case"cstring":this.writeCString(e,o);break;case"string":this.writeString(e,u,o);break;case"u16string":this.writeUCS2String(e,this.endianness,o);break;case"u16stringle":this.writeUCS2String(e,l.LITTLE_ENDIAN,o);break;case"u16stringbe":this.writeUCS2String(e,l.BIG_ENDIAN,o);break;default:if(t.length==3){for(var m=t[1],x=0;x<e.length;x++)this.writeType(m,e[x]);break}else{this.writeStruct(t,e);break}}o!=null&&(this.position=c,this._realloc(o),this.position=c+o)},l.prototype.writeUint64=function(t){var e=Math.floor(t/f);this.writeUint32(e),this.writeUint32(t&4294967295)},l.prototype.writeUint24=function(t){this.writeUint8((t&16711680)>>16),this.writeUint8((t&65280)>>8),this.writeUint8(t&255)},l.prototype.adjustUint32=function(t,e){var i=this.position;this.seek(t),this.writeUint32(e),this.seek(i)},l.prototype.mapInt32Array=function(t,e){this._realloc(t*4);var i=new Int32Array(this._buffer,this.byteOffset+this.position,t);return l.arrayToNative(i,e??this.endianness),this.position+=t*4,i},l.prototype.mapInt16Array=function(t,e){this._realloc(t*2);var i=new Int16Array(this._buffer,this.byteOffset+this.position,t);return l.arrayToNative(i,e??this.endianness),this.position+=t*2,i},l.prototype.mapInt8Array=function(t){this._realloc(t*1);var e=new Int8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=t*1,e},l.prototype.mapUint32Array=function(t,e){this._realloc(t*4);var i=new Uint32Array(this._buffer,this.byteOffset+this.position,t);return l.arrayToNative(i,e??this.endianness),this.position+=t*4,i},l.prototype.mapUint16Array=function(t,e){this._realloc(t*2);var i=new Uint16Array(this._buffer,this.byteOffset+this.position,t);return l.arrayToNative(i,e??this.endianness),this.position+=t*2,i},l.prototype.mapFloat64Array=function(t,e){this._realloc(t*8);var i=new Float64Array(this._buffer,this.byteOffset+this.position,t);return l.arrayToNative(i,e??this.endianness),this.position+=t*8,i},l.prototype.mapFloat32Array=function(t,e){this._realloc(t*4);var i=new Float32Array(this._buffer,this.byteOffset+this.position,t);return l.arrayToNative(i,e??this.endianness),this.position+=t*4,i};var d=function(t){this.buffers=[],this.bufferIndex=-1,t&&(this.insertBuffer(t),this.bufferIndex=0)};d.prototype=new l(new ArrayBuffer,0,l.BIG_ENDIAN),d.prototype.initialized=function(){var t;return this.bufferIndex>-1?!0:this.buffers.length>0?(t=this.buffers[0],t.fileStart===0?(this.buffer=t,this.bufferIndex=0,a.debug("MultiBufferStream","Stream ready for parsing"),!0):(a.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(a.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(t,e){a.debug("ArrayBuffer","Trying to create a new buffer of size: "+(t.byteLength+e.byteLength));var i=new Uint8Array(t.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(e),t.byteLength),i.buffer}
21,d.prototype.reduceBuffer=function(t,e,i){var s;return s=new Uint8Array(i),s.set(new Uint8Array(t,e,i)),s.buffer.fileStart=t.fileStart+e,s.buffer.usedBytes=0,s.buffer},d.prototype.insertBuffer=function(t){for(var e=!0,i=0;i<this.buffers.length;i++){var s=this.buffers[i];if(t.fileStart<=s.fileStart){if(t.fileStart===s.fileStart)if(t.byteLength>s.byteLength){this.buffers.splice(i,1),i--;continue}else a.warn("MultiBufferStream","Buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+") already appended, ignoring");else t.fileStart+t.byteLength<=s.fileStart||(t=this.reduceBuffer(t,0,s.fileStart-t.fileStart)),a.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.splice(i,0,t),i===0&&(this.buffer=t);e=!1;break}else if(t.fileStart<s.fileStart+s.byteLength){var o=s.fileStart+s.byteLength-t.fileStart,u=t.byteLength-o;if(u>0)t=this.reduceBuffer(t,o,u);else{e=!1;break}}}e&&(a.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.push(t),i===0&&(this.buffer=t))},d.prototype.logBufferLevel=function(t){var e,i,s,o,u=[],c,m="";for(s=0,o=0,e=0;e<this.buffers.length;e++)i=this.buffers[e],e===0?(c={},u.push(c),c.start=i.fileStart,c.end=i.fileStart+i.byteLength,m+="["+c.start+"-"):c.end===i.fileStart?c.end=i.fileStart+i.byteLength:(c={},c.start=i.fileStart,m+=u[u.length-1].end-1+"], ["+c.start+"-",c.end=i.fileStart+i.byteLength,u.push(c)),s+=i.usedBytes,o+=i.byteLength;u.length>0&&(m+=c.end-1+"]");var x=t?a.info:a.debug;this.buffers.length===0?x("MultiBufferStream","No more buffer in memory"):x("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+s+"/"+o+" bytes), continuous ranges: "+m)},d.prototype.cleanBuffers=function(){var t,e;for(t=0;t<this.buffers.length;t++)e=this.buffers[t],e.usedBytes===e.byteLength&&(a.debug("MultiBufferStream","Removing buffer #"+t),this.buffers.splice(t,1),t--)},d.prototype.mergeNextBuffer=function(){var t;if(this.bufferIndex+1<this.buffers.length)if(t=this.buffers[this.bufferIndex+1],t.fileStart===this.buffer.fileStart+this.buffer.byteLength){var e=this.buffer.byteLength,i=this.buffer.usedBytes,s=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,t),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=i,this.buffer.fileStart=s,a.debug("ISOFile","Concatenating buffer for box parsing (length: "+e+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},d.prototype.findPosition=function(t,e,i){var s,o=null,u=-1;for(t===!0?s=0:s=this.bufferIndex;s<this.buffers.length&&(o=this.buffers[s],o.fileStart<=e);){u=s,i&&(o.fileStart+o.byteLength<=e?o.usedBytes=o.byteLength:o.usedBytes=e-o.fileStart,this.logBufferLevel());s++}return u!==-1?(o=this.buffers[u],o.fileStart+o.byteLength>=e?(a.debug("MultiBufferStream","Found position in existing buffer #"+u),u):-1):-1},d.prototype.findEndContiguousBuf=function(t){var e,i,s,o=t!==void 0?t:this.bufferIndex;if(i=this.buffers[o],this.buffers.length>o+1)for(e=o+1;e<this.buffers.length&&(s=this.buffers[e],s.fileStart===i.fileStart+i.byteLength);e++)i=s;return i.fileStart+i.byteLength},d.prototype.getEndFilePositionAfter=function(t){var e=this.findPosition(!0,t,!1);return e!==-1?this.findEndContiguousBuf(e):t},d.prototype.addUsedBytes=function(t){this.buffer.usedBytes+=t,this.logBufferLevel()},d.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},d.prototype.seek=function(t,e,i){var s;return s=this.findPosition(e,t,i),s!==-1?(this.buffer=this.buffers[s],this.bufferIndex=s,this.position=t-this.buffer.fileStart,a.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(a.debug("MultiBufferStream","Position "+t+" not found in buffered data"),!1)},d.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},d.prototype.getLength=function(){return this.byteLength},d.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},n.MultiBufferStream=d;var p=function(){var t=3,e=4,i=5,s=6,o=[];o[t]="ES_Descriptor",o[e]="DecoderConfigDescriptor",o[i]="DecoderSpecificInfo",o[s]="SLConfigDescriptor",this.getDescriptorName=function(m){return o[m]};var u=this,c={};return this.parseOneDescriptor=function(m){var x=0,w,v,E;for(w=m.readUint8(),E=m.readUint8();E&128;)x=(E&127)<<7,E=m.readUint8();return x+=E&127,a.debug("MPEG4DescriptorParser","Found "+(o[w]||"Descriptor "+w)+", size "+x+" at position "+m.getPosition()),o[w]?v=new c[o[w]](x):v=new c.Descriptor(x),v.parse(m),v},c.Descriptor=function(m,x){this.tag=m,this.size=x,this.descs=[]},c.Descriptor.prototype.parse=function(m){this.data=m.readUint8Array(this.size)},c.Descriptor.prototype.findDescriptor=function(m){for(var x=0;x<this.descs.length;x++)if(this.descs[x].tag==m)return this.descs[x];return null},c.Descriptor.prototype.parseRemainingDescriptors=function(m){for(var x=m.position;m.position<x+this.size;){var w=u.parseOneDescriptor(m);this.descs.push(w)}},c.ES_Descriptor=function(m){c.Descriptor.call(this,t,m)},c.ES_Descriptor.prototype=new c.Descriptor,c.ES_Descriptor.prototype.parse=function(m){if(this.ES_ID=m.readUint16(),this.flags=m.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=m.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var x=m.readUint8();this.URL=m.readString(x),this.size-=x+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=m.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(m)},c.ES_Descriptor.prototype.getOTI=function(m){var x=this.findDescriptor(e);return x?x.oti:0},c.ES_Descriptor.prototype.getAudioConfig=function(m){var x=this.findDescriptor(e);
21if(!x)return null;var w=x.findDescriptor(i);if(w&&w.data){var v=(w.data[0]&248)>>3;return v===31&&w.data.length>=2&&(v=32+((w.data[0]&7)<<3)+((w.data[1]&224)>>5)),v}else return null},c.DecoderConfigDescriptor=function(m){c.Descriptor.call(this,e,m)},c.DecoderConfigDescriptor.prototype=new c.Descriptor,c.DecoderConfigDescriptor.prototype.parse=function(m){this.oti=m.readUint8(),this.streamType=m.readUint8(),this.bufferSize=m.readUint24(),this.maxBitrate=m.readUint32(),this.avgBitrate=m.readUint32(),this.size-=13,this.parseRemainingDescriptors(m)},c.DecoderSpecificInfo=function(m){c.Descriptor.call(this,i,m)},c.DecoderSpecificInfo.prototype=new c.Descriptor,c.SLConfigDescriptor=function(m){c.Descriptor.call(this,s,m)},c.SLConfigDescriptor.prototype=new c.Descriptor,this};n.MPEG4DescriptorParser=p;var r={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){r.FullBox.prototype=new r.Box,r.ContainerBox.prototype=new r.Box,r.SampleEntry.prototype=new r.Box,r.TrackGroupTypeBox.prototype=new r.FullBox,r.BASIC_BOXES.forEach(function(t){r.createBoxCtor(t)}),r.FULL_BOXES.forEach(function(t){r.createFullBoxCtor(t)}),r.CONTAINER_BOXES.forEach(function(t){r.createContainerBoxCtor(t[0],null,t[1])})},Box:function(t,e,i){this.type=t,this.size=e,this.uuid=i},FullBox:function(t,e,i){r.Box.call(this,t,e,i),this.flags=0,this.version=0},ContainerBox:function(t,e,i){r.Box.call(this,t,e,i),this.boxes=[]},SampleEntry:function(t,e,i,s){r.ContainerBox.call(this,t,e),this.hdr_size=i,this.start=s},SampleGroupEntry:function(t){this.grouping_type=t},TrackGroupTypeBox:function(t,e){r.FullBox.call(this,t,e)},createBoxCtor:function(t,e){r.boxCodes.push(t),r[t+"Box"]=function(i){r.Box.call(this,t,i)},r[t+"Box"].prototype=new r.Box,e&&(r[t+"Box"].prototype.parse=e)},createFullBoxCtor:function(t,e){r[t+"Box"]=function(i){r.FullBox.call(this,t,i)},r[t+"Box"].prototype=new r.FullBox,r[t+"Box"].prototype.parse=function(i){this.parseFullHeader(i),e&&e.call(this,i)}},addSubBoxArrays:function(t){if(t){this.subBoxNames=t;for(var e=t.length,i=0;i<e;i++)this[t[i]+"s"]=[]}},createContainerBoxCtor:function(t,e,i){r[t+"Box"]=function(s){r.ContainerBox.call(this,t,s),r.addSubBoxArrays.call(this,i)},r[t+"Box"].prototype=new r.ContainerBox,e&&(r[t+"Box"].prototype.parse=e)},createMediaSampleEntryCtor:function(t,e,i){r.sampleEntryCodes[t]=[],r[t+"SampleEntry"]=function(s,o){r.SampleEntry.call(this,s,o),r.addSubBoxArrays.call(this,i)},r[t+"SampleEntry"].prototype=new r.SampleEntry,e&&(r[t+"SampleEntry"].prototype.parse=e)},createSampleEntryCtor:function(t,e,i,s){r.sampleEntryCodes[t].push(e),r[e+"SampleEntry"]=function(o){r[t+"SampleEntry"].call(this,e,o),r.addSubBoxArrays.call(this,s)},r[e+"SampleEntry"].prototype=new r[t+"SampleEntry"],i&&(r[e+"SampleEntry"].prototype.parse=i)},createEncryptedSampleEntryCtor:function(t,e,i){r.createSampleEntryCtor.call(this,t,e,i,["sinf"])},createSampleGroupCtor:function(t,e){r[t+"SampleGroupEntry"]=function(i){r.SampleGroupEntry.call(this,t,i)},r[t+"SampleGroupEntry"].prototype=new r.SampleGroupEntry,e&&(r[t+"SampleGroupEntry"].prototype.parse=e)},createTrackGroupCtor:function(t,e){r[t+"TrackGroupTypeBox"]=function(i){r.TrackGroupTypeBox.call(this,t,i)},r[t+"TrackGroupTypeBox"].prototype=new r.TrackGroupTypeBox,e&&(r[t+"TrackGroupTypeBox"].prototype.parse=e)},createUUIDBox:function(t,e,i,s){r.UUIDs.push(t),r.UUIDBoxes[t]=function(o){e?r.FullBox.call(this,"uuid",o,t):i?r.ContainerBox.call(this,"uuid",o,t):r.Box.call(this,"uuid",o,t)},r.UUIDBoxes[t].prototype=e?new r.FullBox:i?new r.ContainerBox:new r.Box,s&&(e?r.UUIDBoxes[t].prototype.parse=function(o){this.parseFullHeader(o),s&&s.call(this,o)}:r.UUIDBoxes[t].prototype.parse=s)}};r.initialize(),r.TKHD_FLAG_ENABLED=1,r.TKHD_FLAG_IN_MOVIE=2,r.TKHD_FLAG_IN_PREVIEW=4,r.TFHD_FLAG_BASE_DATA_OFFSET=1,r.TFHD_FLAG_SAMPLE_DESC=2,r.TFHD_FLAG_SAMPLE_DUR=8,r.TFHD_FLAG_SAMPLE_SIZE=16,r.TFHD_FLAG_SAMPLE_FLAGS=32,r.TFHD_FLAG_DUR_EMPTY=65536,r.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,r.TRUN_FLAGS_DATA_OFFSET=1,r.TRUN_FLAGS_FIRST_FLAG=4,r.TRUN_FLAGS_DURATION=256,r.TRUN_FLAGS_SIZE=512,r.TRUN_FLAGS_FLAGS=1024,r.TRUN_FLAGS_CTS_OFFSET=2048,r.Box.prototype.add=function(t){return this.addBox(new r[t+"Box"])},r.Box.prototype.addBox=function(t){return this.boxes.push(t),this[t.type+"s"]?this[t.type+"s"].push(t):this[t.type]=t,t},r.Box.prototype.set=function(t,e){return this[t]=e,this},r.Box.prototype.addEntry=function(t,e){var i=e||"entries";return this[i]||(this[i]=[]),this[i].push(t),this},n.BoxParser=r,r.parseUUID=function(t){return r.parseHex16(t)},r.parseHex16=function(t){for(var e="",i=0;i<16;i++){var s=t.readUint8().toString(16);e+=s.length===1?"0"+s:s}return e}
21,r.parseOneBox=function(t,e,i){var s,o=t.getPosition(),u=0,c,m;if(t.getEndPosition()-o<8)return a.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:r.ERR_NOT_ENOUGH_DATA};if(i&&i<8)return a.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:r.ERR_NOT_ENOUGH_DATA};var x=t.readUint32(),w=t.readString(4),v=w;if(a.debug("BoxParser","Found box of type '"+w+"' and size "+x+" at position "+o),u=8,w=="uuid"){if(t.getEndPosition()-t.getPosition()<16||i-u<16)return t.seek(o),a.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:r.ERR_NOT_ENOUGH_DATA};m=r.parseUUID(t),u+=16,v=m}if(x==1){if(t.getEndPosition()-t.getPosition()<8||i&&i-u<8)return t.seek(o),a.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+w+'" box'),{code:r.ERR_NOT_ENOUGH_DATA};x=t.readUint64(),u+=8}else if(x===0){if(i)x=i;else if(w!=="mdat")return a.error("BoxParser","Unlimited box size not supported for type: '"+w+"'"),s=new r.Box(w,x),{code:r.OK,box:s,size:s.size}}return x!==0&&x<u?(a.error("BoxParser","Box of type "+w+" has an invalid size "+x+" (too small to be a box)"),{code:r.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:u,start:o}):x!==0&&i&&x>i?(a.error("BoxParser","Box of type '"+w+"' has a size "+x+" greater than its container size "+i),{code:r.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:u,start:o}):x!==0&&o+x>t.getEndPosition()?(t.seek(o),a.info("BoxParser","Not enough data in stream to parse the entire '"+w+"' box"),{code:r.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:u,start:o}):e?{code:r.OK,type:w,size:x,hdr_size:u,start:o}:(r[w+"Box"]?s=new r[w+"Box"](x):w!=="uuid"?(a.warn("BoxParser","Unknown box type: '"+w+"'"),s=new r.Box(w,x),s.has_unparsed_data=!0):r.UUIDBoxes[m]?s=new r.UUIDBoxes[m](x):(a.warn("BoxParser","Unknown uuid type: '"+m+"'"),s=new r.Box(w,x),s.uuid=m,s.has_unparsed_data=!0),s.hdr_size=u,s.start=o,s.write===r.Box.prototype.write&&s.type!=="mdat"&&(a.info("BoxParser","'"+v+"' box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(t)),s.parse(t),c=t.getPosition()-(s.start+s.size),c<0?(a.warn("BoxParser","Parsing of box '"+v+"' did not read the entire indicated box data size (missing "+-c+" bytes), seeking forward"),t.seek(s.start+s.size)):c>0&&(a.error("BoxParser","Parsing of box '"+v+"' read "+c+" more bytes than the indicated box data size, seeking backwards"),s.size!==0&&t.seek(s.start+s.size)),{code:r.OK,box:s,size:s.size})},r.Box.prototype.parse=function(t){this.type!="mdat"?this.data=t.readUint8Array(this.size-this.hdr_size):this.size===0?t.seek(t.getEndPosition()):t.seek(this.start+this.size)},r.Box.prototype.parseDataAndRewind=function(t){this.data=t.readUint8Array(this.size-this.hdr_size),t.position-=this.size-this.hdr_size},r.FullBox.prototype.parseDataAndRewind=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,t.position-=this.size-this.hdr_size},r.FullBox.prototype.parseFullHeader=function(t){this.version=t.readUint8(),this.flags=t.readUint24(),this.hdr_size+=4},r.FullBox.prototype.parse=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},r.ContainerBox.prototype.parse=function(t){for(var e,i;t.getPosition()<this.start+this.size;)if(e=r.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),e.code===r.OK)if(i=e.box,this.boxes.push(i),this.subBoxNames&&this.subBoxNames.indexOf(i.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(i.type)]+"s"].push(i);else{var s=i.type!=="uuid"?i.type:i.uuid;this[s]?a.warn("Box of type "+s+" already stored in field of this type"):this[s]=i}else return},r.Box.prototype.parseLanguage=function(t){this.language=t.readUint16();var e=[];e[0]=this.language>>10&31,e[1]=this.language>>5&31,e[2]=this.language&31,this.languageString=String.fromCharCode(e[0]+96,e[1]+96,e[2]+96)},r.SAMPLE_ENTRY_TYPE_VISUAL="Visual",r.SAMPLE_ENTRY_TYPE_AUDIO="Audio",r.SAMPLE_ENTRY_TYPE_HINT="Hint",r.SAMPLE_ENTRY_TYPE_METADATA="Metadata",r.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",r.SAMPLE_ENTRY_TYPE_SYSTEM="System",r.SAMPLE_ENTRY_TYPE_TEXT="Text",r.SampleEntry.prototype.parseHeader=function(t){t.readUint8Array(6),this.data_reference_index=t.readUint16(),this.hdr_size+=8},r.SampleEntry.prototype.parse=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},r.SampleEntry.prototype.parseDataAndRewind=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,t.position-=this.size-this.hdr_size},r.SampleEntry.prototype.parseFooter=function(t){r.ContainerBox.prototype.parse.call(this,t)},r.createMediaSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_HINT),r.createMediaSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_METADATA),r.createMediaSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_SUBTITLE),r.createMediaSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_SYSTEM),r.createMediaSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_TEXT),r.createMediaSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,function(t){var e;this.parseHeader(t),t.readUint16(),t.readUint16(),t.readUint32Array(3),this.width=t.readUint16(),this.height=t.readUint16(),this.horizresolution=t.readUint32(),this.vertresolution=t.readUint32(),t.readUint32(),this.frame_count=t.readUint16(),e=Math.min(31,t.readUint8()),this.compressorname=t.readString(e),e<31&&t.readString(31-e),this.depth=t.readUint16(),t.readUint16(),this.parseFooter(t)}),r.createMediaSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_AUDIO,function(t){this.parseHeader(t),t.readUint32Array(2),this.channel_c
21ount=t.readUint16(),this.samplesize=t.readUint16(),t.readUint16(),t.readUint16(),this.samplerate=t.readUint32()/65536,this.parseFooter(t)}),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),r.createEncryptedSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),r.createEncryptedSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),r.createEncryptedSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),r.createEncryptedSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),r.createEncryptedSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_TEXT,"enct"),r.createEncryptedSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_METADATA,"encm"),r.createBoxCtor("a1lx",function(t){var e=t.readUint8()&1,i=((e&1)+1)*16;this.layer_size=[];for(var s=0;s<3;s++)i==16?this.layer_size[s]=t.readUint16():this.layer_size[s]=t.readUint32()}),r.createBoxCtor("a1op",function(t){this.op_index=t.readUint8()}),r.createFullBoxCtor("auxC",function(t){this.aux_type=t.readCString();var e=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=t.readUint8Array(e)}),r.createBoxCtor("av1C",function(t){var e=t.readUint8();if(e>>7&!1){a.error("av1C marker problem");return}if(this.version=e&127,this.version!==1){a.error("av1C version "+this.version+" not supported");return}if(e=t.readUint8(),this.seq_profile=e>>5&7,this.seq_level_idx_0=e&31,e=t.readUint8(),this.seq_tier_0=e>>7&1,this.high_bitdepth=e>>6&1,this.twelve_bit=e>>5&1,this.monochrome=e>>4&1,this.chroma_subsampling_x=e>>3&1,this.chroma_subsampling_y=e>>2&1,this.chroma_sample_position=e&3,e=t.readUint8(),this.reserved_1=e>>5&7,this.reserved_1!==0){a.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=e>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=e&15;else if(this.reserved_2=e&15,this.reserved_2!==0){a.error("av1C reserved_2 parsing problem");return}var i=this.size-this.hdr_size-4;this.configOBUs=t.readUint8Array(i)}),r.createBoxCtor("avcC",function(t){var e,i;for(this.configurationVersion=t.readUint8(),this.AVCProfileIndication=t.readUint8(),this.profile_compatibility=t.readUint8(),this.AVCLevelIndication=t.readUint8(),this.lengthSizeMinusOne=t.readUint8()&3,this.nb_SPS_nalus=t.readUint8()&31,i=this.size-this.hdr_size-6,this.SPS=[],e=0;e<this.nb_SPS_nalus;e++)this.SPS[e]={},this.SPS[e].length=t.readUint16(),this.SPS[e].nalu=t.readUint8Array(this.SPS[e].length),i-=2+this.SPS[e].length;for(this.nb_PPS_nalus=t.readUint8(),i--,this.PPS=[],e=0;e<this.nb_PPS_nalus;e++)this.PPS[e]={},this.PPS[e].length=t.readUint16(),this.PPS[e].nalu=t.readUint8Array(this.PPS[e].length),i-=2+this.PPS[e].length;i>0&&(this.ext=t.readUint8Array(i))}),r.createBoxCtor("btrt",function(t){this.bufferSizeDB=t.readUint32(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32()}),r.createBoxCtor("clap",function(t){this.cleanApertureWidthN=t.readUint32(),this.cleanApertureWidthD=t.readUint32(),this.cleanApertureHeightN=t.readUint32(),this.cleanApertureHeightD=t.readUint32(),this.horizOffN=t.readUint32(),this.horizOffD=t.readUint32(),this.vertOffN=t.readUint32(),this.vertOffD=t.readUint32()}),r.createBoxCtor("clli",function(t){this.max_content_light_level=t.readUint16(),this.max_pic_average_light_level=t.readUint16()}),r.createFullBoxCtor("co64",function(t){var e,i;if(e=t.readUint32(),this.chunk_offsets=[],this.version===0)for(i=0;i<e;i++)this.chunk_offsets.push(t.readUint64())}),r.createFullBoxCtor("CoLL",function(t){this.maxCLL=t.readUint16(),this.maxFALL=t.readUint16()}),r.createBoxCtor("colr",function(t){if(this.colour_type=t.readString(4),this.colour_type==="nclx"){this.colour_primaries=t.readUint16(),this.transfer_characteristics=t.readUint16(),this.matrix_coefficients=t.readUint16();var e=t.readUint8();this.full_range_flag=e>>7}else this.colour_type==="rICC"?this.ICC_profile=t.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=t.readUint8Array(this.size-4))}),r.createFullBoxCtor("cprt",function(t){this.parseLanguage(t),this.notice=t.readCString()}),r.createFullBoxCtor("cslg",function(t){this.version===0&&(this.compositionToDTSShift=t.readInt32(),this.leastDecodeToDisplayDelta=t.readInt32(),this.greatestDecodeToDisplayDelta=t.readInt32(),this.compositionStartTime=t.readInt32(),this.compositionEndTime=t.readInt32())}),r.createFullBoxCtor("ctts",function(t){var e,i;if(e=t.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(i=0;i<e;i++){this.sample_counts.push(t.readUint32());var s=t.readInt32();s<0&&a.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(s)}else if(this.version==1)for(i=0;i<e;i++)this.sample_counts.push(t.readUint32()),this.sample_offsets.push(t.readInt32())}),r.createBoxCtor("dac3",function(t){var e=t.readUint8(),i=t.readUint8(),s=t.readUint8();this.fscod=e>>6,this.bsid=e>>1&31,this.bsmod=(e&1)<<2|i>>6&3,this.acmod=i>>3&7,this.lfeon=i>>2&1,this.bit_rate_code=i&3|s>>5&7}),r.createBoxCtor("dec3",function(t){var e=t.readUint16();this.data_rate=e>>3,this.num_ind_sub=e&7,this.ind_subs=[];for(var i=0;i<this.num_ind_sub+1;i++){var s={};this.ind_subs.push(s);var o=t.readUint8(),u=t.readUint8(),c=t.readUint8();s.fscod=o>>6,s.bsid=o>>1&31,s.bsmod=(o&1)<<4|u>>4&15,s.acmod=u>>1&7,s.lfeon=u&1,s.num_dep_sub=c>>1&15,s.num_dep_sub>0&&(s.chan_loc=(c&1)<<8|t.readUint8())}}),r.createFullBoxCtor("dfLa",function(t){var e=127,i=128,s=[],o=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];this.parseFullHeader(t);do{var u=t.readUint8(),c=Math.min(u&e,o.length-1);if(c?t.readUint8Array(t.readUint24()):(t.readUint8Array(13),this.samplerate=t.readUint32()>>12,t.readUint8Array(20)),s.push(o[c]),u&i)break}while(!0);this.numMetadataBlocks=s.length+" ("+s.join(", ")+")"}),r.createBoxCtor("dimm",function(t){this.bytessent=t.readUint64()}),r.createBoxCtor("dmax",function(t){this.time=t.readUint32()}),r.createBoxCtor("dmed",function(t){this.bytessent=t.readUint64()}),r.createBoxCtor("dOps",function(t){if(this.Version=t.readUint8(),this.OutputChannelCount=t.readUint8(),this.PreSkip=t.readUint16(),this.InputSampleRate=t.readUint32(),this.OutputGain=t.readInt16(),this.ChannelMappingFamily=t.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=t.readUint8(),this.CoupledCount=t.readUint8(),this.ChannelMapping=[];for(var e=0;e<this.OutputChannelCount;e++)this.ChannelMapping[e]=t.readUint8()}}),r.createFullBoxCtor("dref",function(t){var e,i;this.entries=[];for(var s=t.readUint32(),o=0;o<s;o++)if(e=r.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),e.code===r.OK)i=e.box,this.entries.push(i);else return}),r.createBoxCtor("drep",function(t){this.bytessent=t.readUint64()}),r.createFullBoxCtor("elng",function(t){this.extended_language=t.readString(this.size-this.hdr_size)}),r.createFullBoxCtor("elst",function(t){this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var s={};this.entries.push(s),this.version===1?(s.segment_duration=t.readUint64(),s.media_time=t.readInt64()):(s.segment_duration=t.readUint32(),s.media_time=t.readInt32()),s.media_rate_integer=t.readInt16(),s.media_rate_fraction=t.readInt16()}}),r.createFullBoxCtor("emsg",function(t){this.version==1?(this.timescale=t.readUint32(),this.presentation_time=t.readUint64(),this.event_duration=t.readUint32(),this.id=t.readUint32(),this.scheme_id_uri=t.readCString(),this.value=t.readCString()):(this.scheme_id_uri=t.readCString(),this.value=t.readCString(),this.timescale=t.readUint32(),this.presentation_time_delta=t.readUint32(),this.event_duration=t.readUint32(),this.id=t.readUint32());var e=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(e-=4),this.message_data=t.readUint8Array(e)}),r.createFullBoxCtor("esds",function(t){var e=t.readUint8Array(this.size-this.hdr_size);if(typeof p<"u"){var i=new p;this.esd=i.parseOneDescriptor(new l(e.buffer,0,l.BIG_ENDIAN))}}),r.createBoxCtor("fiel",function(t){this.fieldCount=t.readUint8(),this.fieldOrdering=t.readUint8()}),r.createBoxCtor("frma",function(t){this.data_format=t.readString(4)}),r.createBoxCtor("ftyp",function(t){var e=this.size-this.hdr_size;this.major_brand=t.readString(4),this.minor_version=t.readUint32(),e-=8,this.compatible_brands=[];for(var i=0;e>=4;)this.compatible_brands[i]=t.readString(4),e-=4,i++}),r.createFullBoxCtor("hdlr",function(t){this.version===0&&(t.readUint32(),this.handler=t.readString(4),t.readUint32Array(3),this.name=t.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\0"&&(this.name=this.name.slice(0,-1)))}),r.createBoxCtor("hvcC",function(t){var e,i,s,o;this.configurationVersion=t.readUint8(),o=t.readUint8(),this.general_profile_space
21=o>>6,this.general_tier_flag=(o&32)>>5,this.general_profile_idc=o&31,this.general_profile_compatibility=t.readUint32(),this.general_constraint_indicator=t.readUint8Array(6),this.general_level_idc=t.readUint8(),this.min_spatial_segmentation_idc=t.readUint16()&4095,this.parallelismType=t.readUint8()&3,this.chroma_format_idc=t.readUint8()&3,this.bit_depth_luma_minus8=t.readUint8()&7,this.bit_depth_chroma_minus8=t.readUint8()&7,this.avgFrameRate=t.readUint16(),o=t.readUint8(),this.constantFrameRate=o>>6,this.numTemporalLayers=(o&13)>>3,this.temporalIdNested=(o&4)>>2,this.lengthSizeMinusOne=o&3,this.nalu_arrays=[];var u=t.readUint8();for(e=0;e<u;e++){var c=[];this.nalu_arrays.push(c),o=t.readUint8(),c.completeness=(o&128)>>7,c.nalu_type=o&63;var m=t.readUint16();for(i=0;i<m;i++){var x={};c.push(x),s=t.readUint16(),x.data=t.readUint8Array(s)}}}),r.createFullBoxCtor("iinf",function(t){var e;this.version===0?this.entry_count=t.readUint16():this.entry_count=t.readUint32(),this.item_infos=[];for(var i=0;i<this.entry_count;i++)if(e=r.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),e.code===r.OK)e.box.type!=="infe"&&a.error("BoxParser","Expected 'infe' box, got "+e.box.type),this.item_infos[i]=e.box;else return}),r.createFullBoxCtor("iloc",function(t){var e;e=t.readUint8(),this.offset_size=e>>4&15,this.length_size=e&15,e=t.readUint8(),this.base_offset_size=e>>4&15,this.version===1||this.version===2?this.index_size=e&15:this.index_size=0,this.items=[];var i=0;if(this.version<2)i=t.readUint16();else if(this.version===2)i=t.readUint32();else throw"version of iloc box not supported";for(var s=0;s<i;s++){var o={};if(this.items.push(o),this.version<2)o.item_ID=t.readUint16();else if(this.version===2)o.item_ID=t.readUint16();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?o.construction_method=t.readUint16()&15:o.construction_method=0,o.data_reference_index=t.readUint16(),this.base_offset_size){case 0:o.base_offset=0;break;case 4:o.base_offset=t.readUint32();break;case 8:o.base_offset=t.readUint64();break;default:throw"Error reading base offset size"}var u=t.readUint16();o.extents=[];for(var c=0;c<u;c++){var m={};if(o.extents.push(m),this.version===1||this.version===2)switch(this.index_size){case 0:m.extent_index=0;break;case 4:m.extent_index=t.readUint32();break;case 8:m.extent_index=t.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:m.extent_offset=0;break;case 4:m.extent_offset=t.readUint32();break;case 8:m.extent_offset=t.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:m.extent_length=0;break;case 4:m.extent_length=t.readUint32();break;case 8:m.extent_length=t.readUint64();break;default:throw"Error reading extent index"}}}}),r.createBoxCtor("imir",function(t){var e=t.readUint8();this.reserved=e>>7,this.axis=e&1}),r.createFullBoxCtor("infe",function(t){if((this.version===0||this.version===1)&&(this.item_ID=t.readUint16(),this.item_protection_index=t.readUint16(),this.item_name=t.readCString(),this.content_type=t.readCString(),this.content_encoding=t.readCString()),this.version===1){this.extension_type=t.readString(4),a.warn("BoxParser","Cannot parse extension type"),t.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=t.readUint16():this.version===3&&(this.item_ID=t.readUint32()),this.item_protection_index=t.readUint16(),this.item_type=t.readString(4),this.item_name=t.readCString(),this.item_type==="mime"?(this.content_type=t.readCString(),this.content_encoding=t.readCString()):this.item_type==="uri "&&(this.item_uri_type=t.readCString()))}),r.createFullBoxCtor("ipma",function(t){var e,i;for(entry_count=t.readUint32(),this.associations=[],e=0;e<entry_count;e++){var s={};this.associations.push(s),this.version<1?s.id=t.readUint16():s.id=t.readUint32();var o=t.readUint8();for(s.props=[],i=0;i<o;i++){var u=t.readUint8(),c={};s.props.push(c),c.essential=(u&128)>>7===1,this.flags&1?c.property_index=(u&127)<<8|t.readUint8():c.property_index=u&127}}}),r.createFullBoxCtor("iref",function(t){var e,i;for(this.references=[];t.getPosition()<this.start+this.size;)if(e=r.parseOneBox(t,!0,this.size-(t.getPosition()-this.start)),e.code===r.OK)this.version===0?i=new r.SingleItemTypeReferenceBox(e.type,e.size,e.hdr_size,e.start):i=new r.SingleItemTypeReferenceBoxLarge(e.type,e.size,e.hdr_size,e.start),i.write===r.Box.prototype.write&&i.type!=="mdat"&&(a.warn("BoxParser",i.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),i.parseDataAndRewind(t)),i.parse(t),this.references.push(i);else return}),r.createBoxCtor("irot",function(t){this.angle=t.readUint8()&3}),r.createFullBoxCtor("ispe",function(t){this.image_width=t.readUint32(),this.image_height=t.readUint32()}),r.createFullBoxCtor("kind",function(t){this.schemeURI=t.readCString(),this.value=t.readCString()}),r.createFullBoxCtor("leva",function(t){var e=t.readUint8();this.levels=[];for(var i=0;i<e;i++){var s={};this.levels[i]=s,s.track_ID=t.readUint32();var o=t.readUint8();switch(s.padding_flag=o>>7,s.assignment_type=o&127,s.assignment_type){case 0:s.grouping_type=t.readString(4);break;case 1:s.grouping_type=t.readString(4),s.grouping_type_parameter=t.readUint32();break;case 2:break;case 3:break;case 4:s.sub_track_id=t.readUint32();break;default:a.warn("BoxParser","Unknown leva assignement type")}}}),r.createBoxCtor("lsel",function(t){this.layer_id=t.readUint16()}),r.createBoxCtor("maxr",function(t){this.period=t.readUint32(),this.bytes=t.readUint32()}),r.createBoxCtor("mdcv",function(t){this.display_primaries=[],this.display_primaries[0]={},this.display_primaries[0].x=t.readUint16(),this.display_primaries[0].y=t.readUint16(),this.display_primaries[1]={},this.display_primaries[1].x=t.readUint16(),this.display_primaries[1].y=t.readUint16(),this.display_primaries[2]={},this.display_primaries[2].x=t.readUint16(),this.display_primaries[2].y=t.readUint16(),this.white_point={},this.white_point.x=t.readUint16(),this.white_point.y=t.readUint16(),this.max_display_mastering_luminance=t.readUint32(),this.min_display_mastering_luminance=t.readUint32()}),r.createFullBoxCtor("mdhd",function(t){this.version==1?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.timescale=t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.timescale=t.readUint32(),this.duration=t.readUint32()),this.parseLanguage(t),t.readUint16()}),r.createFullBoxCtor("mehd",function(t){this.flags&1&&(a.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=t.readUint64():this.fragment_duration=t.readUint32()}),r.createFullBoxCtor("meta",function(t){this.boxes=[],r.ContainerBox.prototype.parse.call(this,t)}),r.createFullBoxCtor("mfhd",function(t){this.sequence_number=t.readUint32()}),r.createFullBoxCtor("mfro",function(t){this._size=t.readUint32()}),r.createFullBoxCtor("mvhd",function(t){this.version==1?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.timescale=t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.timescale=t.readUint32(),this.duration=t.readUint32()),this.rate=t.readUint32(),this.volume=t.readUint16()>>8,t.readUint16(),t.readUint32Array(2),this.matrix=t.readUint32Array(9),t.readUint32Array(6),this.next_track_id=t.readUint32()}),r.createBoxCtor("npck",function(t){this.packetssent=t.readUint32()}),r.createBoxCtor("nump",function(t){this.packetssent=t.readUint64()}),r.createFullBoxCtor("padb",function(t){var e=t.readUint32();this.padbits=[];for(var i=0;i<Math.floor((e+1)/2);i++)this.padbits=t.readUint8()}),r.createBoxCtor("pasp",function(t){this.hSpacing=t.readUint32(),this.vSpacing=t.readUint32()}),r.createBoxCtor("payl",function(t){this.text=t.readString(this.size-this.hdr_size)}),r.createBoxCtor("payt",function(t){this.payloadID=t.readUint32();var e=t.readUint8();this.rtpmap_string=t.readString(e)}),r.createFullBoxCtor("pdin",function(t){var e=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var i=0;i<e;i++)this.rate[i]=t.readUint32(),this.initial_delay[i]=t.readUint32()}),r.createFullBoxCtor("pitm",function(t){this.version===0?this.item_id=t.readUint16():this.item_id=t.readUint32()}),r.createFullBoxCtor("pixi",function(t){var e;
21for(this.num_channels=t.readUint8(),this.bits_per_channels=[],e=0;e<this.num_channels;e++)this.bits_per_channels[e]=t.readUint8()}),r.createBoxCtor("pmax",function(t){this.bytes=t.readUint32()}),r.createFullBoxCtor("prft",function(t){this.ref_track_id=t.readUint32(),this.ntp_timestamp=t.readUint64(),this.version===0?this.media_time=t.readUint32():this.media_time=t.readUint64()}),r.createFullBoxCtor("pssh",function(t){if(this.system_id=r.parseHex16(t),this.version>0){var e=t.readUint32();this.kid=[];for(var i=0;i<e;i++)this.kid[i]=r.parseHex16(t)}var s=t.readUint32();s>0&&(this.data=t.readUint8Array(s))}),r.createFullBoxCtor("clef",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),r.createFullBoxCtor("enof",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),r.createFullBoxCtor("prof",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),r.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),r.createBoxCtor("rtp ",function(t){this.descriptionformat=t.readString(4),this.sdptext=t.readString(this.size-this.hdr_size-4)}),r.createFullBoxCtor("saio",function(t){this.flags&1&&(this.aux_info_type=t.readUint32(),this.aux_info_type_parameter=t.readUint32());var e=t.readUint32();this.offset=[];for(var i=0;i<e;i++)this.version===0?this.offset[i]=t.readUint32():this.offset[i]=t.readUint64()}),r.createFullBoxCtor("saiz",function(t){this.flags&1&&(this.aux_info_type=t.readUint32(),this.aux_info_type_parameter=t.readUint32()),this.default_sample_info_size=t.readUint8();var e=t.readUint32();if(this.sample_info_size=[],this.default_sample_info_size===0)for(var i=0;i<e;i++)this.sample_info_size[i]=t.readUint8()}),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.namespace=t.readCString(),this.schema_location=t.readCString(),this.parseFooter(t)}),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(t){this.parseHeader(t),this.namespace=t.readCString(),this.schema_location=t.readCString(),this.auxiliary_mime_types=t.readCString(),this.parseFooter(t)}),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(t){this.parseHeader(t),this.displayFlags=t.readUint32(),this.horizontal_justification=t.readInt8(),this.vertical_justification=t.readInt8(),this.bg_color_rgba=t.readUint8Array(4),this.box_record=t.readInt16Array(4),this.style_record=t.readUint8Array(12),this.parseFooter(t)}),r.createSampleEntryCtor(r.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(t){this.parseHeader(t),this.parseFooter(t)}),r.createSampleGroupCtor("alst",function(t){var e,i=t.readUint16();for(this.first_output_sample=t.readUint16(),this.sample_offset=[],e=0;e<i;e++)this.sample_offset[e]=t.readUint32();var s=this.description_length-4-4*i;for(this.num_output_samples=[],this.num_total_samples=[],e=0;e<s/4;e++)this.num_output_samples[e]=t.readUint16(),this.num_total_samples[e]=t.readUint16()}),r.createSampleGroupCtor("avll",function(t){this.layerNumber=t.readUint8(),this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()}),r.createSampleGroupCtor("avss",function(t){this.subSequenceIdentifier=t.readUint16(),this.layerNumber=t.readUint8();var e=t.readUint8();this.durationFlag=e>>7,this.avgRateFlag=e>>6&1,this.durationFlag&&(this.duration=t.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()),this.dependency=[];for(var i=t.readUint8(),s=0;s<i;s++){var o={};this.dependency.push(o),o.subSeqDirectionFlag=t.readUint8(),o.layerNumber=t.readUint8(),o.subSequenceIdentifier=t.readUint16()}}),r.createSampleGroupCtor("dtrt",function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),r.createSampleGroupCtor("mvif",function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),r.createSampleGroupCtor("prol",function(t){this.roll_distance=t.readInt16()}),r.createSampleGroupCtor("rap ",function(t){var e=t.readUint8();this.num_leading_samples_known=e>>7,this.num_leading_samples=e&127}),r.createSampleGroupCtor("rash",function(t){if(this.operation_point_count=t.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)a.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=t.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=t.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var e=0;e<this.operation_point_count;e++)this.available_bitrate[e]=t.readUint32(),this.target_rate_share[e]=t.readUint16()}this.maximum_bitrate=t.readUint32(),this.minimum_bitrate=t.readUint32(),this.discard_priority=t.readUint8()}}),r.createSampleGroupCtor("roll",function(t){this.roll_distance=t.readInt16()}),r.SampleGroupEntry.prototype.parse=function(t){a.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=t.readUint8Array(this.description_length)},r.createSampleGroupCtor("scif",function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),r.createSampleGroupCtor("scnm",function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),r.createSampleGroupCtor("seig",function(t){this.reserved=t.readUint8();var e=t.readUint8();this.crypt_byte_block=e>>4,this.skip_byte_block=e&15,this.isProtected=t.readUint8(),this.Per_Sample_IV_Size=t.readUint8(),this.KID=r.parseHex16(t),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=t.readUint8(),this.constant_IV=t.readUint8Array(this.constant_IV_size))}),r.createSampleGroupCtor("stsa",function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),r.createSampleGroupCtor("sync",function(t){var e=t.readUint8();this.NAL_unit_type=e&63}),r.createSampleGroupCtor("tele",function(t){var e=t.readUint8();this.level_independently_decodable=e>>7}),r.createSampleGroupCtor("tsas",function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),r.createSampleGroupCtor("tscl",function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),r.createSampleGroupCtor("vipr",function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),r.createFullBoxCtor("sbgp",function(t){this.grouping_type=t.readString(4),this.version===1?this.grouping_type_parameter=t.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var s={};this.entries.push(s),s.sample_count=t.readInt32(),s.group_description_index=t.readInt32()}}),r.createFullBoxCtor("schm",function(t){this.scheme_type=t.readString(4),this.scheme_version=t.readUint32(),this.flags&1&&(this.scheme_uri=t.readString(this.size-this.hdr_size-8))}),r.createBoxCtor("sdp ",function(t){this.sdptext=t.readString(this.size-this.hdr_size)}),r.createFullBoxCtor("sdtp",function(t){var e,i=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var s=0;s<i;s++)e=t.readUint8(),this.is_leading[s]=e>>6,this.sample_depends_on[s]=e>>4&3,this.sample_is_depended_on[s]=e>>2&3,this.sample_has_redundancy[s]=e&3}),r.createFullBoxCtor("senc"),r.createFullBoxCtor("sgpd",function(t){this.grouping_type=t.readString(4),a.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=t.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=t.readUint32()),this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var s;r[this.grouping_type+"SampleGroupEntry"]?s=new r[this.grouping_type+"SampleGroupEntry"](this.grouping_type):s=new r.SampleGroupEntry(this.grouping_type),this.entries.push(s),this.version===1?this.default_length===0?s.description_length=t.readUint32():s.description_length=this.default_length:s.description_length=this.default_length,s.write===r.SampleGroupEntry.prototype.write&&(a.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),s.data=t.readUint8Array(s.description_length),t.position-=s.description_length),s.parse(t)}}),r.createFullBoxCtor("sidx",function(t){this.reference_ID=t.readUint32(),this.timescale=t.readUint32(),this.version===0?(this.earliest_presentation_time=t.readUint32(),this.first_offset=t.readUint32()):(this.earliest_presentation_time=t.readUint64(),this.first_offset=t.readUint64()),t.readUint16(),this.references=[];for(var e=t.readUint16(),i=0;i<e;i++){var s={};this.references.push(s);var o=t.readUint32();s.reference_type=o>>31&1,s.referenced_size=o&2147483647,s.subsegment_duration=t.readUint32(),o=t.readUint32(),s.starts_with_SAP=o>>31&1,s.SAP_type=o>>28&7,s.SAP_delta_time=o&268435455}}
21),r.SingleItemTypeReferenceBox=function(t,e,i,s){r.Box.call(this,t,e),this.hdr_size=i,this.start=s},r.SingleItemTypeReferenceBox.prototype=new r.Box,r.SingleItemTypeReferenceBox.prototype.parse=function(t){this.from_item_ID=t.readUint16();var e=t.readUint16();this.references=[];for(var i=0;i<e;i++)this.references[i]=t.readUint16()},r.SingleItemTypeReferenceBoxLarge=function(t,e,i,s){r.Box.call(this,t,e),this.hdr_size=i,this.start=s},r.SingleItemTypeReferenceBoxLarge.prototype=new r.Box,r.SingleItemTypeReferenceBoxLarge.prototype.parse=function(t){this.from_item_ID=t.readUint32();var e=t.readUint16();this.references=[];for(var i=0;i<e;i++)this.references[i]=t.readUint32()},r.createFullBoxCtor("SmDm",function(t){this.primaryRChromaticity_x=t.readUint16(),this.primaryRChromaticity_y=t.readUint16(),this.primaryGChromaticity_x=t.readUint16(),this.primaryGChromaticity_y=t.readUint16(),this.primaryBChromaticity_x=t.readUint16(),this.primaryBChromaticity_y=t.readUint16(),this.whitePointChromaticity_x=t.readUint16(),this.whitePointChromaticity_y=t.readUint16(),this.luminanceMax=t.readUint32(),this.luminanceMin=t.readUint32()}),r.createFullBoxCtor("smhd",function(t){this.balance=t.readUint16(),t.readUint16()}),r.createFullBoxCtor("ssix",function(t){this.subsegments=[];for(var e=t.readUint32(),i=0;i<e;i++){var s={};this.subsegments.push(s),s.ranges=[];for(var o=t.readUint32(),u=0;u<o;u++){var c={};s.ranges.push(c),c.level=t.readUint8(),c.range_size=t.readUint24()}}}),r.createFullBoxCtor("stco",function(t){var e;if(e=t.readUint32(),this.chunk_offsets=[],this.version===0)for(var i=0;i<e;i++)this.chunk_offsets.push(t.readUint32())}),r.createFullBoxCtor("stdp",function(t){var e=(this.size-this.hdr_size)/2;this.priority=[];for(var i=0;i<e;i++)this.priority[i]=t.readUint16()}),r.createFullBoxCtor("sthd"),r.createFullBoxCtor("stri",function(t){this.switch_group=t.readUint16(),this.alternate_group=t.readUint16(),this.sub_track_id=t.readUint32();var e=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var i=0;i<e;i++)this.attribute_list[i]=t.readUint32()}),r.createFullBoxCtor("stsc",function(t){var e,i;if(e=t.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(i=0;i<e;i++)this.first_chunk.push(t.readUint32()),this.samples_per_chunk.push(t.readUint32()),this.sample_description_index.push(t.readUint32())}),r.createFullBoxCtor("stsd",function(t){var e,i,s,o;for(this.entries=[],s=t.readUint32(),e=1;e<=s;e++)if(i=r.parseOneBox(t,!0,this.size-(t.getPosition()-this.start)),i.code===r.OK)r[i.type+"SampleEntry"]?(o=new r[i.type+"SampleEntry"](i.size),o.hdr_size=i.hdr_size,o.start=i.start):(a.warn("BoxParser","Unknown sample entry type: "+i.type),o=new r.SampleEntry(i.type,i.size,i.hdr_size,i.start)),o.write===r.SampleEntry.prototype.write&&(a.info("BoxParser","SampleEntry "+o.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),o.parseDataAndRewind(t)),o.parse(t),this.entries.push(o);else return}),r.createFullBoxCtor("stsg",function(t){this.grouping_type=t.readUint32();var e=t.readUint16();this.group_description_index=[];for(var i=0;i<e;i++)this.group_description_index[i]=t.readUint32()}),r.createFullBoxCtor("stsh",function(t){var e,i;if(e=t.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(i=0;i<e;i++)this.shadowed_sample_numbers.push(t.readUint32()),this.sync_sample_numbers.push(t.readUint32())}),r.createFullBoxCtor("stss",function(t){var e,i;if(i=t.readUint32(),this.version===0)for(this.sample_numbers=[],e=0;e<i;e++)this.sample_numbers.push(t.readUint32())}),r.createFullBoxCtor("stsz",function(t){var e;if(this.sample_sizes=[],this.version===0)for(this.sample_size=t.readUint32(),this.sample_count=t.readUint32(),e=0;e<this.sample_count;e++)this.sample_size===0?this.sample_sizes.push(t.readUint32()):this.sample_sizes[e]=this.sample_size}),r.createFullBoxCtor("stts",function(t){var e,i,s;if(e=t.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(i=0;i<e;i++)this.sample_counts.push(t.readUint32()),s=t.readInt32(),s<0&&(a.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),s=1),this.sample_deltas.push(s)}),r.createFullBoxCtor("stvi",function(t){var e=t.readUint32();this.single_view_allowed=e&3,this.stereo_scheme=t.readUint32();var i=t.readUint32();this.stereo_indication_type=t.readString(i);var s,o;for(this.boxes=[];t.getPosition()<this.start+this.size;)if(s=r.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),s.code===r.OK)o=s.box,this.boxes.push(o),this[o.type]=o;else return}),r.createBoxCtor("styp",function(t){r.ftypBox.prototype.parse.call(this,t)}),r.createFullBoxCtor("stz2",function(t){var e,i;if(this.sample_sizes=[],this.version===0)if(this.reserved=t.readUint24(),this.field_size=t.readUint8(),i=t.readUint32(),this.field_size===4)for(e=0;e<i;e+=2){var s=t.readUint8();this.sample_sizes[e]=s>>4&15,this.sample_sizes[e+1]=s&15}else if(this.field_size===8)for(e=0;e<i;e++)this.sample_sizes[e]=t.readUint8();else if(this.field_size===16)for(e=0;e<i;e++)this.sample_sizes[e]=t.readUint16();else a.error("BoxParser","Error in length field in stz2 box")}),r.createFullBoxCtor("subs",function(t){var e,i,s,o;for(s=t.readUint32(),this.entries=[],e=0;e<s;e++){var u={};
21if(this.entries[e]=u,u.sample_delta=t.readUint32(),u.subsamples=[],o=t.readUint16(),o>0)for(i=0;i<o;i++){var c={};u.subsamples.push(c),this.version==1?c.size=t.readUint32():c.size=t.readUint16(),c.priority=t.readUint8(),c.discardable=t.readUint8(),c.codec_specific_parameters=t.readUint32()}}}),r.createFullBoxCtor("tenc",function(t){if(t.readUint8(),this.version===0)t.readUint8();else{var e=t.readUint8();this.default_crypt_byte_block=e>>4&15,this.default_skip_byte_block=e&15}this.default_isProtected=t.readUint8(),this.default_Per_Sample_IV_Size=t.readUint8(),this.default_KID=r.parseHex16(t),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=t.readUint8(),this.default_constant_IV=t.readUint8Array(this.default_constant_IV_size))}),r.createFullBoxCtor("tfdt",function(t){this.version==1?this.baseMediaDecodeTime=t.readUint64():this.baseMediaDecodeTime=t.readUint32()}),r.createFullBoxCtor("tfhd",function(t){var e=0;this.track_id=t.readUint32(),this.size-this.hdr_size>e&&this.flags&r.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=t.readUint64(),e+=8):this.base_data_offset=0,this.size-this.hdr_size>e&&this.flags&r.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=t.readUint32(),e+=4):this.default_sample_description_index=0,this.size-this.hdr_size>e&&this.flags&r.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=t.readUint32(),e+=4):this.default_sample_duration=0,this.size-this.hdr_size>e&&this.flags&r.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=t.readUint32(),e+=4):this.default_sample_size=0,this.size-this.hdr_size>e&&this.flags&r.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=t.readUint32(),e+=4):this.default_sample_flags=0}),r.createFullBoxCtor("tfra",function(t){this.track_ID=t.readUint32(),t.readUint24();var e=t.readUint8();this.length_size_of_traf_num=e>>4&3,this.length_size_of_trun_num=e>>2&3,this.length_size_of_sample_num=e&3,this.entries=[];for(var i=t.readUint32(),s=0;s<i;s++)this.version===1?(this.time=t.readUint64(),this.moof_offset=t.readUint64()):(this.time=t.readUint32(),this.moof_offset=t.readUint32()),this.traf_number=t["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=t["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=t["readUint"+8*(this.length_size_of_sample_num+1)]()}),r.createFullBoxCtor("tkhd",function(t){this.version==1?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.track_id=t.readUint32(),t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.track_id=t.readUint32(),t.readUint32(),this.duration=t.readUint32()),t.readUint32Array(2),this.layer=t.readInt16(),this.alternate_group=t.readInt16(),this.volume=t.readInt16()>>8,t.readUint16(),this.matrix=t.readInt32Array(9),this.width=t.readUint32(),this.height=t.readUint32()}),r.createBoxCtor("tmax",function(t){this.time=t.readUint32()}),r.createBoxCtor("tmin",function(t){this.time=t.readUint32()}),r.createBoxCtor("totl",function(t){this.bytessent=t.readUint32()}),r.createBoxCtor("tpay",function(t){this.bytessent=t.readUint32()}),r.createBoxCtor("tpyl",function(t){this.bytessent=t.readUint64()}),r.TrackGroupTypeBox.prototype.parse=function(t){this.parseFullHeader(t),this.track_group_id=t.readUint32()},r.createTrackGroupCtor("msrc"),r.TrackReferenceTypeBox=function(t,e,i,s){r.Box.call(this,t,e),this.hdr_size=i,this.start=s},r.TrackReferenceTypeBox.prototype=new r.Box,r.TrackReferenceTypeBox.prototype.parse=function(t){this.track_ids=t.readUint32Array((this.size-this.hdr_size)/4)},r.trefBox.prototype.parse=function(t){for(var e,i;t.getPosition()<this.start+this.size;)if(e=r.parseOneBox(t,!0,this.size-(t.getPosition()-this.start)),e.code===r.OK)i=new r.TrackReferenceTypeBox(e.type,e.size,e.hdr_size,e.start),i.write===r.Box.prototype.write&&i.type!=="mdat"&&(a.info("BoxParser","TrackReference "+i.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),i.parseDataAndRewind(t)),i.parse(t),this.boxes.push(i);else return},r.createFullBoxCtor("trep",function(t){for(this.track_ID=t.readUint32(),this.boxes=[];t.getPosition()<this.start+this.size;)if(ret=r.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),ret.code===r.OK)box=ret.box,this.boxes.push(box);else return}),r.createFullBoxCtor("trex",function(t){this.track_id=t.readUint32(),this.default_sample_description_index=t.readUint32(),this.default_sample_duration=t.readUint32(),this.default_sample_size=t.readUint32(),this.default_sample_flags=t.readUint32()}),r.createBoxCtor("trpy",function(t){this.bytessent=t.readUint64()}),r.createFullBoxCtor("trun",function(t){var e=0;if(this.sample_count=t.readUint32(),e+=4,this.size-this.hdr_size>e&&this.flags&r.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=t.readInt32(),e+=4):this.data_offset=0,this.size-this.hdr_size>e&&this.flags&r.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=t.readUint32(),e+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>e)for(var i=0;i<this.sample_count;i++)this.flags&r.TRUN_FLAGS_DURATION&&(this.sample_duration[i]=t.readUint32()),this.flags&r.TRUN_FLAGS_SIZE&&(this.sample_size[i]=t.readUint32()),this.flags&r.TRUN_FLAGS_FLAGS&&(this.sample_flags[i]=t.readUint32()),this.flags&r.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[i]=t.readUint32():this.sample_composition_time_offset[i]=t.readInt32())}),r.createFullBoxCtor("tsel",function(t){this.switch_group=t.readUint32();var e=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var i=0;i<e;i++)this.attribute_list[i]=t.readUint32()}),r.createFullBoxCtor("txtC",function(t){this.config=t.readCString()}),r.createFullBoxCtor("url ",function(t){this.flags!==1&&(this.location=t.readCString())}),r.createFullBoxCtor("urn ",function(t){this.name=t.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=t.readCString())}),r.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,function(t){this.LiveServerManifest=t.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}),r.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(t){this.system_id=r.parseHex16(t);var e=t.readUint32();e>0&&(this.data=t.readUint8Array(e))}),r.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),r.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(t){this.default_AlgorithmID=t.readUint24(),this.default_IV_size=t.readUint8(),this.default_KID=r.parseHex16(t)}),r.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(t){this.fragment_c
21ount=t.readUint8(),this.entries=[];for(var e=0;e<this.fragment_count;e++){var i={},s=0,o=0;this.version===1?(s=t.readUint64(),o=t.readUint64()):(s=t.readUint32(),o=t.readUint32()),i.absolute_time=s,i.absolute_duration=o,this.entries.push(i)}}),r.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,function(t){this.version===1?(this.absolute_time=t.readUint64(),this.duration=t.readUint64()):(this.absolute_time=t.readUint32(),this.duration=t.readUint32())}),r.createFullBoxCtor("vmhd",function(t){this.graphicsmode=t.readUint16(),this.opcolor=t.readUint16Array(3)}),r.createFullBoxCtor("vpcC",function(t){var e;this.version===1?(this.profile=t.readUint8(),this.level=t.readUint8(),e=t.readUint8(),this.bitDepth=e>>4,this.chromaSubsampling=e>>1&7,this.videoFullRangeFlag=e&1,this.colourPrimaries=t.readUint8(),this.transferCharacteristics=t.readUint8(),this.matrixCoefficients=t.readUint8(),this.codecIntializationDataSize=t.readUint16(),this.codecIntializationData=t.readUint8Array(this.codecIntializationDataSize)):(this.profile=t.readUint8(),this.level=t.readUint8(),e=t.readUint8(),this.bitDepth=e>>4&15,this.colorSpace=e&15,e=t.readUint8(),this.chromaSubsampling=e>>4&15,this.transferFunction=e>>1&7,this.videoFullRangeFlag=e&1,this.codecIntializationDataSize=t.readUint16(),this.codecIntializationData=t.readUint8Array(this.codecIntializationDataSize))}),r.createBoxCtor("vttC",function(t){this.text=t.readString(this.size-this.hdr_size)}),r.createFullBoxCtor("vvcC",function(t){var e,i,s={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(C){this.held_bits=C.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(C){this.held_bits=C.readUint16(),this.num_held_bits=16},extract_bits:function(C){var N=this.held_bits>>this.num_held_bits-C&(1<<C)-1;return this.num_held_bits-=C,N}};if(s.stream_read_1_bytes(t),s.extract_bits(5),this.lengthSizeMinusOne=s.extract_bits(2),this.ptl_present_flag=s.extract_bits(1),this.ptl_present_flag){s.stream_read_2_bytes(t),this.ols_idx=s.extract_bits(9),this.num_sublayers=s.extract_bits(3),this.constant_frame_rate=s.extract_bits(2),this.chroma_format_idc=s.extract_bits(2),s.stream_read_1_bytes(t),this.bit_depth_minus8=s.extract_bits(3),s.extract_bits(5);{if(s.stream_read_2_bytes(t),s.extract_bits(2),this.num_bytes_constraint_info=s.extract_bits(6),this.general_profile_idc=s.extract_bits(7),this.general_tier_flag=s.extract_bits(1),this.general_level_idc=t.readUint8(),s.stream_read_1_bytes(t),this.ptl_frame_only_constraint_flag=s.extract_bits(1),this.ptl_multilayer_enabled_flag=s.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(e=0;e<this.num_bytes_constraint_info-1;e++){var o=s.extract_bits(6);s.stream_read_1_bytes(t);var u=s.extract_bits(2);this.general_constraint_info[e]=o<<2|u}this.general_constraint_info[this.num_bytes_constraint_info-1]=s.extract_bits(6)}else s.extract_bits(6);for(s.stream_read_1_bytes(t),this.ptl_sublayer_present_mask=0,i=this.num_sublayers-2;i>=0;--i){var c=s.extract_bits(1);this.ptl_sublayer_present_mask|=c<<i}for(i=this.num_sublayers;i<=8&&this.num_sublayers>1;++i)s.extract_bits(1);for(i=this.num_sublayers-2;i>=0;--i)this.ptl_sublayer_present_mask&1<<i&&(this.sublayer_level_idc[i]=t.readUint8());if(this.ptl_num_sub_profiles=t.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(e=0;e<this.ptl_num_sub_profiles;e++)this.general_sub_profile_idc.push(t.readUint32())}this.max_picture_width=t.readUint16(),this.max_picture_height=t.readUint16(),this.avg_frame_rate=t.readUint16()}var m=12,x=13;this.nalu_arrays=[];var w=t.readUint8();for(e=0;e<w;e++){var v=[];this.nalu_arrays.push(v),s.stream_read_1_bytes(t),v.completeness=s.extract_bits(1),s.extract_bits(2),v.nalu_type=s.extract_bits(5);var E=1;for(v.nalu_type!=x&&v.nalu_type!=m&&(E=t.readUint16()),i=0;i<E;i++){var F=t.readUint16();v.push({data:t.readUint8Array(F),length:F})}}}),r.createFullBoxCtor("vvnC",function(t){var e=strm.readUint8();this.lengthSizeMinusOne=e&3}),r.SampleEntry.prototype.isVideo=function(){return!1},r.SampleEntry.prototype.isAudio=function(){return!1},r.SampleEntry.prototype.isSubtitle=function(){return!1},r.SampleEntry.prototype.isMetadata=function(){return!1},r.SampleEntry.prototype.isHint=function(){return!1},r.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},r.SampleEntry.prototype.getWidth=function(){return""},r.SampleEntry.prototype.getHeight=function(){return""},r.SampleEntry.prototype.getChannelCount=function(){return""},r.SampleEntry.prototype.getSampleRate=function(){return""},r.SampleEntry.prototype.getSampleSize=function(){return""},r.VisualSampleEntry.prototype.isVideo=function(){return!0},r.VisualSampleEntry.prototype.getWidth=function(){return this.width},r.VisualSampleEntry.prototype.getHeight=function(){return this.height},r.AudioSampleEntry.prototype.isAudio=function(){return!0},r.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_c
21ount},r.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},r.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},r.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},r.MetadataSampleEntry.prototype.isMetadata=function(){return!0},r.decimalToHex=function(t,e){var i=Number(t).toString(16);for(e=typeof e>"u"||e===null?e=2:e;i.length<e;)i="0"+i;return i},r.avc1SampleEntry.prototype.getCodec=r.avc2SampleEntry.prototype.getCodec=r.avc3SampleEntry.prototype.getCodec=r.avc4SampleEntry.prototype.getCodec=function(){var t=r.SampleEntry.prototype.getCodec.call(this);return this.avcC?t+"."+r.decimalToHex(this.avcC.AVCProfileIndication)+r.decimalToHex(this.avcC.profile_compatibility)+r.decimalToHex(this.avcC.AVCLevelIndication):t},r.hev1SampleEntry.prototype.getCodec=r.hvc1SampleEntry.prototype.getCodec=function(){var t,e=r.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(e+=".",this.hvcC.general_profile_space){case 0:e+="";break;case 1:e+="A";break;case 2:e+="B";break;case 3:e+="C";break}e+=this.hvcC.general_profile_idc,e+=".";var i=this.hvcC.general_profile_compatibility,s=0;for(t=0;t<32&&(s|=i&1,t!=31);t++)s<<=1,i>>=1;e+=r.decimalToHex(s,0),e+=".",this.hvcC.general_tier_flag===0?e+="L":e+="H",e+=this.hvcC.general_level_idc;var o=!1,u="";for(t=5;t>=0;t--)(this.hvcC.general_constraint_indicator[t]||o)&&(u="."+r.decimalToHex(this.hvcC.general_constraint_indicator[t],0)+u,o=!0);e+=u}return e},r.vvc1SampleEntry.prototype.getCodec=r.vvi1SampleEntry.prototype.getCodec=function(){var t,e=r.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){e+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?e+=".H":e+=".L",e+=this.vvcC.general_level_idc;var i="";if(this.vvcC.general_constraint_info){var s=[],o=0;o|=this.vvcC.ptl_frame_only_constraint<<7,o|=this.vvcC.ptl_multilayer_enabled<<6;var u;for(t=0;t<this.vvcC.general_constraint_info.length;++t)o|=this.vvcC.general_constraint_info[t]>>2&63,s.push(o),o&&(u=t),o=this.vvcC.general_constraint_info[t]>>2&3;if(u===void 0)i=".CA";else{i=".C";var c="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",m=0,x=0;for(t=0;t<=u;++t)for(m=m<<8|s[t],x+=8;x>=5;){var w=m>>x-5&31;i+=c[w],x-=5,m&=(1<<x)-1}x&&(m<<=5-x,i+=c[m&31])}}e+=i}return e},r.mp4aSampleEntry.prototype.getCodec=function(){var t=r.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var e=this.esds.esd.getOTI(),i=this.esds.esd.getAudioConfig();return t+"."+r.decimalToHex(e)+(i?"."+i:"")}else return t},r.stxtSampleEntry.prototype.getCodec=function(){var t=r.SampleEntry.prototype.getCodec.call(this);return this.mime_format?t+"."+this.mime_format:t},r.vp08SampleEntry.prototype.getCodec=r.vp09SampleEntry.prototype.getCodec=function(){var t=r.SampleEntry.prototype.getCodec.call(this),e=this.vpcC.level;e==0&&(e="00");var i=this.vpcC.bitDepth;return i==8&&(i="08"),t+".0"+this.vpcC.profile+"."+e+"."+i},r.av01SampleEntry.prototype.getCodec=function(){var t=r.SampleEntry.prototype.getCodec.call(this),e=this.av1C.seq_level_idx_0;e<10&&(e="0"+e);var i;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?i=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(i=this.av1C.high_bitdepth===1?"10":"08"),t+"."+this.av1C.seq_profile+"."+e+(this.av1C.seq_tier_0?"H":"M")+"."+i},r.Box.prototype.writeHeader=function(t,e){this.size+=8,this.size>f&&(this.size+=8),this.type==="uuid"&&(this.size+=16),a.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+t.getPosition()+(e||"")),this.size>f?t.writeUint32(1):(this.sizePosition=t.getPosition(),t.writeUint32(this.size)),t.writeString(this.type,null,4),this.type==="uuid"&&t.writeUint8Array(this.uuid),this.size>f&&t.writeUint64(this.size)},r.FullBox.prototype.writeHeader=function(t){this.size+=4,r.Box.prototype.writeHeader.call(this,t," v="+this.version+" f="+this.flags),t.writeUint8(this.version),t.writeUint24(this.flags)},r.Box.prototype.write=function(t){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(t),t.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(t),this.data&&t.writeUint8Array(this.data))},r.ContainerBox.prototype.write=function(t){this.size=0,this.writeHeader(t);for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&(this.boxes[e].write(t),this.size+=this.boxes[e].size);a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},r.TrackReferenceTypeBox.prototype.write=function(t){this.size=this.track_ids.length*4,this.writeHeader(t),t.writeUint32Array(this.track_ids)},r.avcCBox.prototype.write=function(t){var e;
21for(this.size=7,e=0;e<this.SPS.length;e++)this.size+=2+this.SPS[e].length;for(e=0;e<this.PPS.length;e++)this.size+=2+this.PPS[e].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(t),t.writeUint8(this.configurationVersion),t.writeUint8(this.AVCProfileIndication),t.writeUint8(this.profile_compatibility),t.writeUint8(this.AVCLevelIndication),t.writeUint8(this.lengthSizeMinusOne+252),t.writeUint8(this.SPS.length+224),e=0;e<this.SPS.length;e++)t.writeUint16(this.SPS[e].length),t.writeUint8Array(this.SPS[e].nalu);for(t.writeUint8(this.PPS.length),e=0;e<this.PPS.length;e++)t.writeUint16(this.PPS[e].length),t.writeUint8Array(this.PPS[e].nalu);this.ext&&t.writeUint8Array(this.ext)},r.co64Box.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(t),t.writeUint32(this.chunk_offsets.length),e=0;e<this.chunk_offsets.length;e++)t.writeUint64(this.chunk_offsets[e])},r.cslgBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(t),t.writeInt32(this.compositionToDTSShift),t.writeInt32(this.leastDecodeToDisplayDelta),t.writeInt32(this.greatestDecodeToDisplayDelta),t.writeInt32(this.compositionStartTime),t.writeInt32(this.compositionEndTime)},r.cttsBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(t),t.writeUint32(this.sample_counts.length),e=0;e<this.sample_counts.length;e++)t.writeUint32(this.sample_counts[e]),this.version===1?t.writeInt32(this.sample_offsets[e]):t.writeUint32(this.sample_offsets[e])},r.drefBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++)this.entries[e].write(t),this.size+=this.entries[e].size;a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},r.elngBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(t),t.writeString(this.extended_language)},r.elstBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(t),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++){var i=this.entries[e];t.writeUint32(i.segment_duration),t.writeInt32(i.media_time),t.writeInt16(i.media_rate_integer),t.writeInt16(i.media_rate_fraction)}},r.emsgBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(t),t.writeCString(this.scheme_id_uri),t.writeCString(this.value),t.writeUint32(this.timescale),t.writeUint32(this.presentation_time_delta),t.writeUint32(this.event_duration),t.writeUint32(this.id),t.writeUint8Array(this.message_data)},r.ftypBox.prototype.write=function(t){this.size=8+4*this.compatible_brands.length,this.writeHeader(t),t.writeString(this.major_brand,null,4),t.writeUint32(this.minor_version);for(var e=0;e<this.compatible_brands.length;e++)t.writeString(this.compatible_brands[e],null,4)},r.hdlrBox.prototype.write=function(t){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(t),t.writeUint32(0),t.writeString(this.handler,null,4),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeCString(this.name)},r.kindBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(t),t.writeCString(this.schemeURI),t.writeCString(this.value)},r.mdhdBox.prototype.write=function(t){this.size=4*4+2*2,this.flags=0,this.version=0,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.timescale),t.writeUint32(this.duration),t.writeUint16(this.language),t.writeUint16(0)},r.mehdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.fragment_duration)},r.mfhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.sequence_number)},r.mvhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=23*4+2*2,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.timescale),t.writeUint32(this.duration),t.writeUint32(this.rate),t.writeUint16(this.volume<<8),t.writeUint16(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32Array(this.matrix
21),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(this.next_track_id)},r.SampleEntry.prototype.writeHeader=function(t){this.size=8,r.Box.prototype.writeHeader.call(this,t),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint16(this.data_reference_index)},r.SampleEntry.prototype.writeFooter=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t),this.size+=this.boxes[e].size;a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},r.SampleEntry.prototype.write=function(t){this.writeHeader(t),t.writeUint8Array(this.data),this.size+=this.data.length,a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},r.VisualSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=2*7+6*4+32,t.writeUint16(0),t.writeUint16(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint16(this.width),t.writeUint16(this.height),t.writeUint32(this.horizresolution),t.writeUint32(this.vertresolution),t.writeUint32(0),t.writeUint16(this.frame_count),t.writeUint8(Math.min(31,this.compressorname.length)),t.writeString(this.compressorname,null,31),t.writeUint16(this.depth),t.writeInt16(-1),this.writeFooter(t)},r.AudioSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=2*4+3*4,t.writeUint32(0),t.writeUint32(0),t.writeUint16(this.channel_count),t.writeUint16(this.samplesize),t.writeUint16(0),t.writeUint16(0),t.writeUint32(this.samplerate<<16),this.writeFooter(t)},r.stppSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,t.writeCString(this.namespace),t.writeCString(this.schema_location),t.writeCString(this.auxiliary_mime_types),this.writeFooter(t)},r.SampleGroupEntry.prototype.write=function(t){t.writeUint8Array(this.data)},r.sbgpBox.prototype.write=function(t){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(t),t.writeString(this.grouping_type,null,4),t.writeUint32(this.grouping_type_parameter),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++){var i=this.entries[e];t.writeInt32(i.sample_count),t.writeInt32(i.group_description_index)}},r.sgpdBox.prototype.write=function(t){var e,i;for(this.flags=0,this.size=12,e=0;e<this.entries.length;e++)i=this.entries[e],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=i.data.length);for(this.writeHeader(t),t.writeString(this.grouping_type,null,4),this.version===1&&t.writeUint32(this.default_length),this.version>=2&&t.writeUint32(this.default_sample_description_index),t.writeUint32(this.entries.length),e=0;e<this.entries.length;e++)i=this.entries[e],this.version===1&&this.default_length===0&&t.writeUint32(i.description_length),i.write(t)},r.sidxBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4*4+2+2+12*this.references.length,this.writeHeader(t),t.writeUint32(this.reference_ID),t.writeUint32(this.timescale),t.writeUint32(this.earliest_presentation_time),t.writeUint32(this.first_offset),t.writeUint16(0),t.writeUint16(this.references.length);for(var e=0;e<this.references.length;e++){var i=this.references[e];t.writeUint32(i.reference_type<<31|i.referenced_size),t.writeUint32(i.subsegment_duration),t.writeUint32(i.starts_with_SAP<<31|i.SAP_type<<28|i.SAP_delta_time)}},r.smhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=4,this.writeHeader(t),t.writeUint16(this.balance),t.writeUint16(0)},r.stcoBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(t),t.writeUint32(this.chunk_offsets.length),t.writeUint32Array(this.chunk_offsets)},r.stscBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(t),t.writeUint32(this.first_chunk.length),e=0;e<this.first_chunk.length;e++)t.writeUint32(this.first_chunk[e]),t.writeUint32(this.samples_per_chunk[e]),t.writeUint32(this.sample_description_index[e])},r.stsdBox.prototype.write=function(t){var e;
21for(this.version=0,this.flags=0,this.size=0,this.writeHeader(t),t.writeUint32(this.entries.length),this.size+=4,e=0;e<this.entries.length;e++)this.entries[e].write(t),this.size+=this.entries[e].size;a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},r.stshBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(t),t.writeUint32(this.shadowed_sample_numbers.length),e=0;e<this.shadowed_sample_numbers.length;e++)t.writeUint32(this.shadowed_sample_numbers[e]),t.writeUint32(this.sync_sample_numbers[e])},r.stssBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(t),t.writeUint32(this.sample_numbers.length),t.writeUint32Array(this.sample_numbers)},r.stszBox.prototype.write=function(t){var e,i=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(e=0;e+1<this.sample_sizes.length;)if(this.sample_sizes[e+1]!==this.sample_sizes[0]){i=!1;break}else e++;else i=!1;this.size=8,i||(this.size+=4*this.sample_sizes.length),this.writeHeader(t),i?t.writeUint32(this.sample_sizes[0]):t.writeUint32(0),t.writeUint32(this.sample_sizes.length),i||t.writeUint32Array(this.sample_sizes)},r.sttsBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(t),t.writeUint32(this.sample_counts.length),e=0;e<this.sample_counts.length;e++)t.writeUint32(this.sample_counts[e]),t.writeUint32(this.sample_deltas[e])},r.tfdtBox.prototype.write=function(t){var e=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>e?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(t),this.version===1?t.writeUint64(this.baseMediaDecodeTime):t.writeUint32(this.baseMediaDecodeTime)},r.tfhdBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&r.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&r.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&r.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&r.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&r.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(t),t.writeUint32(this.track_id),this.flags&r.TFHD_FLAG_BASE_DATA_OFFSET&&t.writeUint64(this.base_data_offset),this.flags&r.TFHD_FLAG_SAMPLE_DESC&&t.writeUint32(this.default_sample_description_index),this.flags&r.TFHD_FLAG_SAMPLE_DUR&&t.writeUint32(this.default_sample_duration),this.flags&r.TFHD_FLAG_SAMPLE_SIZE&&t.writeUint32(this.default_sample_size),this.flags&r.TFHD_FLAG_SAMPLE_FLAGS&&t.writeUint32(this.default_sample_flags)},r.tkhdBox.prototype.write=function(t){this.version=0,this.size=4*18+2*4,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.track_id),t.writeUint32(0),t.writeUint32(this.duration),t.writeUint32(0),t.writeUint32(0),t.writeInt16(this.layer),t.writeInt16(this.alternate_group),t.writeInt16(this.volume<<8),t.writeUint16(0),t.writeInt32Array(this.matrix),t.writeUint32(this.width),t.writeUint32(this.height)},r.trexBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(t),t.writeUint32(this.track_id),t.writeUint32(this.default_sample_description_index),t.writeUint32(this.default_sample_duration),t.writeUint32(this.default_sample_size),t.writeUint32(this.default_sample_flags)},r.trunBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&r.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&r.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&r.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&r.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&r.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&r.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(t),t.writeUint32(this.sample_count),this.flags&r.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=t.getPosition(),t.writeInt32(this.data_offset)),this.flags&r.TRUN_FLAGS_FIRST_FLAG&&t.writeUint32(this.first_sample_flags);for(var e=0;e<this.sample_count;e++)this.flags&r.TRUN_FLAGS_DURATION&&t.writeUint32(this.sample_duration[e]),this.flags&r.TRUN_FLAGS_SIZE&&t.writeUint32(this.sample_size[e]),this.flags&r.TRUN_FLAGS_FLAGS&&t.writeUint32(this.sample_flags[e]),this.flags&r.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?t.writeUint32(this.sample_composition_time_offset[e]):t.writeInt32(this.sample_composition_time_offset[e]))},r["url Box"].prototype.write=function(t){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(t),this.location&&t.writeCString(this.location)},r["urn Box"].prototype.write=function(t){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(t),t.writeCString(this.name),this.location&&t.writeCString(this.location)},r.vmhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=8,this.writeHeader(t),t.writeUint16(this.graphicsmode),t.writeUint16Array(this.opcolor)},r.cttsBox.prototype.unpack=function(t){var e,i,s;for(s=0,e=0;e<this.sample_counts.length;e++)for(i=0;i<this.sample_counts[e];i++)t[s].pts=t[s].dts+this.sample_offsets[e],s++},r.sttsBox.prototype.unpack=function(t){var e,i,s;for(s=0,e=0;e<this.sample_counts.length;e++)for(i=0;i<this.sample_counts[e];i++)s===0?t[s].dts=0:t[s].dts=t[s-1].dts+this.sample_deltas[e],s++},r.stcoBox.prototype.unpack=function(t){var e;
21for(e=0;e<this.chunk_offsets.length;e++)t[e].offset=this.chunk_offsets[e]},r.stscBox.prototype.unpack=function(t){var e,i,s,o,u;for(o=0,u=0,e=0;e<this.first_chunk.length;e++)for(i=0;i<(e+1<this.first_chunk.length?this.first_chunk[e+1]:1/0);i++)for(u++,s=0;s<this.samples_per_chunk[e];s++){if(t[o])t[o].description_index=this.sample_description_index[e],t[o].chunk_index=u;else return;o++}},r.stszBox.prototype.unpack=function(t){var e;for(e=0;e<this.sample_sizes.length;e++)t[e].size=this.sample_sizes[e]},r.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],r.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],r.boxEqualFields=function(t,e){if(t&&!e)return!1;var i;for(i in t)if(!(r.DIFF_BOXES_PROP_NAMES.indexOf(i)>-1)){if(t[i]instanceof r.Box||e[i]instanceof r.Box)continue;if(typeof t[i]>"u"||typeof e[i]>"u")continue;if(typeof t[i]=="function"||typeof e[i]=="function")continue;if(t.subBoxNames&&t.subBoxNames.indexOf(i.slice(0,4))>-1||e.subBoxNames&&e.subBoxNames.indexOf(i.slice(0,4))>-1)continue;if(i==="data"||i==="start"||i==="size"||i==="creation_time"||i==="modification_time")continue;if(r.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(i)>-1)continue;if(t[i]!==e[i])return!1}return!0},r.boxEqual=function(t,e){if(!r.boxEqualFields(t,e))return!1;for(var i=0;i<r.DIFF_BOXES_PROP_NAMES.length;i++){var s=r.DIFF_BOXES_PROP_NAMES[i];if(t[s]&&e[s]&&!r.boxEqual(t[s],e[s]))return!1}return!0};var b=function(){};b.prototype.parseSample=function(t){var e={},i;e.resources=[];var s=new h(t.data.buffer);if(!t.subsamples||t.subsamples.length===0)e.documentString=s.readString(t.data.length);else if(e.documentString=s.readString(t.subsamples[0].size),t.subsamples.length>1)for(i=1;i<t.subsamples.length;i++)e.resources[i]=s.readUint8Array(t.subsamples[i].size);return typeof DOMParser<"u"&&(e.document=new DOMParser().parseFromString(e.documentString,"application/xml")),e};var S=function(){};S.prototype.parseSample=function(t){var e,i=new h(t.data.buffer);return e=i.readString(t.data.length),e},S.prototype.parseConfig=function(t){var e,i=new h(t.buffer);return i.readUint32(),e=i.readCString(),e},n.XMLSubtitlein4Parser=b,n.Textin4Parser=S;var g=function(t){this.stream=t||new d,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.onSidx=null,this.sidxSent=!1};g.prototype.setSegmentOptions=function(t,e,i){var s=this.getTrackById(t);if(s){var o={};this.fragmentedTracks.push(o),o.id=t,o.user=e,o.trak=s,s.nextSample=0,o.segmentStream=null,o.nb_samples=1e3,o.rapAlignement=!0,i&&(i.nbSamples&&(o.nb_samples=i.nbSamples),i.rapAlignement&&(o.rapAlignement=i.rapAlignement))}},g.prototype.unsetSegmentOptions=function(t){for(var e=-1,i=0;i<this.fragmentedTracks.length;i++){var s=this.fragmentedTracks[i];s.id==t&&(e=i)}e>-1&&this.fragmentedTracks.splice(e,1)},g.prototype.setExtractionOptions=function(t,e,i){var s=this.getTrackById(t);if(s){var o={};this.extractedTracks.push(o),o.id=t,o.user=e,o.trak=s,s.nextSample=0,o.nb_samples=1e3,o.samples=[],i&&i.nbSamples&&(o.nb_samples=i.nbSamples)}},g.prototype.unsetExtractionOptions=function(t){for(var e=-1,i=0;i<this.extractedTracks.length;i++){var s=this.extractedTracks[i];s.id==t&&(e=i)}e>-1&&this.extractedTracks.splice(e,1)},g.prototype.parse=function(){var t,e,i=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),t=r.parseOneBox(this.stream,i),t.code===r.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(t))continue;return}else return;else{var s;switch(e=t.box,s=e.type!=="uuid"?e.type:e.uuid,this.boxes.push(e),s){case"mdat":this.mdats.push(e);break;case"moof":this.moofs.push(e);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[s]!==void 0&&a.warn("ISOFile","Duplicate Box of type: "+s+", overriding previous occurrence"),this[s]=e;break}this.updateUsedBytes&&this.updateUsedBytes(e,t)}},g.prototype.checkBuffer=function(t){if(t==null)throw"Buffer must be defined and non empty";if(t.fileStart===void 0)throw"Buffer must have a fileStart property";return t.byteLength===0?(a.warn("ISOFile","Ignoring empty buffer (fileStart: "+t.fileStart+")"),this.stream.logBufferLevel(),!1):(a.info("ISOFile","Processing buffer (fileStart: "+t.fileStart+")"),t.usedBytes=0,this.stream.insertBuffer(t),this.stream.logBufferLevel(),this.stream.initialized()?!0:(a.warn("ISOFile","Not ready to start parsing"),!1))},g.prototype.appendBuffer=function(t,e){var i;if(this.checkBuffer(t))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySe
21nt&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(e),this.nextSeekPosition?(i=this.nextSeekPosition,this.nextSeekPosition=void 0):i=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(i=this.stream.getEndFilePositionAfter(i))):this.nextParsePosition?i=this.nextParsePosition:i=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(a.info("ISOFile","Done processing buffer (fileStart: "+t.fileStart+") - next buffer to fetch should have a fileStart position of "+i),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),a.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),i},g.prototype.getInfo=function(){var t,e,i={},s,o,u,c,m=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(i.hasMoov=!0,i.duration=this.moov.mvhd.duration,i.timescale=this.moov.mvhd.timescale,i.isFragmented=this.moov.mvex!=null,i.isFragmented&&this.moov.mvex.mehd&&(i.fragment_duration=this.moov.mvex.mehd.fragment_duration),i.isProgressive=this.isProgressive,i.hasIOD=this.moov.iods!=null,i.brands=[],i.brands.push(this.ftyp.major_brand),i.brands=i.brands.concat(this.ftyp.compatible_brands),i.created=new Date(m+this.moov.mvhd.creation_time*1e3),i.modified=new Date(m+this.moov.mvhd.modification_time*1e3),i.tracks=[],i.audioTracks=[],i.videoTracks=[],i.subtitleTracks=[],i.metadataTracks=[],i.hintTracks=[],i.otherTracks=[],t=0;t<this.moov.traks.length;t++){if(s=this.moov.traks[t],c=s.mdia.minf.stbl.stsd.entries[0],o={},i.tracks.push(o),o.id=s.tkhd.track_id,o.name=s.mdia.hdlr.name,o.references=[],s.tref)for(e=0;e<s.tref.boxes.length;e++)u={},o.references.push(u),u.type=s.tref.boxes[e].type,u.track_ids=s.tref.boxes[e].track_ids;s.edts&&(o.edits=s.edts.elst.entries),o.created=new Date(m+s.tkhd.creation_time*1e3),o.modified=new Date(m+s.tkhd.modification_time*1e3),o.movie_duration=s.tkhd.duration,o.movie_timescale=i.timescale,o.layer=s.tkhd.layer,o.alternate_group=s.tkhd.alternate_group,o.volume=s.tkhd.volume,o.matrix=s.tkhd.matrix,o.track_width=s.tkhd.width/65536,o.track_height=s.tkhd.height/65536,o.timescale=s.mdia.mdhd.timescale,o.cts_shift=s.mdia.minf.stbl.cslg,o.duration=s.mdia.mdhd.duration,o.samples_duration=s.samples_duration,o.codec=c.getCodec(),o.kind=s.udta&&s.udta.kinds.length?s.udta.kinds[0]:{schemeURI:"",value:""},o.language=s.mdia.elng?s.mdia.elng.extended_language:s.mdia.mdhd.languageString,o.nb_samples=s.samples.length,o.size=s.samples_size,o.bitrate=o.size*8*o.timescale/o.samples_duration,c.isAudio()?(o.type="audio",i.audioTracks.push(o),o.audio={},o.audio.sample_rate=c.getSampleRate(),o.audio.channel_count=c.getChannelCount(),o.audio.sample_size=c.getSampleSize()):c.isVideo()?(o.type="video",i.videoTracks.push(o),o.video={},o.video.width=c.getWidth(),o.video.height=c.getHeight()):c.isSubtitle()?(o.type="subtitles",i.subtitleTracks.push(o)):c.isHint()?(o.type="metadata",i.hintTracks.push(o)):c.isMetadata()?(o.type="metadata",i.metadataTracks.push(o)):(o.type="metadata",i.otherTracks.push(o))}else i.hasMoov=!1;if(i.mime="",i.hasMoov&&i.tracks){for(i.videoTracks&&i.videoTracks.length>0?i.mime+='video/mp4; codecs="':i.audioTracks&&i.audioTracks.length>0?i.mime+='audio/mp4; codecs="':i.mime+='application/mp4; codecs="',t=0;t<i.tracks.length;t++)t!==0&&(i.mime+=","),i.mime+=i.tracks[t].codec;i.mime+='"; profiles="',i.mime+=this.ftyp.compatible_brands.join(),i.mime+='"'}return i},g.prototype.processSamples=function(t){var e,i;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(e=0;e<this.fragmentedTracks.length;e++){var s=this.fragmentedTracks[e];for(i=s.trak;i.nextSample<i.samples.length&&this.sampleProcessingStarted;){a.debug("ISOFile","Creating media fragment on track #"+s.id+" for sample "+i.nextSample);var o=this.createFragment(s.id,i.nextSample,s.segmentStream);if(o)s.segmentStream=o,i.nextSample++;else break;if((i.nextSample%s.nb_samples===0||t||i.nextSample>=i.samples.length)&&(a.info("ISOFile","Sending fragmented data on track #"+s.id+" for samples ["+Math.max(0,i.nextSample-s.nb_samples)+","+(i.nextSample-1)+"]"),a.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(s.id,s.user,s.segmentStream.buffer,i.nextSample,t||i.nextSample>=i.samples.length),s.segmentStream=null,s!==this.fragmentedTracks[e]))break}}if(this.onSamples!==null)for(e=0;e<this.extractedTracks.length;e++){var u=this.extractedTracks[e];for(i=u.trak;i.nextSample<i.samples.length&&this.sampleProcessingStarted;){a.debug("ISOFile","Exporting on track #"+u.id+" sample #"+i.nextSample);var c=this.getSample(i,i.nextSample);if(c)i.nextSample++,u.samples.push(c);else break;if((i.nextSample%u.nb_samples===0||i.nextSample>=i.samples.length)&&(a.debug("ISOFile","Sending samples on track #"+u.id+" for sample "+i.nextSample),this.onSamples&&this.onSamples(u.id,u.user,u.samples),u.samples=[],u!==this.extractedTracks[e]))break}}}},g.prototype.getBox=function(t){var e=this.getBoxes(t,!0);return e.length?e[0]:null},g.prototype.getBoxes=function(t,e){var i=[];return g._sweep.call(this,t,i,e),i}
21,g._sweep=function(t,e,i){this.type&&this.type==t&&e.push(this);for(var s in this.boxes){if(e.length&&i)return;g._sweep.call(this.boxes[s],t,e,i)}},g.prototype.getTrackSamplesInfo=function(t){var e=this.getTrackById(t);if(e)return e.samples},g.prototype.getTrackSample=function(t,e){var i=this.getTrackById(t),s=this.getSample(i,e);return s},g.prototype.releaseUsedSamples=function(t,e){var i=0,s=this.getTrackById(t);s.lastValidSample||(s.lastValidSample=0);for(var o=s.lastValidSample;o<e;o++)i+=this.releaseSample(s,o);a.info("ISOFile","Track #"+t+" released samples up to "+e+" (released size: "+i+", remaining: "+this.samplesDataSize+")"),s.lastValidSample=e},g.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},g.prototype.stop=function(){this.sampleProcessingStarted=!1},g.prototype.flush=function(){a.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},g.prototype.seekTrack=function(t,e,i){var s,o,u=1/0,c=0,m=0,x;if(i.samples.length===0)return a.info("ISOFile","No sample in track, cannot seek! Using time "+a.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(s=0;s<i.samples.length;s++){if(o=i.samples[s],s===0)m=0,x=o.timescale;else if(o.cts>t*o.timescale){m=s-1;break}e&&o.is_sync&&(c=s)}for(e&&(m=c),t=i.samples[m].cts,i.nextSample=m;i.samples[m].alreadyRead===i.samples[m].size&&i.samples[m+1];)m++;return u=i.samples[m].offset+i.samples[m].alreadyRead,a.info("ISOFile","Seeking to "+(e?"RAP":"")+" sample #"+i.nextSample+" on track "+i.tkhd.track_id+", time "+a.getDurationString(t,x)+" and offset: "+u),{offset:u,time:t/x}},g.prototype.seek=function(t,e){var i=this.moov,s,o,u,c={offset:1/0,time:1/0};if(this.moov){for(u=0;u<i.traks.length;u++)s=i.traks[u],o=this.seekTrack(t,e,s),o.offset<c.offset&&(c.offset=o.offset),o.time<c.time&&(c.time=o.time);return a.info("ISOFile","Seeking at time "+a.getDurationString(c.time,1)+" needs a buffer with a fileStart position of "+c.offset),c.offset===1/0?c={offset:this.nextParsePosition,time:0}:c.offset=this.stream.getEndFilePositionAfter(c.offset),a.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+c.offset),c}else throw"Cannot seek: moov not received!"},g.prototype.equal=function(t){for(var e=0;e<this.boxes.length&&e<t.boxes.length;){var i=this.boxes[e],s=t.boxes[e];if(!r.boxEqual(i,s))return!1;e++}return!0},n.ISOFile=g,g.prototype.lastBoxStartPosition=0,g.prototype.parsingMdat=null,g.prototype.nextParsePosition=0,g.prototype.discardMdatData=!1,g.prototype.processIncompleteBox=function(t){var e,i,s;return t.type==="mdat"?(e=new r[t.type+"Box"](t.size),this.parsingMdat=e,this.boxes.push(e),this.mdats.push(e),e.start=t.start,e.hdr_size=t.hdr_size,this.stream.addUsedBytes(e.hdr_size),this.lastBoxStartPosition=e.start+e.size,s=this.stream.seek(e.start+e.size,!1,this.discardMdatData),s?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=e.start+e.size,!1)):(t.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),i=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,i?(this.nextParsePosition=this.stream.getEndPosition(),!0):(t.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+t.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},g.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},g.prototype.processIncompleteMdat=function(){var t,e;return t=this.parsingMdat,e=this.stream.seek(t.start+t.size,!1,this.discardMdatData),e?(a.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},g.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},g.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},g.prototype.updateUsedBytes=function(t,e){this.stream.addUsedBytes&&(t.type==="mdat"?(this.stream.addUsedBytes(t.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(t.size-t.hdr_size)):this.stream.addUsedBytes(t.size))},g.prototype.add=r.Box.prototype.add,g.prototype.addBox=r.Box.prototype.addBox,g.prototype.init=function(t){var e=t||{};this.add("ftyp").set("major_brand",e.brands&&e.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",e.brands||["iso4"]);var i=this.add("moov");return i.add("mvhd").set("timescale",e.timescale||600).set("rate",e.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",e.duration||0).set("volume",e.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),i.add("mvex"),this},g.prototype.addTrack=function(t){this.moov||this.init(t);var e=t||{};e.width=e.width||320,e.height=e.height||320,e.id=e.id||this.moov.mvhd.next_track_id,e.type=e.type||"avc1";var i=this.moov.add("trak");this.moov.mvhd.next_track_id=e.id+1,i.add("tkhd").set("flags",r.TKHD_FLAG_ENABLED|r.TKHD_FLAG_IN_MOVIE|r.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",e.id).set("duration",e.duration||0).set("layer",e.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[0,0,0,0,0,0,0,0,0]).set("width",e.width<<16).set("height",e.height<<16);var s=i.add("mdia");s.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",e.timescale||1).set("duration",e.media_duration||0).set("language",e.language||"und"),s.add("hdlr").set("handler",e.hdlr||"vide").set("name",e.name||"Track created with MP4Box.js"),s.add("elng").set("extended_language",e.language||"fr-FR");var o=s.add("minf");if(r[e.type+"SampleEntry"]!==void 0){var u=new r[e.type+"SampleEntry"];u.data_reference_index=1;var c="";for(var m in r.sampleEntryCodes)for(var x=r.sampleEntryCodes[m],w=0;w<x.length;w++)if(x.indexOf(e.type)>-1){c=m;break}switch(c){case"Visual":if(o.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),u.set("width",e.width).set("height",e.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",e.type+" Compressor").set("depth",24),e.avcDecoderConfigRecord){var v=new r.avcCBox,E=new h(e.avcDecoderConfigRecord);v.parse(E),u.addBox(v)}break;case"Audio":o.add("smhd").set("balance",e.balance||0),u.set("channel_c
21ount",e.channel_count||2).set("samplesize",e.samplesize||16).set("samplerate",e.samplerate||65536);break;case"Hint":o.add("hmhd");break;case"Subtitle":switch(o.add("sthd"),e.type){case"stpp":u.set("namespace",e.namespace||"nonamespace").set("schema_location",e.schema_location||"").set("auxiliary_mime_types",e.auxiliary_mime_types||"");break}break;case"Metadata":o.add("nmhd");break;case"System":o.add("nmhd");break;default:o.add("nmhd");break}e.description&&u.addBox(e.description),e.description_boxes&&e.description_boxes.forEach(function(C){u.addBox(C)}),o.add("dinf").add("dref").addEntry(new r["url Box"]().set("flags",1));var F=o.add("stbl");return F.add("stsd").addEntry(u),F.add("stts").set("sample_counts",[]).set("sample_deltas",[]),F.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),F.add("stco").set("chunk_offsets",[]),F.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",e.id).set("default_sample_description_index",e.default_sample_description_index||1).set("default_sample_duration",e.default_sample_duration||0).set("default_sample_size",e.default_sample_size||0).set("default_sample_flags",e.default_sample_flags||0),this.buildTrakSampleLists(i),e.id}},r.Box.prototype.computeSize=function(t){var e=t||new l;e.endianness=l.BIG_ENDIAN,this.write(e)},g.prototype.addSample=function(t,e,i){var s=i||{},o={},u=this.getTrackById(t);if(u!==null){o.number=u.samples.length,o.track_id=u.tkhd.track_id,o.timescale=u.mdia.mdhd.timescale,o.description_index=s.sample_description_index?s.sample_description_index-1:0,o.description=u.mdia.minf.stbl.stsd.entries[o.description_index],o.data=e,o.size=e.byteLength,o.alreadyRead=o.size,o.duration=s.duration||1,o.cts=s.cts||0,o.dts=s.dts||0,o.is_sync=s.is_sync||!1,o.is_leading=s.is_leading||0,o.depends_on=s.depends_on||0,o.is_depended_on=s.is_depended_on||0,o.has_redundancy=s.has_redundancy||0,o.degradation_priority=s.degradation_priority||0,o.offset=0,o.subsamples=s.subsamples,u.samples.push(o),u.samples_size+=o.size,u.samples_duration+=o.duration,u.first_dts||(u.first_dts=s.dts),this.processSamples();var c=this.createSingleSampleMoof(o);return this.addBox(c),c.computeSize(),c.trafs[0].truns[0].data_offset=c.size+8,this.add("mdat").data=new Uint8Array(e),o}},g.prototype.createSingleSampleMoof=function(t){var e=0;t.is_sync?e=1<<25:e=65536;var i=new r.moofBox;i.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var s=i.add("traf"),o=this.getTrackById(t.track_id);return s.add("tfhd").set("track_id",t.track_id).set("flags",r.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),s.add("tfdt").set("baseMediaDecodeTime",t.dts-(o.first_dts||0)),s.add("trun").set("flags",r.TRUN_FLAGS_DATA_OFFSET|r.TRUN_FLAGS_DURATION|r.TRUN_FLAGS_SIZE|r.TRUN_FLAGS_FLAGS|r.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[t.duration]).set("sample_size",[t.size]).set("sample_flags",[e]).set("sample_composition_time_offset",[t.cts-t.dts]),i},g.prototype.lastMoofIndex=0,g.prototype.samplesDataSize=0,g.prototype.resetTables=function(){var t,e,i,s,o,u,c,m;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,t=0;t<this.moov.traks.length;t++){e=this.moov.traks[t],e.tkhd.duration=0,e.mdia.mdhd.duration=0,i=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,i.chunk_offsets=[],s=e.mdia.minf.stbl.stsc,s.first_chunk=[],s.samples_per_chunk=[],s.sample_description_index=[],o=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,o.sample_sizes=[],u=e.mdia.minf.stbl.stts,u.sample_counts=[],u.sample_deltas=[],c=e.mdia.minf.stbl.ctts,c&&(c.sample_counts=[],c.sample_offsets=[]),m=e.mdia.minf.stbl.stss;var x=e.mdia.minf.stbl.boxes.indexOf(m);x!=-1&&(e.mdia.minf.stbl.boxes[x]=null)}},g.initSampleGroups=function(t,e,i,s,o){var u,c,m,x;function w(v,E,F){this.grouping_type=v,this.grouping_type_parameter=E,this.sbgp=F,this.last_sample_in_run=-1,this.entry_index=-1}for(e&&(e.sample_groups_info=[]),t.sample_groups_info||(t.sample_groups_info=[]),c=0;c<i.length;c++){for(x=i[c].grouping_type+"/"+i[c].grouping_type_parameter,m=new w(i[c].grouping_type,i[c].grouping_type_parameter,i[c]),e&&(e.sample_groups_info[x]=m),t.sample_groups_info[x]||(t.sample_groups_info[x]=m),u=0;u<s.length;u++)s[u].grouping_type===i[c].grouping_type&&(m.description=s[u],m.description.used=!0);if(o)for(u=0;
21u<o.length;u++)o[u].grouping_type===i[c].grouping_type&&(m.fragment_description=o[u],m.fragment_description.used=!0,m.is_fragment=!0)}if(e){if(o)for(c=0;c<o.length;c++)!o[c].used&&o[c].version>=2&&(x=o[c].grouping_type+"/0",m=new w(o[c].grouping_type,0),m.is_fragment=!0,e.sample_groups_info[x]||(e.sample_groups_info[x]=m))}else for(c=0;c<s.length;c++)!s[c].used&&s[c].version>=2&&(x=s[c].grouping_type+"/0",m=new w(s[c].grouping_type,0),t.sample_groups_info[x]||(t.sample_groups_info[x]=m))},g.setSampleGroupProperties=function(t,e,i,s){var o,u;e.sample_groups=[];for(o in s)if(e.sample_groups[o]={},e.sample_groups[o].grouping_type=s[o].grouping_type,e.sample_groups[o].grouping_type_parameter=s[o].grouping_type_parameter,i>=s[o].last_sample_in_run&&(s[o].last_sample_in_run<0&&(s[o].last_sample_in_run=0),s[o].entry_index++,s[o].entry_index<=s[o].sbgp.entries.length-1&&(s[o].last_sample_in_run+=s[o].sbgp.entries[s[o].entry_index].sample_count)),s[o].entry_index<=s[o].sbgp.entries.length-1?e.sample_groups[o].group_description_index=s[o].sbgp.entries[s[o].entry_index].group_description_index:e.sample_groups[o].group_description_index=-1,e.sample_groups[o].group_description_index!==0){var c;s[o].fragment_description?c=s[o].fragment_description:c=s[o].description,e.sample_groups[o].group_description_index>0?(e.sample_groups[o].group_description_index>65535?u=(e.sample_groups[o].group_description_index>>16)-1:u=e.sample_groups[o].group_description_index-1,c&&u>=0&&(e.sample_groups[o].description=c.entries[u])):c&&c.version>=2&&c.default_group_description_index>0&&(e.sample_groups[o].description=c.entries[c.default_group_description_index-1])}},g.process_sdtp=function(t,e,i){e&&(t?(e.is_leading=t.is_leading[i],e.depends_on=t.sample_depends_on[i],e.is_depended_on=t.sample_is_depended_on[i],e.has_redundancy=t.sample_has_redundancy[i]):(e.is_leading=0,e.depends_on=0,e.is_depended_on=0,e.has_redundancy=0))},g.prototype.buildSampleLists=function(){var t,e;for(t=0;t<this.moov.traks.length;t++)e=this.moov.traks[t],this.buildTrakSampleLists(e)},g.prototype.buildTrakSampleLists=function(t){var e,i,s,o,u,c,m,x,w,v,E,F,C,N,z,H,j,X,V,M,Y,Q,P,$;if(t.samples=[],t.samples_duration=0,t.samples_size=0,i=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,s=t.mdia.minf.stbl.stsc,o=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,u=t.mdia.minf.stbl.stts,c=t.mdia.minf.stbl.ctts,m=t.mdia.minf.stbl.stss,x=t.mdia.minf.stbl.stsd,w=t.mdia.minf.stbl.subs,F=t.mdia.minf.stbl.stdp,v=t.mdia.minf.stbl.sbgps,E=t.mdia.minf.stbl.sgpds,X=-1,V=-1,M=-1,Y=-1,Q=0,P=0,$=0,g.initSampleGroups(t,null,v,E),!(typeof o>"u")){for(e=0;e<o.sample_sizes.length;e++){var k={};k.number=e,k.track_id=t.tkhd.track_id,k.timescale=t.mdia.mdhd.timescale,k.alreadyRead=0,t.samples[e]=k,k.size=o.sample_sizes[e],t.samples_size+=k.size,e===0?(N=1,C=0,k.chunk_index=N,k.chunk_run_index=C,j=s.samples_per_chunk[C],H=0,C+1<s.first_chunk.length?z=s.first_chunk[C+1]-1:z=1/0):e<j?(k.chunk_index=N,k.chunk_run_index=C):(N++,k.chunk_index=N,H=0,N<=z||(C++,C+1<s.first_chunk.length?z=s.first_chunk[C+1]-1:z=1/0),k.chunk_run_index=C,j+=s.samples_per_chunk[C]),k.description_index=s.sample_description_index[k.chunk_run_index]-1,k.description=x.entries[k.description_index],k.offset=i.chunk_offsets[k.chunk_index-1]+H,H+=k.size,e>X&&(V++,X<0&&(X=0),X+=u.sample_counts[V]),e>0?(t.samples[e-1].duration=u.sample_deltas[V],t.samples_duration+=t.samples[e-1].duration,k.dts=t.samples[e-1].dts+t.samples[e-1].duration):k.dts=0,c?(e>=M&&(Y++,M<0&&(M=0),M+=c.sample_counts[Y]),k.cts=t.samples[e].dts+c.sample_offsets[Y]):k.cts=k.dts,m?(e==m.sample_numbers[Q]-1?(k.is_sync=!0,Q++):(k.is_sync=!1,k.degradation_priority=0),w&&w.entries[P].sample_delta+$==e+1&&(k.subsamples=w.entries[P].subsamples,$+=w.entries[P].sample_delta,P++)):k.is_sync=!0,g.process_sdtp(t.mdia.minf.stbl.sdtp,k,k.number),F?k.degradation_priority=F.priority[e]:k.degradation_priority=0,w&&w.entries[P].sample_delta+$==e&&(k.subsamples=w.entries[P].subsamples,$+=w.entries[P].sample_delta),(v.length>0||E.length>0)&&g.setSampleGroupProperties(t,k,e,t.sample_groups_info)}e>0&&(t.samples[e-1].duration=Math.max(t.mdia.mdhd.duration-t.samples[e-1].dts,0),t.samples_duration+=t.samples[e-1].duration)}},g.prototype.updateSampleLists=function(){var t,e,i,s,o,u,c,m,x,w,v,E,F,C,N;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(x=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,x.type=="moof")for(w=x,t=0;t<w.trafs.length;t++){for(v=w.trafs[t],E=this.getTrackById(v.tfhd.track_id),F=this.getTrexById(v.tfhd.track_id),v.tfhd.flags&r.TFHD_FLAG_SAMPLE_DESC?s=v.tfhd.default_sample_description_index:s=F?F.default_sample_description_index:1,v.tfhd.flags&r.TFHD_FLAG_SAMPLE_DUR?o=v.tfhd.default_sample_duration:o=F?F.default_sample_duration:0,v.tfhd.flags&r.TFHD_FLAG_SAMPLE_SIZE?u=v.tfhd.default_sample_size:u=F?F.default_sample_size:0,v.tfhd.flags&r.TFHD_FLAG_SAMPLE_FLAGS?c=v.tfhd.default_sample_flags:c=F?F.default_sample_flags:0,v.sample_number=0,v.sbgps.length>0&&g.initSampleGroups(E,v,v.sbgps,E.mdia.minf.stbl.sgpds,v.sgpds),e=0;e<v.truns.length;e++){var z=v.truns[e];for(i=0;i<z.sample_count;i++){C={},C.moof_number=this.lastMoofIndex,C.number_in_traf=v.sample_number,v.sample_number++,C.number=E.samples.length,v.first_sample_index=E.samples.length,E.samples.push(C),C.track_id=E.tkhd.track_id,C.timescale=E.mdia.mdhd.timescale,C.description_index=s-1,C.description=E.mdia.minf.stbl.stsd.entries[C.description_index],C.size=u,z.flags&r.TRUN_FLAGS_SIZE&&(C.size=z.sample_size[i]),E.samples_size+=C.size,C.duration=o,z.flags&r.TRUN_FLAGS_DURATION&&(C.duration=z.sample_duration[i]),E.samples_duration+=C.duration,E.first_traf_merged||i>0?C.dts=E.samples[E.samples.length-2].dts+E.samples[E.samples.length-2].duration:(v.tfdt?C.dts=v.tfdt.baseMediaDecodeTime:C.dts=0,E.first_traf_merged=!0),C.cts=C.dts,z.flags&r.TRUN_FLAGS_CTS_OFFSET&&(C.cts=C.dts+z.sample_composition_time_offset[i]),N=c,z.flags&r.TRUN_FLAGS_FLAGS?N=z.sample_flags[i]:i===0&&z.flags&r.TRUN_FLAGS_FIRST_FLAG&&(N=z.first_sample_flags),C.is_sync=!(N>>16&1),C.is_leading=N>>26&3,C.depends_on=N>>24&3,C.is_depended_on=N>>22&3,C.has_redundancy=N>>20&3,C.degradation_priority=N&65535;var H=!!(v.tfhd.flags&r.TFHD_FLAG_BASE_DATA_OFFSET),j=!!(v.tfhd.flags&r.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),X=!!(z.flags&r.TRUN_FLAGS_DATA_OFFSET),V=0;H?V=v.tfhd.base_data_offset:j||e===0?V=w.start:V=m,e===0&&i===0?X?C.offset=V+z.data_offset:C.offset=V:C.offset=m,m=C.offset+C.size,(v.sbgps.length>0||v.sgpds.length>0||E.mdia.minf.stbl.sbgps.length>0||E.mdia.minf.stbl.sgpds.length>0)&&g.setSampleGroupProperties(E,C,C.number_in_traf,v.sample_groups_info)}}if(v.subs){E.has_fragment_subsamples=!0;var M=v.first_sample_index;for(e=0;
21e<v.subs.entries.length;e++)M+=v.subs.entries[e].sample_delta,C=E.samples[M-1],C.subsamples=v.subs.entries[e].subsamples}}}},g.prototype.getSample=function(t,e){var i,s=t.samples[e];if(!this.moov)return null;if(!s.data)s.data=new Uint8Array(s.size),s.alreadyRead=0,this.samplesDataSize+=s.size,a.debug("ISOFile","Allocating sample #"+e+" on track #"+t.tkhd.track_id+" of size "+s.size+" (total: "+this.samplesDataSize+")");else if(s.alreadyRead==s.size)return s;for(;;){var o=this.stream.findPosition(!0,s.offset+s.alreadyRead,!1);if(o>-1){i=this.stream.buffers[o];var u=i.byteLength-(s.offset+s.alreadyRead-i.fileStart);if(s.size-s.alreadyRead<=u)return a.debug("ISOFile","Getting sample #"+e+" data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-i.fileStart)+" read size: "+(s.size-s.alreadyRead)+" full size: "+s.size+")"),l.memcpy(s.data.buffer,s.alreadyRead,i,s.offset+s.alreadyRead-i.fileStart,s.size-s.alreadyRead),i.usedBytes+=s.size-s.alreadyRead,this.stream.logBufferLevel(),s.alreadyRead=s.size,s;if(u===0)return null;a.debug("ISOFile","Getting sample #"+e+" partial data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-i.fileStart)+" read size: "+u+" full size: "+s.size+")"),l.memcpy(s.data.buffer,s.alreadyRead,i,s.offset+s.alreadyRead-i.fileStart,u),s.alreadyRead+=u,i.usedBytes+=u,this.stream.logBufferLevel()}else return null}},g.prototype.releaseSample=function(t,e){var i=t.samples[e];return i.data?(this.samplesDataSize-=i.size,i.data=null,i.alreadyRead=0,i.size):0},g.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},g.prototype.getCodecs=function(){var t,e="";for(t=0;t<this.moov.traks.length;t++){var i=this.moov.traks[t];t>0&&(e+=","),e+=i.mdia.minf.stbl.stsd.entries[0].getCodec()}return e},g.prototype.getTrexById=function(t){var e;if(!this.moov||!this.moov.mvex)return null;for(e=0;e<this.moov.mvex.trexs.length;e++){var i=this.moov.mvex.trexs[e];if(i.track_id==t)return i}return null},g.prototype.getTrackById=function(t){if(this.moov===void 0)return null;for(var e=0;e<this.moov.traks.length;e++){var i=this.moov.traks[e];if(i.tkhd.track_id==t)return i}return null},g.prototype.items=[],g.prototype.itemsDataSize=0,g.prototype.flattenItemInfo=function(){var t=this.items,e,i,s,o=this.meta;if(o!=null&&o.hdlr!==void 0&&o.iinf!==void 0){for(e=0;e<o.iinf.item_infos.length;e++)s={},s.id=o.iinf.item_infos[e].item_ID,t[s.id]=s,s.ref_to=[],s.name=o.iinf.item_infos[e].item_name,o.iinf.item_infos[e].protection_index>0&&(s.protection=o.ipro.protections[o.iinf.item_infos[e].protection_index-1]),o.iinf.item_infos[e].item_type?s.type=o.iinf.item_infos[e].item_type:s.type="mime",s.content_type=o.iinf.item_infos[e].content_type,s.content_encoding=o.iinf.item_infos[e].content_encoding;if(o.iloc)for(e=0;e<o.iloc.items.length;e++){var u=o.iloc.items[e];switch(s=t[u.item_ID],u.data_reference_index!==0&&(a.warn("Item storage with reference to other files: not supported"),s.source=o.dinf.boxes[u.data_reference_index-1]),u.construction_method){case 0:break;case 1:a.warn("Item storage with construction_method : not supported");break;case 2:a.warn("Item storage with construction_method : not supported");break}for(s.extents=[],s.size=0,i=0;i<u.extents.length;i++)s.extents[i]={},s.extents[i].offset=u.extents[i].extent_offset+u.base_offset,s.extents[i].length=u.extents[i].extent_length,s.extents[i].alreadyRead=0,s.size+=s.extents[i].length}if(o.pitm&&(t[o.pitm.item_id].primary=!0),o.iref)for(e=0;e<o.iref.references.length;e++){var c=o.iref.references[e];for(i=0;i<c.references.length;i++)t[c.from_item_ID].ref_to.push({type:c.type,id:c.references[i]})}if(o.iprp)for(var m=0;m<o.iprp.ipmas.length;m++){var x=o.iprp.ipmas[m];for(e=0;e<x.associations.length;e++){var w=x.associations[e];for(s=t[w.id],s.properties===void 0&&(s.properties={},s.properties.boxes=[]),i=0;i<w.props.length;i++){var v=w.props[i];if(v.property_index>0&&v.property_index-1<o.iprp.ipco.boxes.length){var E=o.iprp.ipco.boxes[v.property_index-1];s.properties[E.type]=E,s.properties.boxes.push(E)}}}}}},g.prototype.getItem=function(t){var e,i;if(!this.meta)return null;if(i=this.items[t],!i.data&&i.size)i.data=new Uint8Array(i.size),i.alreadyRead=0,this.itemsDataSize+=i.size,a.debug("ISOFile","Allocating item #"+t+" of size "+i.size+" (total: "+this.itemsDataSize+")");else if(i.alreadyRead===i.size)return i;for(var s=0;s<i.extents.length;s++){var o=i.extents[s];if(o.alreadyRead!==o.length){var u=this.stream.findPosition(!0,o.offset+o.alreadyRead,!1);if(u>-1){e=this.stream.buffers[u];var c=e.byteLength-(o.offset+o.alreadyRead-e.fileStart);if(o.length-o.alreadyRead<=c)a.debug("ISOFile","Getting item #"+t+" extent #"+s+" data (alreadyRead: "+o.alreadyRead+" offset: "+(o.offset+o.alreadyRead-e.fileStart)+" read size: "+(o.length-o.alreadyRead)+" full extent size: "+o.length+" full item size: "+i.size+")"),l.memcpy(i.data.buffer,i.alreadyRead,e,o.offset+o.alreadyRead-e.fileStart,o.length-o.alreadyRead),e.usedBytes+=o.length-o.alreadyRead,this.stream.logBufferLevel(),i.alreadyRead+=o.length-o.alreadyRead,o.alreadyRead=o.length;else return a.debug("ISOFile","Getting item #"+t+" extent #"+s+" partial data (alreadyRead: "+o.alreadyRead+" offset: "+(o.offset+o.alreadyRead-e.fileStart)+" read size: "+c+" full extent size: "+o.length+" full item size: "+i.size+")"),l.memcpy(i.data.buffer,i.alreadyRead,e,o.offset+o.alreadyRead-e.fileStart,c),o.alreadyRead+=c,i.alreadyRead+=c,e.usedBytes+=c,this.stream.logBufferLevel(),null}else return null}}return i.alreadyRead===i.size?i:null},g.prototype.releaseItem=function(t){var e=this.items[t];if(e.data){this.itemsDataSize-=e.size,e.data=null,e.alreadyRead=0;for(var i=0;i<e.extents.length;i++){var s=e.extents[i];s.alreadyRead=0}return e.size}else return 0},g.prototype.processItems=function(t){for(var e in this.items){var i=this.items[e];this.getItem(i.id),t&&!i.sent&&(t(i),i.sent=!0,i.data=null)}},g.prototype.hasItem=function(t){for(var e in this.items){var i=this.items[e];if(i.name===t)return i.id}return-1},g.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},g.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},g.prototype.itemToFragmentedTrackFile=function(t){var e=t||{},i=null;if(e.itemId?i=this.getItem(e.itemId):i=this.getPrimaryItem(),i==null)return null;var s=new g;s.discardMdatData=!1;var o={type:i.type,description_boxes:i.properties.boxes};i.properties.ispe&&(o.width=i.properties.ispe.image_width,o.height=i.properties.ispe.image_height);var u=s.addTrack(o);return u?(s.addSample(u,i.data),s):null},g.prototype.write=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t)}
21,g.prototype.createFragment=function(t,e,i){var s=this.getTrackById(t),o=this.getSample(s,e);if(o==null)return o=s.samples[e],this.nextSeekPosition?this.nextSeekPosition=Math.min(o.offset+o.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=s.samples[e].offset+o.alreadyRead,null;var u=i||new l;u.endianness=l.BIG_ENDIAN;var c=this.createSingleSampleMoof(o);c.write(u),c.trafs[0].truns[0].data_offset=c.size+8,a.debug("MP4Box","Adjusting data_offset with new value "+c.trafs[0].truns[0].data_offset),u.adjustUint32(c.trafs[0].truns[0].data_offset_position,c.trafs[0].truns[0].data_offset);var m=new r.mdatBox;return m.data=o.data,m.write(u),u},g.writeInitializationSegment=function(t,e,i,s){var o;a.debug("ISOFile","Generating initialization segment");var u=new l;u.endianness=l.BIG_ENDIAN,t.write(u);var c=e.add("mvex");for(i&&c.add("mehd").set("fragment_duration",i),o=0;o<e.traks.length;o++)c.add("trex").set("track_id",e.traks[o].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",s).set("default_sample_size",0).set("default_sample_flags",65536);return e.write(u),u.buffer},g.prototype.save=function(t){var e=new l;e.endianness=l.BIG_ENDIAN,this.write(e),e.save(t)},g.prototype.getBuffer=function(){var t=new l;return t.endianness=l.BIG_ENDIAN,this.write(t),t.buffer},g.prototype.initializeSegmentation=function(){var t,e,i,s;for(this.onSegment===null&&a.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),e=[],t=0;t<this.fragmentedTracks.length;t++){var o=new r.moovBox;o.mvhd=this.moov.mvhd,o.boxes.push(o.mvhd),i=this.getTrackById(this.fragmentedTracks[t].id),o.boxes.push(i),o.traks.push(i),s={},s.id=i.tkhd.track_id,s.user=this.fragmentedTracks[t].user,s.buffer=g.writeInitializationSegment(this.ftyp,o,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[t].samples.length>0?this.moov.traks[t].samples[0].duration:0),e.push(s)}return e},r.Box.prototype.printHeader=function(t){this.size+=8,this.size>f&&(this.size+=8),this.type==="uuid"&&(this.size+=16),t.log(t.indent+"size:"+this.size),t.log(t.indent+"type:"+this.type)},r.FullBox.prototype.printHeader=function(t){this.size+=4,r.Box.prototype.printHeader.call(this,t),t.log(t.indent+"version:"+this.version),t.log(t.indent+"flags:"+this.flags)},r.Box.prototype.print=function(t){this.printHeader(t)},r.ContainerBox.prototype.print=function(t){this.printHeader(t);for(var e=0;e<this.boxes.length;e++)if(this.boxes[e]){var i=t.indent;t.indent+=" ",this.boxes[e].print(t),t.indent=i}},g.prototype.print=function(t){t.indent="";for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&this.boxes[e].print(t)},r.mvhdBox.prototype.print=function(t){r.FullBox.prototype.printHeader.call(this,t),t.log(t.indent+"creation_time: "+this.creation_time),t.log(t.indent+"modification_time: "+this.modification_time),t.log(t.indent+"timescale: "+this.timescale),t.log(t.indent+"duration: "+this.duration),t.log(t.indent+"rate: "+this.rate),t.log(t.indent+"volume: "+(this.volume>>8)),t.log(t.indent+"matrix: "+this.matrix.join(", ")),t.log(t.indent+"next_track_id: "+this.next_track_id)},r.tkhdBox.prototype.print=function(t){r.FullBox.prototype.printHeader.call(this,t),t.log(t.indent+"creation_time: "+this.creation_time),t.log(t.indent+"modification_time: "+this.modification_time),t.log(t.indent+"track_id: "+this.track_id),t.log(t.indent+"duration: "+this.duration),t.log(t.indent+"volume: "+(this.volume>>8)),t.log(t.indent+"matrix: "+this.matrix.join(", ")),t.log(t.indent+"layer: "+this.layer),t.log(t.indent+"alternate_group: "+this.alternate_group),t.log(t.indent+"width: "+this.width),t.log(t.indent+"height: "+this.height)};var U={};U.createFile=function(t,e){var i=t!==void 0?t:!0,s=new g(e);return s.discardMdatData=!i,s},n.createFile=U.createFile})(Hi);function jn(n,a){var h,l,f,d;try{const p=n.getTrackById(a);for(const r of p.mdia.minf.stbl.stsd.entries){const b=r.esds,S=(d=(f=(l=(h=b==null?void 0:b.esd)==null?void 0:h.descs)==null?void 0:l[0])==null?void 0:f.descs)==null?void 0:d[0];if(S!=null&&S.data)return S.data}}catch{}return null}async function ii(n){return new Promise(a=>{let h=!1;const l=f=>{h||(h=!0,a(f))};try{const f=Hi.createFile(),d=[];let p=null,r=null;f.onError=()=>l(null),f.onReady=S=>{const g=S.audioTracks&&S.audioTracks[0];if(!g||!(g.codec||"").startsWith("mp4a")){l(null);return}if(p=g,r=jn(f,g.id),!r){l(null);return}f.setExtractionOptions(g.id,null,{nbSamples:1e6}),f.start()},f.onSamples=(S,g,U)=>{for(const t of U)d.push({data:new Uint8Array(t.data),timestamp:t.cts/t.timescale*1e6,duration:t.duration/t.timescale*1e6,key:!!t.is_sync})};const b=n.slice(0);b.fileStart=0,f.appendBuffer(b),f.flush(),setTimeout(()=>{var S,g;if(!p||!r||d.length===0){l(null);return}l({sampleRate:((S=p.audio)==null?void 0:S.sample_rate)||44100,numberOfChannels:((g=p.audio)==null?void 0:g.channel_c
21ount)||2,description:r,samples:d})},0)}catch{l(null)}})}const Gn=408125543,Hn=374648427,Vi=174,Vn=225,Wi=524531317,Wn=160,Yn=215,$n=131,qn=134,Kn=25506,Xn=159,Zn=2807729,Qn=231,Jn=163,ts=161,es=new Set([Gn,Hn,Vi,Vn,Wi,Wn]);function is(n,a){if(a>=n.length)return null;const h=n[a];let l=128,f=1;for(;f<=4&&!(h&l);)l>>=1,f++;if(f>4)return null;let d=0;for(let p=0;p<f;p++)d=d*256+n[a+p];return{id:d,len:f}}function rs(n,a){if(a>=n.length)return null;const h=n[a];let l=128,f=1;for(;f<=8&&!(h&l);)l>>=1,f++;if(f>8)return null;let d=h&l-1,p=d===l-1;for(let r=1;r<f;r++)d=d*256+n[a+r],n[a+r]!==255&&(p=!1);return{size:d,len:f,unknown:p}}function Xt(n,a,h){let l=0;for(let f=0;f<h;f++)l=l*256+n[a+f];return l}function ns(n,a){const h=n[a];let l=128,f=1;for(;f<=8&&!(h&l);)l>>=1,f++;let d=h&l-1;for(let p=1;p<f;p++)d=d*256+n[a+p];return{value:d,len:f}}function ss(n){try{const a=new Uint8Array(n);if(!(a[0]===26&&a[1]===69&&a[2]===223&&a[3]===163))return null;let h=1e6,l=-1,f=0,d=null,p=-1,r=-1,b=0,S=!1,g=null,U=!1;const t=()=>{U&&r===2&&S&&l===-1&&(l=p,f=b||2,d=g),U=!1,p=-1,r=-1,b=0,S=!1,g=null};let e=0;const i=[];let s=0;for(;s<a.length;){const o=is(a,s);if(!o)break;s+=o.len;const u=rs(a,s);if(!u)break;s+=u.len;const c=o.id;if(es.has(c)){c===Vi?(t(),U=!0):c===Wi&&(t(),e=0);continue}const m=s,x=u.size;switch(c){case Zn:h=Xt(a,m,x);break;case Yn:p=Xt(a,m,x);break;case $n:r=Xt(a,m,x);break;case qn:{S=new TextDecoder().decode(a.subarray(m,m+x)).indexOf("A_OPUS")===0;break}case Kn:g=a.slice(m,m+x);break;case Xn:b=Xt(a,m,x);break;case Qn:e=Xt(a,m,x);break;case Jn:case ts:{if(l>=0){const w=ns(a,m);if(w.value===l){const v=a[m+w.len]<<8|a[m+w.len+1],E=v>32767?v-65536:v,C=a[m+w.len+2]>>1&3,N=m+w.len+3;if(C===0){const z=(e+E)*(h/1e6);i.push({data:a.slice(N,m+x),timestamp:Math.round(z*1e3),duration:2e4})}}}break}}s=m+x}if(t(),l<0||!d||i.length===0)return null;for(let o=0;o<i.length-1;o++){const u=i[o+1].timestamp-i[o].timestamp;u>0&&u<2e5&&(i[o].duration=u)}return{sampleRate:48e3,numberOfChannels:f||2,description:d,packets:i}}catch{return null}}const rt=globalThis;function as(){return typeof rt.VideoEncoder=="function"&&typeof rt.VideoFrame=="function"}const mi=n=>Math.max(2,Math.floor(n/2)*2);function os(){if(typeof navigator>"u")return!1;const n=navigator.userAgent||"",a=/Macintosh/.test(n)&&navigator.maxTouchPoints>1;return/iP(hone|ad|od)/.test(n)||a}async function ls(n,a,h,l){const f=typeof rt.AudioDecoder=="function"&&typeof rt.EncodedAudioChunk=="function",d=typeof rt.AudioEncoder=="function";if(!f||!d)return!1;const p={codec:"mp4a.40.2",sampleRate:h,numberOfChannels:l,description:n.description},r={codec:"mp4a.40.2",sampleRate:h,numberOfChannels:l,bitrate:16e4};try{const[g,U]=await Promise.all([rt.AudioDecoder.isConfigSupported(p),rt.AudioEncoder.isConfigSupported(r)]);if(!(g!=null&&g.supported)||!(U!=null&&U.supported))return!1}catch{return!1}const b=[];return!await new Promise(g=>{try{const U=new rt.AudioDecoder({output:t=>b.push(t),error:()=>g(!1)});U.configure(p);for(const t of n.samples)U.decode(new rt.EncodedAudioChunk({type:t.key?"key":"delta",timestamp:t.timestamp,duration:t.duration,data:t.data}));U.flush().then(()=>{try{U.close()}catch{}g(!0)}).catch(()=>g(!1))}catch{g(!1)}})||b.length===0?(b.forEach(g=>{try{g.close()}catch{}}),!1):(await new Promise((g,U)=>{try{const t=new rt.AudioEncoder({output:(e,i)=>a.addAudioChunk(e,i),error:e=>U(e instanceof Error?e:new Error(String(e)))});t.configure(r);for(const e of b)try{t.encode(e)}finally{try{e.close()}catch{}}t.flush().then(()=>{try{t.close()}catch{}g()}).catch(U)}catch(t){U(t instanceof Error?t:new Error(String(t)))}}),!0)}function hs(n,a,h){const l=Math.round(n*a*h*.16);return Math.min(48e6,Math.max(12e6,l))}async function ds(n,a,h,l){const f=["avc1.640034","avc1.640028","avc1.4d0028","avc1.42e028","avc1.42001f"];for(const d of f){const p={codec:d,width:n,height:a,bitrate:l,framerate:h,avc:{format:"avc"}};try{const r=await rt.VideoEncoder.isConfigSupported(p);if(r!=null&&r.supported)return p}catch{}}return null}async function Ps({videoUrl:n,script:a,style:h,font:l,position:f,animationId:d,durationFallback:p,timedChunks:r,output:b,focus:S,trim:g,zoom:U,onProgress:t,signal:e}){if(!as())throw new Error("WebCodecs not supported in this browser.");let i=null,s;try{const u=await fetch(n,{mode:"cors"});if(!u.ok)throw new Error(`Could not fetch the video (${u.status}).`);const c=await u.blob();s=await c.arrayBuffer(),i=URL.createObjectURL(c)}catch{throw new Error("Could not load the video for captioning.")}const o=document.createElement("video");
21o.src=i,o.muted=!0,o.defaultMuted=!0,o.playsInline=!0,o.crossOrigin="anonymous",o.setAttribute("muted",""),o.setAttribute("playsinline",""),o.style.cssText="position:fixed;left:-99999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none;",document.body.appendChild(o);try{await new Promise((L,W)=>{o.onloadedmetadata=()=>L(),o.onerror=()=>W(new Error("Could not load the video for captioning."))});const u=mi((b==null?void 0:b.width)||o.videoWidth||1080),c=mi((b==null?void 0:b.height)||o.videoHeight||1920),m=await He(o),x=p&&isFinite(p)?p:0,w=m||x;if(!w)throw new Error("Video has no readable duration.");const v=g?Math.max(0,Math.min(g.start,w)):0,E=g?Math.min(w,Math.max(g.end,v+.1)):w,F=g?Math.max(.1,E-v):w,C=30,N=await ds(u,c,C,hs(u,c,C));if(!N)throw new Error("No supported H.264 encoder configuration.");const z=await ii(s);let H=null,j,X;if(z)j=z.sampleRate,X=z.numberOfChannels;else{H=ss(s);const L=typeof rt.AudioDecoder=="function"&&typeof rt.AudioEncoder=="function"&&typeof rt.EncodedAudioChunk=="function";if(!H||!L)throw new Error("Source audio needs transcoding (non-MP4/AAC).");j=H.sampleRate,X=H.numberOfChannels}const V=new Gi({target:new $e,video:{codec:"avc",width:u,height:c},audio:{codec:"aac",numberOfChannels:X,sampleRate:j},fastStart:"in-memory",firstTimestampBehavior:"offset"}),M=document.createElement("canvas");M.width=u,M.height=c;const Y=M.getContext("2d",{alpha:!1});if(!Y)throw new Error("Canvas 2D context unavailable.");const Q=await Ci({width:u,height:c,duration:F,script:a,style:h,font:l,position:f,animationId:d,timedChunks:r,focus:S,zoom:U}),P=new rt.VideoEncoder({output:(L,W)=>V.addVideoChunk(L,W),error:L=>{throw L instanceof Error?L:new Error(String(L))}});P.configure(N);const $=30,k=Math.round(1e6/$),ht=Math.max(1,Math.round(F*$)),pt=$*2,At=L=>new Promise(W=>setTimeout(W,L)),Ft=(L,W)=>{const q=new rt.VideoFrame(M,{timestamp:Math.max(0,L),duration:k});P.encode(q,{keyFrame:W}),q.close()},wt=typeof o.requestVideoFrameCallback=="function",Wt=L=>new Promise(W=>{let q=!1;const J=()=>{q||(q=!0,o.removeEventListener("seeked",gt),W())},gt=()=>J();o.addEventListener("seeked",gt);const K=Math.min(Math.max(0,L),Math.max(0,w-.001));if(Math.abs(o.currentTime-K)<.001){setTimeout(J,0);return}try{o.currentTime=K}catch{J()}setTimeout(J,2e3)}),tt=()=>new Promise(L=>{let W=!1;const q=()=>{W||(W=!0,L())};if(wt)try{o.requestVideoFrameCallback(()=>q())}catch{}requestAnimationFrame(()=>requestAnimationFrame(q)),setTimeout(q,300)});try{o.pause()}catch{}for(let L=0;L<ht;L++){if(e!=null&&e.cancelled)throw new Error("Captioning cancelled.");const W=L/$;for(await Wt(v+W),await tt(),Q(Y,o,W),Ft(L*k,L%pt===0),t==null||t(Math.min(90,Math.round(L/ht*90)));P.encodeQueueSize>60;)await At(5)}await P.flush(),P.close();const mt=v*1e6,ot=E*1e6,_t=(L,W)=>!g||L+W>mt&&L<ot,T=L=>Math.max(0,Math.round(L-(g?mt:0)));if(z){const L=g?{...z,samples:z.samples.filter(q=>_t(q.timestamp,q.duration)).map(q=>({...q,timestamp:T(q.timestamp)}))}:z;(os()?await ls(L,V,j,X):!1)||L.samples.forEach((q,J)=>{V.addAudioChunkRaw(q.data,q.key?"key":"delta",Math.max(0,Math.round(q.timestamp)),Math.max(0,Math.round(q.duration)),J===0?{decoderConfig:{codec:"mp4a.40.2",sampleRate:j,numberOfChannels:X,description:L.description}}:void 0)})}else if(H){const L=g?H.packets.filter(W=>_t(W.timestamp,W.duration)).map(W=>({...W,timestamp:T(W.timestamp)})):H.packets;await new Promise((W,q)=>{try{const J=new rt.AudioEncoder({output:(K,Yt)=>V.addAudioChunk(K,Yt),error:K=>q(K instanceof Error?K:new Error(String(K)))});J.configure({codec:"mp4a.40.2",sampleRate:j,numberOfChannels:X,bitrate:128e3});const gt=new rt.AudioDecoder({output:K=>{try{J.encode(K)}finally{K.close()}},error:K=>q(K instanceof Error?K:new Error(String(K)))});gt.configure({codec:"opus",sampleRate:j,numberOfChannels:X,description:H.description});for(const K of L)gt.decode(new rt.EncodedAudioChunk({type:"key",timestamp:K.timestamp,duration:K.duration,data:K.data}));(async()=>{await gt.flush(),gt.close(),await J.flush(),J.close(),W()})().catch(K=>q(K instanceof Error?K:new Error(String(K))))}catch(J){q(J instanceof Error?J:new Error(String(J)))}})}V.finalize(),t==null||t(100);const{buffer:Tt}=V.target;return{blob:new Blob([Tt],{type:"video/mp4"}),ext:"mp4"}}finally{i&&URL.revokeObjectURL(i),o.remove()}}async function ri(n){const a=lr();return n==null||n(8),a}async function fs(n){return new Promise(a=>{const h=document.createElement("video");h.preload="metadata",h.muted=!0,h.src=n,h.onloadedmetadata=async()=>{const l=await He(h);a({width:h.videoWidth||1080,height:h.videoHeight||1920,duration:l})},h.onerror=()=>a({width:1080,height:1920,duration:0})})}function ni(n){return n==="mov"?{ext:"mov",mime:"video/quicktime"}:{ext:"mp4",mime:"video/mp4"}}async function Rs({videoUrl:n,script:a,style:h,font:l,position:f,durationFallback:d,format:p="mp4",timedChunks:r,output:b,focus:S,trim:g,zoom:U,onProgress:t}){if(!je())throw new Error("WebAssembly not supported in this browser.");const{ext:e,mime:i}=ni(p),{width:s,height:o,duration:u}=await fs(n),c=u||d||0;if(!c)throw new Error("Could not read the video duration.");const m=g?Math.max(0,Math.min(g.start,c)):0,x=g?Math.min(c,Math.max(g.end,m+.1)):c,w=g?Math.max(.1,x-m):c,v=(b==null?void 0:b.height)||o,E=await ri(t);t==null||t(15);const F=({progress:C})=>{C>=0&&C<=1&&(t==null||t(15+Math.round(C*80)))};E.on("progress",F);try{await E.writeFile("in.mp4",await Fe(n));let C="Caption";try{l!=null&&l.ttfUrl&&(await E.writeFile("font.ttf",await Fe(l.ttfUrl)),C=l.name)}catch{}const N=zr(a,w,h,l,v,f,r);await E.writeFile("subs.ass",new TextEncoder().encode(N));const z=U&&U>0?U:1;let H="";if(b||z>1){const Q=(b==null?void 0:b.width)??(s||1080),P=(b==null?void 0:b.height)??(o||1920),$=Math.round(Q*z),k=Math.round(P*z),ht=S?Math.min(1,Math.max(0,S.x)):.5,pt=S?Math.min(1,Math.max(0,S.y)):.5,At=`clip(in_w*${ht.toFixed(4)}-${Q}/2,0,in_w-${Q})`,Ft=`clip(in_h*${pt.toFixed(4)}-${P}/2,0,in_h-${P})`;H=`scale=${$}:${k}:force_original_aspect_ratio=increase,crop=${Q}:${P}:'${At}':'${Ft}',`}const j=`out.${e}`,X=g?["-ss",m.toFixed(3)]:[],V=g?["-t",w.toFixed(3)]:[];await E.exec([...X,"-i","in.mp4",...V,"-vf",`${H}subtitles=subs.ass:fontsdir=.`,"-c:v","libx264","-preset","veryfast","-crf","18","-pix_fmt","yuv420p","-c:a","aac","-b:a","192k","-movflags","+faststart",j]);const M=await E.readFile(j);t==null||t(100);const Y=M instanceof Uint8Array?M:new TextEncoder().encode(String(M));return{blob:new Blob([Y],{type:i}),ext:e}}finally{E.off("progress",F);for(const C of["in.mp4","out.mp4","out.mov","subs.ass","font.ttf"])try{await E.deleteFile(C)}catch{}}}async function Os({videoUrl:n,format:a="mp4",onProgress:h}){if(!je())throw new Error("WebAssembly not supported in this browser.");const{ext:l,mime:f}=ni(a),d=await ri(h);h==null||h(20);const p=({progress:b})=>{b>=0&&b<=1&&(h==null||h(20+Math.round(b*75)))};d.on("progress",p);const r=`remux.${l}`;try{await d.writeFile("src.mp4",await Fe(n)),await d.exec(["-i","src.mp4","-c","copy","-movflags","+faststart",r]);const b=await d.readFile(r);h==null||h(100);const S=b instanceof Uint8Array?b:new TextEncoder().encode(String(b));return{blob:new Blob([S],{type:f}),ext:l}}finally{d.off("progress",p);for(const b of["src.mp4","remux.mp4","remux.mov"])try{await d.deleteFile(b)}catch{}}}async function js(n,a,h){if(!je())throw new Error("WebAssembly not supported in this browser.");const{ext:l,mime:f}=ni(a),d=await ri(h);h==null||h(20);const p=({progress:b})=>{b>=0&&b<=1&&(h==null||h(20+Math.round(b*75)))};d.on("progress",p);const r=`tx.${l}`;try{await d.writeFile("tx-in",new Uint8Array(await n.arrayBuffer())),await d.exec(["-i","tx-in","-c:v","libx264","-preset","veryfast","-crf","18","-pix_fmt","yuv420p","-c:a","aac","-b:a","192k","-movflags","+faststart",r]);const b=await d.readFile(r);h==null||h(100);const S=b instanceof Uint8Array?b:new TextEncoder().encode(String(b));return{blob:new Blob([S],{type:f}),ext:l}}finally{d.off("progress",p);for(const b of["tx-in","tx.mp4","tx.mov"])try{await d.deleteFile(b)}catch{}}}const Lt=globalThis;async function cs(n,a){const h=(a==null?void 0:a.trim)??null,l=(a==null?void 0:a.format)??"mp3",f=await fetch(n);if(!f.ok)throw new Error("Could not load the video to extract audio.");const d=await f.arrayBuffer();if(l==="mp3"){let r=await us(d);if(r||(r=await Yi(d)),r){const b=$i(r,h);try{const S=await ps(b.channels,b.sampleRate);if(S.size>0)return{blob:S,ext:"mp3"}}catch{}}}const p=await ms(d,h);return p||await _s(d,h)}async function us(n){if(typeof Lt.AudioDecoder!="function"||typeof Lt.EncodedAudioChunk!="function")return null;let a;try{a=await ii(n)}catch{a=null}if(!a)return null;const{sampleRate:h,numberOfChannels:l,description:f,samples:d}=a,p={codec:"mp4a.40.2",sampleRate:h,numberOfChannels:l,description:f};try{const S=await Lt.AudioDecoder.isConfigSupported(p);if(!(S!=null&&S.supported))return null}catch{return null}const r=[];if(!await new Promise(S=>{try{const g=new Lt.AudioDecoder({output:U=>r.push(U),error:()=>S(!1)});g.configure(p);for(const U of d)g.decode(new Lt.EncodedAudioChunk({type:U.key?"key":"delta",timestamp:U.timestamp,duration:U.duration,data:U.data}));g.flush().then(()=>{try{g.close()}catch{}S(!0)}).catch(()=>S(!1))}catch{S(!1)}})||r.length===0)return r.forEach(S=>{try{S.close()}catch{}}),null;try{const S=Math.max(1,l);let g=0;for(const e of r)g+=e.numberOfFrames;const U=[];for(let e=0;e<S;e++)U.push(new Float32Array(g));let t=0;for(const e of r){const i=e.numberOfFrames;for(let s=0;s<S;s++){const o=new Float32Array(i);try{e.copyTo(o,{planeIndex:s,format:"f32-planar"})}catch{}U[s].set(o,t)}t+=i;try{e.close()}catch{}}return{channels:U,sampleRate:h}}catch{return r.forEach(S=>{try{S.close()}catch{}}),null}}async function Yi(n){const a=Lt.AudioContext||Lt.webkitAudioContext;if(!a)return null;const h=new a;try{const l=await h.decodeAudioData(n.slice(0)),f=[];for(let d=0;d<l.numberOfChannels;d++)f.push(l.getChannelData(d).slice());
21return{channels:f,sampleRate:l.sampleRate}}catch{return null}finally{try{await h.close()}catch{}}}function $i(n,a){var r;if(!a)return n;const{channels:h,sampleRate:l}=n,f=((r=h[0])==null?void 0:r.length)??0,d=Math.max(0,Math.floor(a.start*l)),p=Math.min(f,Math.ceil(a.end*l));return p<=d?n:{channels:h.map(b=>b.slice(d,p)),sampleRate:l}}function _i(n){const a=new Int16Array(n.length);for(let h=0;h<n.length;h++){const l=Math.max(-1,Math.min(1,n[h]));a[h]=l<0?l*32768:l*32767}return a}async function ps(n,a,h=192){var t;const l=await Qi(()=>import("./lamejs-Bfg6XjLl.js"),[]),f=l.Mp3Encoder||((t=l.default)==null?void 0:t.Mp3Encoder);if(!f)throw new Error("MP3 encoder unavailable.");const d=Math.min(2,n.length)||1,p=new f(d,a,h),r=_i(n[0]||new Float32Array(0)),b=d>1?_i(n[1]):null,S=1152,g=[];for(let e=0;e<r.length;e+=S){const i=r.subarray(e,e+S),s=b?p.encodeBuffer(i,b.subarray(e,e+S)):p.encodeBuffer(i);s&&s.length&&g.push(new Uint8Array(s))}const U=p.flush();return U&&U.length&&g.push(new Uint8Array(U)),new Blob(g,{type:"audio/mpeg"})}async function ms(n,a){let h;try{h=await ii(n)}catch{h=null}if(!h)return null;try{const{sampleRate:l,numberOfChannels:f,description:d}=h,p=a?a.start*1e6:0,r=a?a.end*1e6:1/0,b=a?h.samples.filter(U=>U.timestamp+U.duration>p&&U.timestamp<r).map(U=>({...U,timestamp:Math.max(0,U.timestamp-p)})):h.samples;if(b.length===0)return null;const S=new Gi({target:new $e,audio:{codec:"aac",numberOfChannels:f,sampleRate:l},fastStart:"in-memory",firstTimestampBehavior:"offset"});b.forEach((U,t)=>{S.addAudioChunkRaw(U.data,U.key?"key":"delta",Math.max(0,Math.round(U.timestamp)),Math.max(0,Math.round(U.duration)),t===0?{decoderConfig:{codec:"mp4a.40.2",sampleRate:l,numberOfChannels:f,description:d}}:void 0)}),S.finalize();const{buffer:g}=S.target;return{blob:new Blob([g],{type:"audio/mp4"}),ext:"m4a"}}catch{return null}}async function _s(n,a){const h=await Yi(n);if(!h)throw new Error("Audio extraction isnât supported in this browser.");const l=$i(h,a);return{blob:gs(l.channels,l.sampleRate),ext:"wav"}}function gs(n,a){var U;const h=Math.max(1,n.length),l=((U=n[0])==null?void 0:U.length)??0,f=2,d=h*f,p=l*d,r=new ArrayBuffer(44+p),b=new DataView(r),S=(t,e)=>{for(let i=0;i<e.length;i++)b.setUint8(t+i,e.charCodeAt(i))};S(0,"RIFF"),b.setUint32(4,36+p,!0),S(8,"WAVE"),S(12,"fmt "),b.setUint32(16,16,!0),b.setUint16(20,1,!0),b.setUint16(22,h,!0),b.setUint32(24,a,!0),b.setUint32(28,a*d,!0),b.setUint16(32,d,!0),b.setUint16(34,8*f,!0),S(36,"data"),b.setUint32(40,p,!0);let g=44;for(let t=0;t<l;t++)for(let e=0;e<h;e++){let i=n[e][t]||0;i=Math.max(-1,Math.min(1,i)),b.setInt16(g,i<0?i*32768:i*32767,!0),g+=2}return new Blob([r],{type:"audio/wav"})}const Gs=Object.freeze(Object.defineProperty({__proto__:null,extractAudio:cs},Symbol.toStringTag,{value:"Module"}));export{hr as C,cr as D,zs as S,Es as a,Ts as b,Cs as c,Bs as d,bi as e,ks as f,ur as g,Is as h,As as i,Fs as j,li as k,Tr as l,as as m,Ps as n,Rs as o,Ds as p,Ms as q,He as r,Os as s,js as t,Ls as u,Ns as v,br as w,zr as x,cs as y,Gs as z};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.