1import{bJ as as,p as sl,d as Fr,o as Z,a as re,h as be,u as w,b as L,t as Y,v as $e,j as nt,e as Ce,f as pe,aa as Br,m as zn,cT as al,a9 as Gr,U as dn,n as qt,F as Qe,E as Xt,k as Dt,l as ke,Z as os,J as cs,s as bt,ab as ol,cu as cl,L as ll,a8 as ul,C as dl,a_ as sa,D as fl}from"./BnyHmBjY.js";import{i as hl,g as ml}from"./gLRRMFFU.js";import{k as pl,r as gl,l as bl,n as kl}from"./DJlwB_t4.js";/** 2 * @license lucide-vue-next v0.475.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const yl=r=>r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/** 7 * @license lucide-vue-next v0.475.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */var Mi={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"};/** 12 * @license lucide-vue-next v0.475.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const wl=({size:r,strokeWidth:e=2,absoluteStrokeWidth:t,color:i,iconNode:n,name:s,class:a,...o},{slots:c})=>as("svg",{...Mi,width:r||Mi.width,height:r||Mi.height,stroke:i||Mi.stroke,"stroke-width":t?Number(e)*24/Number(r):e,class:["lucide",`lucide-${yl(s??"icon")}`],...o},[...n.map(l=>as(...l)),...c.default?[c.default()]:[]]);/** 17 * @license lucide-vue-next v0.475.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const Ee=(r,e)=>(t,{slots:i})=>as(wl,{...t,iconNode:e,name:r},i);/** 22 * @license lucide-vue-next v0.475.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const xl=Ee("ArrowLeftIcon",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** 27 * @license lucide-vue-next v0.475.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const Tl=Ee("CameraIcon",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/** 32 * @license lucide-vue-next v0.475.0 - ISC 33 * 34 * This source code is licensed under the ISC license. 35 * See the LICENSE file in the root directory of this source tree. 36 */const Wi=Ee("CircleAlertIcon",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** 37 * @license lucide-vue-next v0.475.0 - ISC 38 * 39 * This source code is licensed under the ISC license. 40 * See the LICENSE file in the root directory of this source tree. 41 */const _l=Ee("CircleCheckIcon",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** 42 * @license lucide-vue-next v0.475.0 - ISC 43 * 44 * This source code is licensed under the ISC license. 45 * See the LICENSE file in the root directory of this source tree. 46 */const Sl=Ee("CircleHelpIcon",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** 47 * @license lucide-vue-next v0.475.0 - ISC 48 * 49 * This source code is licensed under the ISC license. 50 * See the LICENSE file in the root directory of this source tree. 51 */const vl=Ee("DownloadIcon",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** 52 * @license lucide-vue-next v0.475.0 - ISC 53 * 54 * This source code is licensed under the ISC license. 55 * See the LICENSE file in the root directory of this source tree. 56 */const Pl=Ee("FilePlus2Icon",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);/** 57 * @license lucide-vue-next v0.475.0 - ISC 58 * 59 * This source code is licensed under the ISC license. 60 * See the LICENSE file in the root directory of this source tree.
61 */const ko=Ee("FilmIcon",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]);/** 62 * @license lucide-vue-next v0.475.0 - ISC 63 * 64 * This source code is licensed under the ISC license. 65 * See the LICENSE file in the root directory of this source tree. 66 */const Hi=Ee("InfoIcon",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/** 67 * @license lucide-vue-next v0.475.0 - ISC 68 * 69 * This source code is licensed under the ISC license. 70 * See the LICENSE file in the root directory of this source tree. 71 */const yo=Ee("LoaderCircleIcon",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** 72 * @license lucide-vue-next v0.475.0 - ISC 73 * 74 * This source code is licensed under the ISC license. 75 * See the LICENSE file in the root directory of this source tree. 76 */const Cl=Ee("MagnetIcon",[["path",{d:"m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15",key:"1i3lhw"}],["path",{d:"m5 8 4 4",key:"j6kj7e"}],["path",{d:"m12 15 4 4",key:"lnac28"}]]);/** 77 * @license lucide-vue-next v0.475.0 - ISC 78 * 79 * This source code is licensed under the ISC license. 80 * See the LICENSE file in the root directory of this source tree. 81 */const Il=Ee("MonitorPlayIcon",[["path",{d:"M10 7.75a.75.75 0 0 1 1.142-.638l3.664 2.249a.75.75 0 0 1 0 1.278l-3.664 2.25a.75.75 0 0 1-1.142-.64z",key:"1pctta"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}]]);/** 82 * @license lucide-vue-next v0.475.0 - ISC 83 * 84 * This source code is licensed under the ISC license. 85 * See the LICENSE file in the root directory of this source tree. 86 */const El=Ee("MonitorXIcon",[["path",{d:"m14.5 12.5-5-5",key:"1jahn5"}],["path",{d:"m9.5 12.5 5-5",key:"1k2t7b"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** 87 * @license lucide-vue-next v0.475.0 - ISC 88 * 89 * This source code is licensed under the ISC license. 90 * See the LICENSE file in the root directory of this source tree. 91 */const Al=Ee("PauseIcon",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** 92 * @license lucide-vue-next v0.475.0 - ISC 93 * 94 * This source code is licensed under the ISC license. 95 * See the LICENSE file in the root directory of this source tree. 96 */const zl=Ee("PlayIcon",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** 97 * @license lucide-vue-next v0.475.0 - ISC 98 * 99 * This source code is licensed under the ISC license. 100 * See the LICENSE file in the root directory of this source tree. 101 */const Fl=Ee("PlusIcon",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** 102 * @license lucide-vue-next v0.475.0 - ISC 103 * 104 * This source code is licensed under the ISC license. 105 * See the LICENSE file in the root directory of this source tree. 106 */const Bl=Ee("Redo2Icon",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]]);/** 107 * @license lucide-vue-next v0.475.0 - ISC 108 * 109 * This source code is licensed under the ISC license. 110 * See the LICENSE file in the root directory of this source tree. 111 */const Rl=Ee("ScissorsIcon",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]]);/** 112 * @license lucide-vue-next v0.475.0 - ISC 113 * 114 * This source code is licensed under the ISC license. 115 * See the LICENSE file in the root directory of this source tree. 116 */const Ml=Ee("SkipBackIcon",[["polygon",{points:"19 20 9 12 19 4 19 20",key:"o2sva"}],["line",{x1:"5",x2:"5",y1:"19",y2:"5",key:"1ocqjk"}]]);/** 117 * @license lucide-vue-next v0.475.0 - ISC 118 * 119 * This source code is licensed under the ISC license. 120 * See the LICENSE file in the root directory of this source tree. 121 */const Ol=Ee("SkipForwardIcon",[["polygon",{points:"5 4 15 12 5 20 5 4",key:"16p6eg"}],["line",{x1:"19",x2:"19",y1:"5",y2:"19",key:"futhcm"}]]);/** 122 * @license lucide-vue-next v0.475.0 - ISC 123 * 124 * This source code is licensed under the ISC license. 125 * See the LICENSE file in the root directory of this source tree. 126 */const Dl=Ee("Trash2Icon",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}
126],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** 127 * @license lucide-vue-next v0.475.0 - ISC 128 * 129 * This source code is licensed under the ISC license. 130 * See the LICENSE file in the root directory of this source tree. 131 */const Nl=Ee("Undo2Icon",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/** 132 * @license lucide-vue-next v0.475.0 - ISC 133 * 134 * This source code is licensed under the ISC license. 135 * See the LICENSE file in the root directory of this source tree. 136 */const Ul=Ee("UploadIcon",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** 137 * @license lucide-vue-next v0.475.0 - ISC 138 * 139 * This source code is licensed under the ISC license. 140 * See the LICENSE file in the root directory of this source tree. 141 */const fn=Ee("XIcon",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** 142 * @license lucide-vue-next v0.475.0 - ISC 143 * 144 * This source code is licensed under the ISC license. 145 * See the LICENSE file in the root directory of this source tree. 146 */const Vl=Ee("ZoomInIcon",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** 147 * @license lucide-vue-next v0.475.0 - ISC 148 * 149 * This source code is licensed under the ISC license. 150 * See the LICENSE file in the root directory of this source tree. 151 */const Ll=Ee("ZoomOutIcon",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Wl={page_title:"Video-Studio",studio_title:"Studio",back:"Zurück",undo:"Rückgängig",redo:"Wiederholen",export:"Exportieren",media_title:"Medien",media_empty_title:"Noch keine Medien",media_empty_desc:"Ãffnen Sie Versionen aus einer Generierung oder fügen Sie ein Video von Ihrem Computer hinzu.",media_add_local:"Lokales Video hinzufügen",viewer_empty:"Hier erscheint die Vorschau",inspector_title:"Clip",inspector_empty:"Wählen Sie einen Clip in der Timeline aus, um seine Details zu sehen.",timeline_empty:"Ziehen Sie Medien hierher, um mit dem Schneiden zu beginnen.",split:"Teilen",delete:"Löschen",unsupported_title:"Bitte verwenden Sie einen Computer",unsupported_desc:"Das Studio benötigt einen Bildschirm mit mindestens 1024 px Breite.",media_section_handoff:"Aus der Generierung",media_section_recent:"Letzte Generierungen",media_section_local:"Lokale Dateien",media_add_to_timeline:"Zur Timeline hinzufügen",media_probing:"Video wird gelesenâ¦",media_unsupported_origin:"Diese Quelle kann im Studio noch nicht bearbeitet werden.",media_unsupported_codec:"Dieser Browser kann das Video nicht decodieren.",media_error_network:"Video konnte nicht geladen werden.",media_too_large:"Datei ist gröÃer als 200 MB.",media_no_video:"Keine Videospur gefunden.",media_remove:"Entfernen",media_download:"Herunterladen",recent_empty:"Keine kürzlich erstellten Videos auf diesem Gerät.",play:"Abspielen",pause:"Pause",prev_frame:"Vorheriges Bild",next_frame:"Nächstes Bild",inspector_prompt:"Prompt",inspector_model:"Modell",inspector_in:"Ein",inspector_out:"Aus",inspector_duration:"Dauer",zoom_in:"VergröÃern",zoom_out:"Verkleinern",zoom:"Zoom",snap:"Einrasten",shortcuts:"Tastenkürzel",sc_play:"Wiedergabe / Pause",sc_frame:"Vorheriger / nächster Frame",sc_second:"1 Sekunde zurück / vor",sc_split:"Am Abspielkopf teilen",sc_delete:"Clip löschen",sc_undo:"Rückgängig",sc_redo:"Wiederholen",sc_in_out:"Ein- / Ausgangspunkt auf Abspielkopf setzen",sc_zoom:"Timeline zoomen",sc_move:"Clip nach links / rechts bewegen",clip_aria:"Clip {n}: {start} â {end}",invalid_timecode:"Format MM:SS:FF verwenden",split_at_playhead:"Am Abspielkopf teilen",export_title:"Video exportieren",export_resolution:"Auflösung",export_res_source:"Original",export_duration:"Dauer",exp
151ort_start:"Exportieren",export_cancel:"Abbrechen",export_progress:"Export läuft⦠{pct}%",export_done:"Export abgeschlossen",export_file_size:"DateigröÃe",export_download:"Herunterladen",export_continue:"Weiter bearbeiten",export_failed:"Der Export ist fehlgeschlagen. Bitte versuche es erneut.",export_retry:"Erneut versuchen",export_too_long:"Die Timeline ist länger als 2 Minuten. Kürze sie zum Exportieren.",export_unsupported:"Dieser Browser kann kein Video exportieren. Bitte verwende die neueste Version von Chrome oder Edge.",export_no_audio_encoder:"Dieser Browser kann kein Audio kodieren, daher wird das Video ohne Ton exportiert.",export_no_audio:"Keiner der Clips hat eine Tonspur, das Video wird daher stumm sein.",export_mixed_aspect:"Clips mit abweichendem Seitenverhältnis werden mit schwarzen Balken angezeigt.",export_keep_open:"Bitte lasse diesen Tab geöffnet, bis der Export abgeschlossen ist.",export_close:"SchlieÃen",export_checking:"Browser-Unterstützung wird geprüftâ¦",use_frame:"Dieses Bild als erstes Frame verwenden",use_frame_uploading:"Frame wird hochgeladenâ¦",use_frame_failed:"Das Frame konnte nicht hochgeladen werden. Bitte erneut versuchen.",new_project:"Neues Projekt",autosave_local_removed:"Lokale Dateien können nach einem Neuladen nicht wiederhergestellt werden und wurden aus dem Projekt entfernt.",dismiss:"SchlieÃen"},Hl={de:Wl},ql={page_title:"Video Studio",studio_title:"Studio",back:"Back",undo:"Undo",redo:"Redo",export:"Export",media_title:"Media",media_empty_title:"No media yet",media_empty_desc:"Open versions from a generation, or add a video from your computer.",media_add_local:"Add local video",viewer_empty:"Preview appears here",inspector_title:"Clip",inspector_empty:"Select a clip on the timeline to see its details.",timeline_empty:"Drag media here to start editing.",split:"Split",delete:"Delete",unsupported_title:"Please use a computer",unsupported_desc:"The studio needs a screen at least 1024px wide.",media_section_handoff:"From generation",media_section_recent:"Recent generations",media_section_local:"Local files",media_add_to_timeline:"Add to timeline",media_probing:"Reading videoâ¦",media_unsupported_origin:"This source can't be edited in the studio yet.",media_unsupported_codec:"This browser can't decode this video.",media_error_network:"Couldn't load this video.",media_too_large:"File is larger than 200 MB.",media_no_video:"No video track found.",media_remove:"Remove",media_download:"Download",recent_empty:"No recent videos on this device.",play:"Play",pause:"Pause",prev_frame:"Previous frame",next_frame:"Next frame",inspector_prompt:"Prompt",inspector_model:"Model",inspector_in:"In",inspector_out:"Out",inspector_duration:"Duration",zoom_in:"Zoom in",zoom_out:"Zoom out",zoom:"Zoom",snap:"Snapping",shortcuts:"Keyboard shortcuts",sc_play:"Play / pause",sc_frame:"Previous / next frame",sc_second:"Back / forward 1 second",sc_split:"Split at playhead",sc_delete:"Delete clip",sc_undo:"Undo",sc_redo:"Redo",sc_in_out:"Set in / out to playhead",sc_zoom:"Zoom timeline",sc_move:"Move clip left / right",clip_aria:"Clip {n}: {start} â {end}",invalid_timecode:"Use MM:SS:FF",split_at_playhead:"Split at playhead",export_title:"Export video",export_resolution:"Resolution",export_res_source:"Original",export_duration:"Duration",export_start:"Export",export_cancel:"Cancel",export_progress:"Exporting⦠{pct}%",export_done:"Export complete",export_file_size:"File size",export_download:"Download",export_continue:"Keep editing",export_failed:"Export failed. Please try again.",export_retry:"Try again",export_too_long:"The timeline is longer than 2 minutes. Shorten it to export.",export_unsupported:"This browser can't export video. Use the latest Chrome or Edge.",export_no_audio_encoder:"This browser can't encode audio, so the video will be exported without sound.",export_no_audio:"None of the clips has audio, so the video will be silent.",export_mixed_aspect:"Clips with a different aspect ratio will be letterboxed.",export_keep_open:"Keep this tab open until the export finishes.",export_close:"Close",export_checking:"Checking browser supportâ¦",use_frame:"Use this frame as first frame",use_frame_uploading:"Uploading frameâ¦",use_frame_failed:"Couldn't upload the frame. Please try again.",new_project:"New project",autosave_local_removed:"Local files can't be restored after a reload and were removed from the project.",dismiss:"Dismiss"},$l={en:ql},jl={page_title:"Estudio de vÃdeo",studio_title:"Estudio",back:"Volver",undo:"Deshacer",redo:"Rehacer",export:"Exportar",media_title:"Medios",media_empty_title:"Aún no hay medios",media_empty_desc:"Abre versiones de una generación o añade un vÃdeo desde tu ordenador.",media_add_local:"Añadir vÃdeo local",viewer_empty:"La vista previa aparecerá aquÃ",inspector_title:"Clip",inspector_empty:"Selecciona un clip en la lÃnea de tiempo para ver sus detalles.",timeline_empty:"Arrastra medios aquà para empezar a editar.",split:"Dividir",delete:"Eliminar",unsupported_title:"Usa un ordenador",unsupported_desc:"El estudio necesita una pantalla de al menos 1024 px de ancho.",media_section_handoff:"Desde la generación",media_section_recent:"Generaciones recientes",media_section_local:"Archivos locales",media_add_to_timeline:"Añadir a la lÃnea de tiempo",media_probing:"Leyendo vÃdeoâ¦",media_unsupported_origin:"Esta fuente aún no se puede editar en el estudio.",media_unsupported_codec:"Este navegador no puede decodificar este vÃdeo.",media_error_network:"No se pudo cargar este vÃdeo.",media_too_large:"El archivo supera los 200 MB.",media_no_video:"No se encontró pista de vÃdeo.",media_remove:"Eliminar",media_download:"Descargar",recent_empty:"No hay vÃdeos recientes en este dispositivo.",play:"Reproducir",pause:"Pausa",prev_frame:"Fotograma anterior",next_frame:"Fotograma siguiente",inspector_prompt:"Prompt",inspector_model:"Modelo",inspector_in:"Entrada",inspector_out:"Salida",inspector_duration:"Duración",zoom_in:"Acercar",zoom_out:"Alejar",zoom:"Zoom",snap:"Ajuste",shortcuts:"Atajos de teclado",sc_play:"Reproducir / pausar",sc_frame:"Fotograma anterior / siguiente",sc_second:"Retroceder / avanzar 1 s",sc_split:"Dividir en el cursor",sc_delete:"Eliminar clip",sc_undo:"Deshacer",sc_redo:"Rehacer",sc_in_out:"Definir entrada / salida en el cursor",sc_zoom:"Zoom de la lÃnea de tiempo",sc_move:"Mover clip a la izquierda / derecha",clip_aria:"Clip {n}: {start} â {end}
151",invalid_timecode:"Usa MM:SS:FF",split_at_playhead:"Dividir en el cursor",export_title:"Exportar video",export_resolution:"Resolución",export_res_source:"Original",export_duration:"Duración",export_start:"Exportar",export_cancel:"Cancelar",export_progress:"Exportando⦠{pct}%",export_done:"Exportación completada",export_file_size:"Tamaño del archivo",export_download:"Descargar",export_continue:"Seguir editando",export_failed:"La exportación ha fallado. Inténtalo de nuevo.",export_retry:"Reintentar",export_too_long:"La lÃnea de tiempo supera los 2 minutos. Acórtala para exportar.",export_unsupported:"Este navegador no puede exportar video. Usa la última versión de Chrome o Edge.",export_no_audio_encoder:"Este navegador no puede codificar audio, por lo que el video se exportará sin sonido.",export_no_audio:"Ninguno de los clips tiene audio, asà que el video será mudo.",export_mixed_aspect:"Los clips con una proporción distinta se mostrarán con bandas negras.",export_keep_open:"No cierres esta pestaña hasta que finalice la exportación.",export_close:"Cerrar",export_checking:"Comprobando compatibilidad del navegadorâ¦",use_frame:"Usar este fotograma como primer fotograma",use_frame_uploading:"Subiendo fotogramaâ¦",use_frame_failed:"No se pudo subir el fotograma. Inténtalo de nuevo.",new_project:"Nuevo proyecto",autosave_local_removed:"Los archivos locales no se pueden restaurar tras recargar y se eliminaron del proyecto.",dismiss:"Descartar"},Kl={es:jl},Gl={page_title:"Studio vidéo",studio_title:"Studio",back:"Retour",undo:"Annuler",redo:"Rétablir",export:"Exporter",media_title:"Médias",media_empty_title:"Aucun média pour le moment",media_empty_desc:"Ouvrez des versions depuis une génération ou ajoutez une vidéo depuis votre ordinateur.",media_add_local:"Ajouter une vidéo locale",viewer_empty:"L'aperçu apparaîtra ici",inspector_title:"Clip",inspector_empty:"Sélectionnez un clip sur la timeline pour voir ses détails.",timeline_empty:"Glissez des médias ici pour commencer le montage.",split:"Diviser",delete:"Supprimer",unsupported_title:"Veuillez utiliser un ordinateur",unsupported_desc:"Le studio nécessite un écran d'au moins 1024 px de large.",media_section_handoff:"Depuis la génération",media_section_recent:"Générations récentes",media_section_local:"Fichiers locaux",media_add_to_timeline:"Ajouter à la timeline",media_probing:"Lecture de la vidéoâ¦",media_unsupported_origin:"Cette source ne peut pas encore être modifiée dans le studio.",media_unsupported_codec:"Ce navigateur ne peut pas décoder cette vidéo.",media_error_network:"Impossible de charger cette vidéo.",media_too_large:"Le fichier dépasse 200 Mo.",media_no_video:"Aucune piste vidéo trouvée.",media_remove:"Supprimer",media_download:"Télécharger",recent_empty:"Aucune vidéo récente sur cet appareil.",play:"Lire",pause:"Pause",prev_frame:"Image précédente",next_frame:"Image suivante",inspector_prompt:"Prompt",inspector_model:"Modèle",inspector_in:"Entrée",inspector_out:"Sortie",inspector_duration:"Durée",zoom_in:"Zoom avant",zoom_out:"Zoom arrière",zoom:"Zoom",snap:"Magnétisme",shortcuts:"Raccourcis clavier",sc_play:"Lecture / pause",sc_frame:"Image précédente / suivante",sc_second:"Recul / avance dâ1 s",sc_split:"Diviser à la tête de lecture",sc_delete:"Supprimer le clip",sc_undo:"Annuler",sc_redo:"Rétablir",sc_in_out:"Définir lâentrée / la sortie sur la tête de lecture",sc_zoom:"Zoomer la timeline",sc_move:"Déplacer le clip à gauche / droite",clip_aria:"Clip {n} : {start} â {end}",invalid_timecode:"Utilisez MM:SS:FF",split_at_playhead:"Diviser à la tête de lecture",export_title:"Exporter la vidéo",export_resolution:"Résolution",export_res_source:"Originale",export_duration:"Durée",export_start:"Exporter",export_cancel:"Annuler",export_progress:"Exportation⦠{pct} %",export_done:"Exportation terminée",export_file_size:"Taille du fichier",export_download:"Télécharger",exp
151ort_continue:"Continuer le montage",export_failed:"L'exportation a échoué. Veuillez réessayer.",export_retry:"Réessayer",export_too_long:"La timeline dépasse 2 minutes. Raccourcissez-la pour exporter.",export_unsupported:"Ce navigateur ne peut pas exporter de vidéo. Utilisez la dernière version de Chrome ou Edge.",export_no_audio_encoder:"Ce navigateur ne peut pas encoder l'audio, la vidéo sera donc exportée sans son.",export_no_audio:"Aucun des clips n'a de piste audio, la vidéo sera donc muette.",export_mixed_aspect:"Les clips dont le format diffère seront présentés avec des bandes noires.",export_keep_open:"Gardez cet onglet ouvert jusqu'à la fin de l'exportation.",export_close:"Fermer",export_checking:"Vérification de la compatibilité du navigateurâ¦",use_frame:"Utiliser cette image comme première frame",use_frame_uploading:"Envoi de l'imageâ¦",use_frame_failed:"Impossible d'envoyer l'image. Veuillez réessayer.",new_project:"Nouveau projet",autosave_local_removed:"Les fichiers locaux ne peuvent pas être restaurés après un rechargement et ont été retirés du projet.",dismiss:"Fermer"},Xl={fr:Gl},Ql={page_title:"ãããªã¹ã¿ã¸ãª",studio_title:"ã¹ã¿ã¸ãª",back:"æ»ã",undo:"å
ã«æ»ã",redo:"ããç´ã",export:"æ¸ãåºã",media_title:"ã¡ãã£ã¢",media_empty_title:"ã¡ãã£ã¢ã¯ã¾ã ããã¾ãã",media_empty_desc:"çæçµæãããã¼ã¸ã§ã³ãéãããã³ã³ãã¥ã¼ã¿ã¼ããåç»ã追å ãã¦ãã ããã",media_add_local:"ãã¼ã«ã«åç»ã追å ",viewer_empty:"ããã«ãã¬ãã¥ã¼ã表示ããã¾ã",inspector_title:"ã¯ãªãã",inspector_empty:"ã¿ã¤ã ã©ã¤ã³ã§ã¯ãªããã鏿ããã¨è©³ç´°ã表示ããã¾ãã",timeline_empty:"ããã«ã¡ãã£ã¢ããã©ãã°ãã¦ç·¨éãéå§ãã¾ãã",split:"åå²",delete:"åé¤",unsupported_title:"ãã½ã³ã³ã§ãå©ç¨ãã ãã",unsupported_desc:"ã¹ã¿ã¸ãªã«ã¯å¹
1024px 以ä¸ã®ç»é¢ãå¿
è¦ã§ãã",media_section_handoff:"çæãã",media_section_recent:"æè¿ã®çæ",media_section_local:"ãã¼ã«ã«ãã¡ã¤ã«",media_add_to_timeline:"ã¿ã¤ã ã©ã¤ã³ã«è¿½å ",media_probing:"åç»ãèªã¿è¾¼ã¿ä¸â¦",media_unsupported_origin:"ãã®ã½ã¼ã¹ã¯ã¾ã ã¹ã¿ã¸ãªã§ç·¨éã§ãã¾ããã",media_unsupported_codec:"ãã®ãã©ã¦ã¶ã¯ãã®åç»ããã³ã¼ãã§ãã¾ããã",media_error_network:"ãã®åç»ãèªã¿è¾¼ãã¾ããã§ããã",media_too_large:"ãã¡ã¤ã«ã 200 MB ãè¶
ãã¦ãã¾ãã",media_no_video:"åç»ãã©ãã¯ãè¦ã¤ããã¾ããã",media_remove:"åé¤",media_download:"ãã¦ã³ãã¼ã",recent_empty:"ãã®ããã¤ã¹ã«ã¯æè¿ã®åç»ãããã¾ããã",play:"åç",pause:"䏿忢",prev_frame:"åã®ãã¬ã¼ã ",next_frame:"次ã®ãã¬ã¼ã ",inspector_prompt:"ããã³ãã",inspector_model:"ã¢ãã«",inspector_in:"ã¤ã³",inspector_out:"ã¢ã¦ã",inspector_duration:"é·ã",zoom_in:"æ¡å¤§",zoom_out:"縮å°",zoom:"ãºã¼ã ",snap:"ã¹ããã",shortcuts:"ãã¼ãã¼ãã·ã§ã¼ãã«ãã",sc_play:"åç / 䏿忢",sc_frame:"å / 次ã®ãã¬ã¼ã ",sc_second:"1 ç§æ»ã / é²ã",sc_split:"åçãããã§åå²",sc_delete:"ã¯ãªãããåé¤",sc_undo:"åãæ¶ã",sc_redo:"ããç´ã",sc_in_out:"ã¤ã³ / ã¢ã¦ããåçãããã«è¨å®",sc_zoom:"ã¿ã¤ã ã©ã¤ã³ããºã¼ã ",sc_move:"ã¯ãªãããå·¦å³ã«ç§»å",clip_aria:"ã¯ãªãã {n}: {start} â {end}",invalid_timecode:"MM:SS:FF å½¢å¼ã§å
¥åãã¦ãã ãã",split_at_playhead:"åçãããã§åå²",export_title:"åç»ãã¨ã¯ã¹ãã¼ã",export_resolution:"è§£å度",export_res_source:"å
ã®ãµã¤ãº",export_duration:"é·ã",export_start:"ã¨ã¯ã¹ãã¼ã",export_cancel:"ãã£ã³ã»ã«",export_progress:"ã¨ã¯ã¹ãã¼ãä¸â¦ {pct}%",export_done:"ã¨ã¯ã¹ãã¼ããå®äºãã¾ãã",export_file_size:"ãã¡ã¤ã«ãµã¤ãº",export_download:"ãã¦ã³ãã¼ã",export_continue:"ç·¨éãç¶ãã",export_failed:"ã¨ã¯ã¹ãã¼ãã«å¤±æãã¾ãããããä¸åº¦ã試ããã ããã",export_retry:"å試
151è¡",export_too_long:"ã¿ã¤ã ã©ã¤ã³ã 2 åãè¶
ãã¦ãã¾ããçããã¦ããã¨ã¯ã¹ãã¼ããã¦ãã ããã",export_unsupported:"ãã®ãã©ã¦ã¶ã§ã¯åç»ãã¨ã¯ã¹ãã¼ãã§ãã¾ãããææ°ã® Chrome ã¾ã㯠Edge ããå©ç¨ãã ããã",export_no_audio_encoder:"ãã®ãã©ã¦ã¶ã§ã¯é³å£°ãã¨ã³ã³ã¼ãã§ããªããããé³å£°ãªãã§ã¨ã¯ã¹ãã¼ãããã¾ãã",export_no_audio:"ãã¹ã¦ã®ã¯ãªããã«é³å£°ããªããããç¡é³ã§ã¨ã¯ã¹ãã¼ãããã¾ãã",export_mixed_aspect:"ã¢ã¹ãã¯ãæ¯ã®ç°ãªãã¯ãªããã«ã¯é»å¸¯ãä»ãã¾ãã",export_keep_open:"ã¨ã¯ã¹ãã¼ããå®äºããã¾ã§ãã®ã¿ããéããªãã§ãã ããã",export_close:"éãã",export_checking:"ãã©ã¦ã¶ã®å¯¾å¿ç¶æ³ã確èªä¸â¦",use_frame:"ãã®ãã¬ã¼ã ãæåã®ãã¬ã¼ã ã¨ãã¦ä½¿ç¨",use_frame_uploading:"ãã¬ã¼ã ãã¢ãããã¼ãä¸â¦",use_frame_failed:"ãã¬ã¼ã ãã¢ãããã¼ãã§ãã¾ããã§ãããããä¸åº¦ã試ããã ããã",new_project:"æ°è¦ããã¸ã§ã¯ã",autosave_local_removed:"ãã¼ã«ã«ãã¡ã¤ã«ã¯åèªã¿è¾¼ã¿å¾ã«å¾©å
ã§ããªããããããã¸ã§ã¯ãããåé¤ããã¾ããã",dismiss:"éãã"},Yl={ja:Ql},Zl={page_title:"ë¹ëì¤ ì¤íëì¤",studio_title:"ì¤íëì¤",back:"ë¤ë¡",undo:"ì¤í ì·¨ì",redo:"ë¤ì ì¤í",export:"ë³´ë´ê¸°",media_title:"미ëì´",media_empty_title:"ìì§ ë¯¸ëì´ê° ììµëë¤",media_empty_desc:"ìì± ê²°ê³¼ìì ë²ì ì ì´ê±°ë ì»´í¨í°ìì ëììì ì¶ê°íì¸ì.",media_add_local:"ë¡ì»¬ ëìì ì¶ê°",viewer_empty:"ì¬ê¸°ì ë¯¸ë¦¬ë³´ê¸°ê° íìë©ëë¤",inspector_title:"í´ë¦½",inspector_empty:"íìë¼ì¸ìì í´ë¦½ì ì ííë©´ ìì¸ ì ë³´ê° íìë©ëë¤.",timeline_empty:"ì¬ê¸°ë¡ 미ëì´ë¥¼ ëëê·¸íì¬ í¸ì§ì ììíì¸ì.",split:"ë¶í ",delete:"ìì ",unsupported_title:"ì»´í¨í°ìì ì¬ì©í´ 주ì¸ì",unsupported_desc:"ì¤íëì¤ìë ëë¹ê° 1024px ì´ìì¸ íë©´ì´ íìí©ëë¤.",media_section_handoff:"ìì± ê²°ê³¼ìì",media_section_recent:"ìµê·¼ ìì±",media_section_local:"ë¡ì»¬ íì¼",media_add_to_timeline:"íìë¼ì¸ì ì¶ê°",media_probing:"ëìì ì½ë ì¤â¦",media_unsupported_origin:"ì´ ìì¤ë ìì§ ì¤íëì¤ìì í¸ì§í ì ììµëë¤.",media_unsupported_codec:"ì´ ë¸ë¼ì°ì ë ì´ ëììì ëì½ë©í ì ììµëë¤.",media_error_network:"ì´ ëììì ë¶ë¬ì¤ì§ 못íìµëë¤.",media_too_large:"íì¼ì´ 200MB를 ì´ê³¼í©ëë¤.",media_no_video:"ë¹ëì¤ í¸ëì ì°¾ì ì ììµëë¤.",media_remove:"ìì ",media_download:"ë¤ì´ë¡ë",recent_empty:"ì´ ê¸°ê¸°ì ìµê·¼ ëììì´ ììµëë¤.",play:"ì¬ì",pause:"ì¼ì ì ì§",prev_frame:"ì´ì íë ì",next_frame:"ë¤ì íë ì",inspector_prompt:"í롬íí¸",inspector_model:"모ë¸",inspector_in:"ì¸",inspector_out:"ìì",inspector_duration:"길ì´",zoom_in:"íë",zoom_out:"ì¶ì",zoom:"ì¤",snap:"ì¤ë
",shortcuts:"í¤ë³´ë ë¨ì¶í¤",sc_play:"ì¬ì / ì¼ì ì ì§",sc_frame:"ì´ì / ë¤ì íë ì",sc_second:"1ì´ ë¤ë¡ / ìì¼ë¡",sc_split:"ì¬ì í¤ëìì ë¶í ",sc_delete:"í´ë¦½ ìì ",sc_undo:"ì¤í ì·¨ì",sc_redo:"ë¤ì ì¤í",sc_in_out:"ì¸ / ììì ì¬ì í¤ëë¡ ì¤ì ",sc_zoom:"íìë¼ì¸ íë / ì¶ì",sc_move:"í´ë¦½ì ì¢ì°ë¡ ì´ë",clip_aria:"í´ë¦½ {n}: {start} â {end}",invalid_timecode:"MM:SS:FF íìì ì¬ì©íì¸ì",split_at_playhead:"ì¬ì í¤ëìì ë¶í ",export_title:"ëììë³´ë´ê¸°",export_resolution:"í´ìë",export_res_source:"ì본",export_duration:"길ì´",export_start:"ë³´ë´ê¸°",export_cancel:"ì·¨ì",export_progress:"ë³´ë´ë ì¤â¦ {pct}%",export_done:"ë³´ë´ê¸° ìë£",export_file_size:"íì¼ í¬ê¸°",export_download:"ë¤ì´ë¡ë",export_continue:"ê³ì í¸ì§",export_failed:"ë³´ë´ê¸°ì ì¤í¨íìµëë¤. ë¤ì ìëí´ ì£¼ì¸ì.",export_retry:"ë¤ì ìë",export_too_long:"íìë¼ì¸ì´ 2ë¶ì ì´ê³¼í©ëë¤. ì¤ì¸ íë³´ë´ì¸ì.",export_unsupported:"ì´ ë¸ë¼ì°ì ììë ëìììë³´ë¼ ì ììµëë¤. ìµì Chrome ëë Edge를 ì¬ì©íì¸ì.",export_no_audio_encoder:"ì´ ë¸ë¼ì°ì ììë ì
151¤ëì¤ë¥¼ ì¸ì½ë©í ì ìì´ ì리 ìì´ë³´ë´ì§ëë¤.",export_no_audio:"모ë í´ë¦½ì ì¤ëì¤ê° ìì´ ììì´ ë¬´ìì¼ë¡ë³´ë´ì§ëë¤.",export_mixed_aspect:"íë©´ ë¹ì¨ì´ ë¤ë¥¸ í´ë¦½ìë ë í°ë°ì¤ê° ì ì©ë©ëë¤.",export_keep_open:"ë³´ë´ê¸°ê° ëë ëê¹ì§ ì´ íì ë«ì§ ë§ì¸ì.",export_close:"ë«ê¸°",export_checking:"ë¸ë¼ì°ì ì§ì íì¸ ì¤â¦",use_frame:"ì´ íë ìì 첫 íë ìì¼ë¡ ì¬ì©",use_frame_uploading:"íë ì ì
ë¡ë ì¤â¦",use_frame_failed:"íë ìì ì
ë¡ëí ì ììµëë¤. ë¤ì ìëí´ ì£¼ì¸ì.",new_project:"ì íë¡ì í¸",autosave_local_removed:"ë¡ì»¬ íì¼ì ìë¡ê³ 침 í ë³µìí ì ìì´ íë¡ì í¸ìì ì ê±°ëììµëë¤.",dismiss:"ë«ê¸°"},Jl={ko:Zl},eu={page_title:"Estúdio de vÃdeo",studio_title:"Estúdio",back:"Voltar",undo:"Desfazer",redo:"Refazer",export:"Exportar",media_title:"MÃdia",media_empty_title:"Ainda não há mÃdia",media_empty_desc:"Abra versões de uma geração ou adicione um vÃdeo do seu computador.",media_add_local:"Adicionar vÃdeo local",viewer_empty:"A pré-visualização aparecerá aqui",inspector_title:"Clipe",inspector_empty:"Selecione um clipe na linha do tempo para ver os detalhes.",timeline_empty:"Arraste mÃdia aqui para começar a editar.",split:"Dividir",delete:"Excluir",unsupported_title:"Use um computador",unsupported_desc:"O estúdio precisa de uma tela com pelo menos 1024 px de largura.",media_section_handoff:"Da geração",media_section_recent:"Gerações recentes",media_section_local:"Ficheiros locais",media_add_to_timeline:"Adicionar à timeline",media_probing:"A ler vÃdeoâ¦",media_unsupported_origin:"Esta fonte ainda não pode ser editada no estúdio.",media_unsupported_codec:"Este navegador não consegue descodificar este vÃdeo.",media_error_network:"Não foi possÃvel carregar este vÃdeo.",media_too_large:"O ficheiro excede 200 MB.",media_no_video:"Nenhuma faixa de vÃdeo encontrada.",media_remove:"Remover",media_download:"Transferir",recent_empty:"Sem vÃdeos recentes neste dispositivo.",play:"Reproduzir",pause:"Pausa",prev_frame:"Fotograma anterior",next_frame:"Fotograma seguinte",inspector_prompt:"Prompt",inspector_model:"Modelo",inspector_in:"Entrada",inspector_out:"SaÃda",inspector_duration:"Duração",zoom_in:"Ampliar",zoom_out:"Reduzir",zoom:"Zoom",snap:"Encaixe",shortcuts:"Atalhos de teclado",sc_play:"Reproduzir / pausar",sc_frame:"Quadro anterior / seguinte",sc_second:"Voltar / avançar 1 s",sc_split:"Dividir no cursor",sc_delete:"Eliminar clipe",sc_undo:"Anular",sc_redo:"Refazer",sc_in_out:"Definir entrada / saÃda no cursor",sc_zoom:"Zoom da linha do tempo",sc_move:"Mover clipe para a esquerda / direita",clip_aria:"Clipe {n}: {start} â {end}",invalid_timecode:"Use MM:SS:FF",split_at_playhead:"Dividir no cursor",export_title:"Exportar vÃdeo",export_resolution:"Resolução",export_res_source:"Original",export_duration:"Duração",export_start:"Exportar",export_cancel:"Cancelar",export_progress:"Exportando⦠{pct}%",export_done:"Exportação concluÃda",export_file_size:"Tamanho do arquivo",export_download:"Baixar",export_continue:"Continuar editando",export_failed:"A exportação falhou. Tente novamente.",exp
151ort_retry:"Tentar novamente",export_too_long:"A linha do tempo tem mais de 2 minutos. Encurte-a para exportar.",export_unsupported:"Este navegador não pode exportar vÃdeo. Use o Chrome ou Edge mais recente.",export_no_audio_encoder:"Este navegador não pode codificar áudio, então o vÃdeo será exportado sem som.",export_no_audio:"Nenhum dos clipes tem áudio, portanto o vÃdeo ficará sem som.",export_mixed_aspect:"Clipes com proporção diferente serão exibidos com faixas pretas.",export_keep_open:"Mantenha esta aba aberta até a exportação terminar.",export_close:"Fechar",export_checking:"Verificando suporte do navegadorâ¦",use_frame:"Usar este quadro como primeiro quadro",use_frame_uploading:"Enviando quadroâ¦",use_frame_failed:"Não foi possÃvel enviar o quadro. Tente novamente.",new_project:"Novo projeto",autosave_local_removed:"Os ficheiros locais não podem ser restaurados após recarregar e foram removidos do projeto.",dismiss:"Dispensar"},tu={pt:eu},ru={page_title:"ÐидеоÑÑÑдиÑ",studio_title:"СÑÑдиÑ",back:"Ðазад",undo:"ÐÑмениÑÑ",redo:"ÐовÑоÑиÑÑ",export:"ÐкÑпоÑÑ",media_title:"Ðедиа",media_empty_title:"Ðока Ð½ÐµÑ Ð¼ÐµÐ´Ð¸Ð°",media_empty_desc:"ÐÑкÑойÑе веÑÑии из генеÑаÑии или добавÑÑе видео Ñ ÐºÐ¾Ð¼Ð¿ÑÑÑеÑа.",media_add_local:"ÐобавиÑÑ Ð²Ð¸Ð´ÐµÐ¾ Ñ ÐºÐ¾Ð¼Ð¿ÑÑÑеÑа",viewer_empty:"ÐдеÑÑ Ð¿Ð¾ÑвиÑÑÑ Ð¿ÑедпÑоÑмоÑÑ",inspector_title:"Ðлип",inspector_empty:"ÐÑбеÑиÑе клип на Ñаймлинии, ÑÑÐ¾Ð±Ñ ÑвидеÑÑ ÐµÐ³Ð¾ деÑали.",timeline_empty:"ÐеÑеÑаÑиÑе медиа ÑÑда, ÑÑÐ¾Ð±Ñ Ð½Ð°ÑаÑÑ Ð¼Ð¾Ð½Ñаж.",split:"РазделиÑÑ",delete:"УдалиÑÑ",unsupported_title:"ÐожалÑйÑÑа, иÑполÑзÑйÑе компÑÑÑеÑ",unsupported_desc:"СÑÑдии нÑжен ÑкÑан ÑиÑиной не менее 1024 пикÑелей.",media_section_handoff:"Ðз генеÑаÑии",media_section_recent:"Ðедавние генеÑаÑии",media_section_local:"ÐокалÑнÑе ÑайлÑ",media_add_to_timeline:"ÐобавиÑÑ Ð½Ð° Ñаймлайн",media_probing:"ЧÑение видеоâ¦",media_unsupported_origin:"ÐÑÐ¾Ñ Ð¸ÑÑоÑник пока нелÑÐ·Ñ ÑедакÑиÑоваÑÑ Ð² ÑÑÑдии.",media_unsupported_codec:"ÐÑаÑÐ·ÐµÑ Ð½Ðµ Ð¼Ð¾Ð¶ÐµÑ Ð´ÐµÐºÐ¾Ð´Ð¸ÑоваÑÑ ÑÑо видео.",media_error_network:"Ðе ÑдалоÑÑ Ð·Ð°Ð³ÑÑзиÑÑ Ð²Ð¸Ð´ÐµÐ¾.",media_too_large:"Файл болÑÑе 200 ÐÐ.",media_no_video:"ÐидеодоÑожка не найдена.",media_remove:"УдалиÑÑ",media_download:"СкаÑаÑÑ",recent_empty:"Ðа ÑÑом ÑÑÑÑойÑÑве Ð½ÐµÑ Ð½ÐµÐ´Ð°Ð²Ð½Ð¸Ñ
видео.",play:"ÐоÑпÑоизвеÑÑи",pause:"ÐаÑза",prev_frame:"ÐÑедÑдÑÑий кадÑ",next_frame:"СледÑÑÑий кадÑ",inspector_prompt:"ÐÑомпÑ",inspector_model:"ÐоделÑ",inspector_in:"ÐÑ
од",inspector_out:"ÐÑÑ
од",inspector_duration:"ÐлиÑелÑноÑÑÑ",zoom_in:"УвелиÑиÑÑ",zoom_out:"УменÑÑиÑÑ",zoom:"ÐаÑÑÑаб",snap:"ÐÑивÑзка",shortcuts:"ÐоÑÑÑие клавиÑи",sc_play:"ÐоÑпÑоизведение / паÑза",sc_frame:"ÐÑедÑдÑÑий / ÑледÑÑÑий кадÑ",sc_second:"Ðазад / впеÑÑд на 1 Ñ",sc_split:"РазделиÑÑ Ð½Ð° ÑказаÑеле",sc_delete:"УдалиÑÑ ÐºÐ»Ð¸Ð¿",sc_undo:"ÐÑмениÑÑ",sc_redo:"ÐовÑоÑиÑÑ",sc_in_out:"УÑÑановиÑÑ Ð²Ñ
од / вÑÑ
од по ÑказаÑелÑ",sc_zoom:"ÐаÑÑÑабиÑоваÑÑ Ñаймлайн",sc_move:"ÐеÑемеÑÑиÑÑ ÐºÐ»Ð¸Ð¿ влево / впÑаво",clip_aria:"Ðлип {n}: {start} â {end}",invalid_timecode:"ФоÑмаÑ: ÐÐ:СС:ÐÐ",split_at_playhead:"РазделиÑÑ Ð½Ð° ÑказаÑеле",export_title:"ÐкÑпоÑÑ Ð²Ð¸Ð´ÐµÐ¾",export_resolution:"РазÑеÑение",export_res_source:"ÐÑигинал",export_duration:"ÐлиÑелÑноÑÑÑ",export_start:"ÐкÑпоÑÑ",export_cancel:"ÐÑмена",export_progress:"ÐкÑпоÑÑ⦠{pct}%",export_done:"ÐкÑпоÑÑ Ð·Ð°Ð²ÐµÑÑÑн",export_file_size:"Ð Ð°Ð·Ð¼ÐµÑ Ñайла",export_download:"СкаÑаÑÑ",export_continue:"ÐÑодолжиÑÑ ÑедакÑиÑование",export_failed:"ÐкÑпоÑÑ Ð½Ðµ ÑдалÑÑ. ÐопÑобÑйÑе еÑÑ Ñаз.",export_retry:"ÐовÑоÑиÑÑ",export_too_long:"ÐлиÑелÑноÑÑÑ Ð²Ñеменной ÑÐºÐ°Ð»Ñ Ð¿ÑевÑÑÐ°ÐµÑ 2 минÑÑÑ. СокÑаÑиÑе ÐµÑ Ð´Ð»Ñ ÑкÑпоÑÑа.",export_unsupported:"ÐÑÐ¾Ñ Ð±ÑаÑÐ·ÐµÑ Ð½Ðµ Ð¼Ð¾Ð¶ÐµÑ ÑкÑпоÑÑиÑоваÑÑ Ð²Ð¸Ð´ÐµÐ¾. ÐÑполÑзÑйÑе поÑледнÑÑ Ð²ÐµÑÑÐ¸Ñ Chrome или Edge.",exp
151ort_no_audio_encoder:"ÐÑÐ¾Ñ Ð±ÑаÑÐ·ÐµÑ Ð½Ðµ Ð¼Ð¾Ð¶ÐµÑ ÐºÐ¾Ð´Ð¸ÑоваÑÑ Ð°Ñдио, поÑÑÐ¾Ð¼Ñ Ð²Ð¸Ð´ÐµÐ¾ бÑÐ´ÐµÑ ÑкÑпоÑÑиÑовано без звÑка.",export_no_audio:"Ðи в одном из ÑÑагменÑов Ð½ÐµÑ Ð·Ð²Ñка, поÑÑÐ¾Ð¼Ñ Ð²Ð¸Ð´ÐµÐ¾ бÑÐ´ÐµÑ Ð±ÐµÐ·Ð·Ð²ÑÑнÑм.",export_mixed_aspect:"ФÑагменÑÑ Ñ Ð´ÑÑгим ÑооÑноÑением ÑÑоÑон бÑдÑÑ Ð¿Ð¾ÐºÐ°Ð·Ð°Ð½Ñ Ñ ÑÑÑнÑми полоÑами.",export_keep_open:"Ðе закÑÑвайÑе ÑÑÑ Ð²ÐºÐ»Ð°Ð´ÐºÑ Ð´Ð¾ завеÑÑÐµÐ½Ð¸Ñ ÑкÑпоÑÑа.",export_close:"ÐакÑÑÑÑ",export_checking:"ÐÑовеÑка поддеÑжки бÑаÑзеÑомâ¦",use_frame:"ÐÑполÑзоваÑÑ ÑÑÐ¾Ñ ÐºÐ°Ð´Ñ ÐºÐ°Ðº пеÑвÑй",use_frame_uploading:"ÐагÑÑзка кадÑаâ¦",use_frame_failed:"Ðе ÑдалоÑÑ Ð·Ð°Ð³ÑÑзиÑÑ ÐºÐ°Ð´Ñ. ÐовÑоÑиÑе попÑÑкÑ.",new_project:"ÐовÑй пÑоекÑ",autosave_local_removed:"ÐокалÑнÑе ÑÐ°Ð¹Ð»Ñ Ð½ÐµÐ»ÑÐ·Ñ Ð²Ð¾ÑÑÑановиÑÑ Ð¿Ð¾Ñле пеÑезагÑÑзки â они ÑÐ´Ð°Ð»ÐµÐ½Ñ Ð¸Ð· пÑоекÑа.",dismiss:"СкÑÑÑÑ"},iu={ru},nu={page_title:"Video Stüdyosu",studio_title:"Stüdyo",back:"Geri",undo:"Geri al",redo:"Yinele",export:"DıÅa aktar",media_title:"Medya",media_empty_title:"Henüz medya yok",media_empty_desc:"Bir oluÅturma iÅleminden sürümleri açın veya bilgisayarınızdan bir video ekleyin.",media_add_local:"Yerel video ekle",viewer_empty:"Ãnizleme burada görünecek",inspector_title:"Klip",inspector_empty:"Ayrıntılarını görmek için zaman çizelgesinde bir klip seçin.",timeline_empty:"Düzenlemeye baÅlamak için medyayı buraya sürükleyin.",split:"Böl",delete:"Sil",unsupported_title:"Lütfen bir bilgisayar kullanın",unsupported_desc:"Stüdyo en az 1024 piksel geniÅliÄinde bir ekran gerektirir.",media_section_handoff:"OluÅturmadan",media_section_recent:"Son oluÅturmalar",media_section_local:"Yerel dosyalar",media_add_to_timeline:"Zaman çizelgesine ekle",media_probing:"Video okunuyorâ¦",media_unsupported_origin:"Bu kaynak henüz stüdyoda düzenlenemiyor.",media_unsupported_codec:"Bu tarayıcı bu videoyu çözemiyor.",media_error_network:"Bu video yüklenemedi.",media_too_large:"Dosya 200 MB'tan büyük.",media_no_video:"Video parçası bulunamadı.",media_remove:"Kaldır",media_download:"İndir",recent_empty:"Bu cihazda son oluÅturulan video yok.",play:"Oynat",pause:"Duraklat",prev_frame:"Ãnceki kare",next_frame:"Sonraki kare",inspector_prompt:"İstem",inspector_model:"Model",inspector_in:"GiriÅ",inspector_out:"ÃıkıÅ",inspector_duration:"Süre",zoom_in:"YakınlaÅtır",zoom_out:"UzaklaÅtır",zoom:"YakınlaÅtırma",snap:"YapıÅma",shortcuts:"Klavye kısayolları",sc_play:"Oynat / duraklat",sc_frame:"Ãnceki / sonraki kare",sc_second:"1 sn geri / ileri",sc_split:"Oynatma çubuÄunda böl",sc_delete:"Klibi sil",sc_undo:"Geri al",sc_redo:"Yinele",sc_in_out:"GiriÅ / çıkıÅı imlece ayarla",sc_zoom:"Zaman çizelgesini yakınlaÅtır",sc_move:"Klibi sola / saÄa taÅı",clip_aria:"Klip {n}: {start} â {end}",invalid_timecode:"MM:SS:FF kullanın",split_at_playhead:"Oynatma çubuÄunda böl",export_title:"Videoyu dıÅa aktar",export_resolution:"Ãözünürlük",export_res_source:"Orijinal",export_duration:"Süre",export_start:"DıÅa aktar",export_cancel:"İptal",export_progress:"DıÅa aktarılıyor⦠%{pct}",export_done:"DıÅa aktarma tamamlandı",export_file_size:"Dosya boyutu",export_download:"İndir",export_continue:"Düzenlemeye devam et",export_failed:"DıÅa aktarma baÅarısız oldu. Lütfen tekrar deneyin.",export_retry:"Tekrar dene",export_too_long:"Zaman çizelgesi 2 dakikadan uzun. DıÅa aktarmak için kısaltın.",export_unsupported:"Bu tarayıcı video dıÅa aktaramıyor. En güncel Chrome veya Edge kullanın.",export_no_audio_encoder:"Bu tarayıcı ses kodlayamıyor, bu nedenle video sessiz dıÅa aktarılacak.",export_no_audio:"Kliplerin hiçbirinde ses yok, bu nedenle video sessiz olacak.",export_mixed_aspect:"Farklı en-boy oranına sahip klipler siyah bantlarla gösterilir.",exp
151ort_keep_open:"DıÅa aktarma bitene kadar bu sekmeyi kapatmayın.",export_close:"Kapat",export_checking:"Tarayıcı desteÄi kontrol ediliyorâ¦",use_frame:"Bu kareyi ilk kare olarak kullan",use_frame_uploading:"Kare yükleniyorâ¦",use_frame_failed:"Kare yüklenemedi. Lütfen tekrar deneyin.",new_project:"Yeni proje",autosave_local_removed:"Yerel dosyalar yeniden yükleme sonrası geri getirilemez ve projeden kaldırıldı.",dismiss:"Kapat"},su={tr:nu},au={page_title:"è§é¢åªè¾å°",studio_title:"åªè¾å°",back:"è¿å",undo:"æ¤é",redo:"éå",export:"导åº",media_title:"ç´ æ",media_empty_title:"è¿æ²¡æç´ æ",media_empty_desc:"ä»çæç»ææå¼çæ¬ï¼ææ·»å æ¬å°è§é¢ã",media_add_local:"æ·»å æ¬å°è§é¢",viewer_empty:"é¢è§å°æ¾ç¤ºå¨è¿é",inspector_title:"çæ®µ",inspector_empty:"卿¶é´è½´ä¸éæ©ä¸ä¸ªç段æ¥ç详æ
ã",timeline_empty:"æç´ ææå°è¿éå¼å§åªè¾ã",split:"åå²",delete:"å é¤",unsupported_title:"请å¨çµèä¸ä½¿ç¨åªè¾å°",unsupported_desc:"åªè¾å°éè¦è³å° 1024px 宽çå±å¹ã",media_section_handoff:"æ¬æ¬¡å¸¦å
¥",media_section_recent:"æè¿çæ",media_section_local:"æ¬å°æä»¶",media_add_to_timeline:"æ·»å å°æ¶é´è½´",media_probing:"æ£å¨è¯»åè§é¢â¦",media_unsupported_origin:"è¯¥æ¥æºæä¸æ¯æå¨åªè¾å°ä¸ç¼è¾ã",media_unsupported_codec:"å½åæµè§å¨æ æ³è§£ç 该è§é¢ã",media_error_network:"æ æ³å 载该è§é¢ã",media_too_large:"æä»¶è¶
è¿ 200 MBã",media_no_video:"æªæ¾å°è§é¢è½¨éã",media_remove:"ç§»é¤",media_download:"ä¸è½½",recent_empty:"æ¤è®¾å¤ä¸è¿æ²¡ææè¿çæçè§é¢ã",play:"ææ¾",pause:"æå",prev_frame:"ä¸ä¸å¸§",next_frame:"ä¸ä¸å¸§",inspector_prompt:"æç¤ºè¯",inspector_model:"模å",inspector_in:"å
¥ç¹",inspector_out:"åºç¹",inspector_duration:"æ¶é¿",zoom_in:"æ¾å¤§",zoom_out:"缩å°",zoom:"缩æ¾",snap:"å¸é",shortcuts:"å¿«æ·é®",sc_play:"ææ¾ / æå",sc_frame:"ä¸ä¸å¸§ / ä¸ä¸å¸§",sc_second:"åé / åè¿ 1 ç§",sc_split:"卿æ¾å¤´å¤åå²",sc_delete:"å é¤ç段",sc_undo:"æ¤é",sc_redo:"éå",sc_in_out:"æå
¥ç¹ / åºç¹è®¾å°ææ¾å¤´",sc_zoom:"ç¼©æ¾æ¶é´è½´",sc_move:"å·¦å³ç§»å¨ç段",clip_aria:"çæ®µ {n}ï¼{start} â {end}",invalid_timecode:"æ ¼å¼åºä¸º å:ç§:帧",split_at_playhead:"卿æ¾å¤´å¤åå²",export_title:"导åºè§é¢",export_resolution:"å辨ç",export_res_source:"åå§",export_duration:"æ¶é¿",export_start:"å¼å§å¯¼åº",export_cancel:"åæ¶",export_progress:"æ£å¨å¯¼åºâ¦ {pct}%",export_done:"导åºå®æ",export_file_size:"æä»¶å¤§å°",export_download:"ä¸è½½",export_continue:"ç»§ç»ç¼è¾",export_failed:"导åºå¤±è´¥ï¼è¯·éè¯ã",export_retry:"éè¯",export_too_long:"æ¶é´è½´è¶
è¿ 2 åéï¼è¯·ç¼©çåå导åºã",export_unsupported:"å½åæµè§å¨æ æ³å¯¼åºè§é¢ï¼è¯·ä½¿ç¨ææ°ç Chrome æ Edgeã",export_no_audio_encoder:"å½åæµè§å¨æ æ³ç¼ç é³é¢ï¼å¯¼åºçè§é¢å°æ²¡æå£°é³ã",export_no_audio:"ææçæ®µé½æ²¡æé³è½¨ï¼å¯¼åºçè§é¢æ²¡æå£°é³ã",export_mixed_aspect:"æ¯ä¾ä¸åççæ®µä¼å é»è¾¹ã",export_keep_open:"导åºå®æå请ä¸è¦å
³éæ¤é¡µé¢ã",export_close:"å
³é",export_checking:"æ£å¨æ£æ¥æµè§å¨æ¯æâ¦",use_frame:"ç¨å½å帧ä½ä¸ºé¦å¸§",use_frame_uploading:"æ£å¨ä¸ä¼ ç»é¢â¦",use_frame_failed:"ç»é¢ä¸ä¼ 失败ï¼è¯·éè¯ã",new_project:"æ°å»ºé¡¹ç®",autosave_local_removed:"æ¬å°æä»¶å¨å·æ°åæ æ³æ¢å¤ï¼å·²ä»é¡¹ç®ä¸ç§»é¤ã",dismiss:"å
³é"},ou={zh:au},cu={en:$l,zh:ou,ru:iu,de:Hl,fr:Xl,ja:Yl,ko:Jl,es:Kl,pt:tu,tr:su};function Rr(){return sl({useScope:"local",messages:Object.fromEntries(Object.entries(cu).map(([r,e])=>[r,e[r]]))})}const lu={class:"flex h-full min-h-0 flex-1 flex-col items-center justify-center bg-white px-6 text-center dark:bg-zinc-950"},uu={class:"mt-2 text-[13px] font-medium text-zinc-900 dark:text-zinc-100"},du={class:"mt-1 text-xs text-zinc-500 dark:text-zinc-400"},fu=Fr({__name:"StudioUnsupported",setup(r){const{t:e}=Rr();return(t,i)=>(Z(),re("div",lu,[be(w(El),{class:"h-5 w-5 text-zinc-400"}),L("p",uu,Y(w(e)("unsupported_title")),1),L("p",du,Y(w(e)("unsupported_desc")),1
151)]))}});function Zr(r){return 1/r}function xi(r,e){return Number.isFinite(r)?Math.max(0,Math.round(r*e)/e):0}function As(r,e){return Number.isFinite(r)?Math.max(0,Math.floor(r*e)/e):0}function st(r,e){const t=Math.max(0,Math.round(r*e)),i=t%e,n=Math.floor(t/e),s=n%60,a=Math.floor(n/60)%60,o=Math.floor(n/3600),c=u=>String(u).padStart(2,"0"),l=`${c(a)}:${c(s)}:${c(i)}`;return o>0?`${o}:${l}`:l}function aa(r,e){if(!Number.isFinite(e)||e<=0)return null;const t=r.trim().split(":");if(t.length!==3&&t.length!==4||t.some(c=>!/^\d{1,2}$/.test(c)))return null;const i=t.map(Number),[n,s,a,o]=t.length===4?i:[0,...i];return a>=60||o>=e||t.length===4&&s>=60?null:n*3600+s*60+a+o/e}const ls="application/x-studio-source",hu=["draggable"],mu={class:"h-6 w-10 flex-shrink-0 overflow-hidden rounded-md bg-zinc-200 dark:bg-zinc-800"},pu=["src"],gu={key:1,class:"h-full w-full animate-pulse bg-zinc-200 motion-reduce:animate-none dark:bg-zinc-800"},bu={key:2,class:"flex h-full w-full items-center justify-center"},ku={class:"min-w-0 flex-1"},yu={class:"truncate text-[12.5px] font-medium leading-4 text-zinc-900 dark:text-zinc-100"},wu={key:0,class:"text-[11px] tabular-nums leading-4 text-zinc-500 dark:text-zinc-400"},xu={key:1,class:"text-[11px] leading-4 text-zinc-500 dark:text-zinc-400"},Tu={key:2,class:"text-[11px] leading-4 text-amber-700 dark:text-amber-300"},_u=["href"],Su=["aria-label"],vu=["aria-label"],Pu=Fr({__name:"StudioMediaRow",props:{source:{},poster:{},loading:{type:Boolean},removable:{type:Boolean}},emits:["add","remove"],setup(r,{emit:e}){const t=r,i=e;function n(c){t.source.status!=="ready"||!c.dataTransfer||(c.dataTransfer.setData(ls,t.source.id),c.dataTransfer.effectAllowed="copy")}const{t:s}=Rr(),a=pe(()=>{switch(t.source.error){case"origin":return s("media_unsupported_origin");case"not_decodable":return s("media_unsupported_codec");case"too_large":return s("media_too_large");case"no_video_track":return s("media_no_video");case"network":return s("media_error_network");default:return s("media_unsupported_codec")}}),o=pe(()=>t.source.originalUrl||t.source.url);return(c,l)=>(Z(),re("div",{class:"group flex min-h-10 items-center gap-2 rounded-md px-2 py-1.5 transition-colors duration-150 hover:bg-zinc-100 motion-reduce:transition-none dark:hover:bg-white/[0.06]",draggable:r.source.status==="ready",onDragstart:n},[L("div",mu,[r.poster?(Z(),re("img",{key:0,src:r.poster,alt:"",class:"h-full w-full object-cover"},null,8,pu)):r.loading||r.source.status==="probing"?(Z(),re("div",gu)):(Z(),re("div",bu,[be(w(ko),{class:"h-3.5 w-3.5 text-zinc-400"})]))]),L("div",ku,[L("p",yu,Y(r.source.label),1),r.source.status==="ready"?(Z(),re("p",wu,Y(w(st)(r.source.duration,30)),1)):r.source.status==="probing"?(Z(),re("p",xu,Y(w(s)("media_probing")),1)):(Z(),re("p",Tu,[$e(Y(w(a))+" ",1),r.source.error==="origin"&&w(o)?(Z(),re("a",{key:0,href:w(o),download:"",class:"ml-1 text-zinc-500 underline decoration-zinc-300 underline-offset-2 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100",onClick:l[0]||(l[0]=nt(()=>{},["stop"]))}
151,Y(w(s)("media_download")),9,_u)):Ce("",!0)]))]),r.source.status==="ready"?(Z(),re("button",{key:0,type:"button","aria-label":w(s)("media_add_to_timeline"),class:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center self-center rounded-md text-zinc-500 transition-colors duration-150 hover:bg-zinc-200 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:hover:bg-white/[0.08] dark:hover:text-zinc-100",onClick:l[1]||(l[1]=nt(u=>i("add",r.source.id),["stop"]))},[be(w(Fl),{class:"h-3.5 w-3.5"})],8,Su)):Ce("",!0),r.removable?(Z(),re("button",{key:1,type:"button","aria-label":w(s)("media_remove"),class:"invisible inline-flex h-6 w-6 flex-shrink-0 items-center justify-center self-center rounded-md text-zinc-400 transition-colors duration-150 hover:bg-zinc-200 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 group-hover:visible group-focus-within:visible motion-reduce:transition-none dark:hover:bg-white/[0.08] dark:hover:text-zinc-100",onClick:l[2]||(l[2]=nt(u=>i("remove",r.source.id),["stop"]))},[be(w(fn),{class:"h-3.5 w-3.5"})],8,vu)):Ce("",!0)],40,hu))}}),wo=()=>`clip-${Math.random().toString(36).slice(2,10)}`,us=1e-9;function ft(r){return r.out-r.in}function Zt(r){const e=[];let t=0;for(const i of r.clips)e.push(t),t+=ft(i);return e}function Ii(r){return r.clips.reduce((e,t)=>e+ft(t),0)}function Sr(r,e){const t=r.clips;if(!t.length)return null;const i=Math.max(0,e),n=Zt(r);for(let a=0;a<t.length;a++){const o=t[a],c=n[a],l=c+ft(o);if(i<l-us)return{clipIndex:a,sourceTime:o.in+(i-c)}}const s=t.length-1;return{clipIndex:s,sourceTime:t[s].out}}function xo(r){const e=Zt(r);return r.clips.length?[...e,Ii(r)]:[0]}function Fn(r,e){const t=xo(r);let i=0,n=Number.POSITIVE_INFINITY;for(let s=0;s<t.length;s++){const a=Math.abs(t[s]-e);a<n&&(i=s,n=a)}return i}function Cu(r,e,t){let i=r,n=t;for(const s of e){const a=Math.abs(s-r);a<=n&&(i=s,n=a)}return i}function Iu(r,e){const t=Sr(r,e);return t?{clip:r.clips[t.clipIndex],index:t.clipIndex}:null}function Eu(r,e,t,i=wo){const n=r.sources.find(c=>c.id===e);if(!n||n.status!=="ready")return r;const s={id:i(),sourceId:e,in:0,out:As(n.duration,r.fps)},a=[...r.clips],o=t===void 0?a.length:Math.min(Math.max(Math.trunc(t),0),a.length);return a.splice(o,0,s),{...r,clips:a}}function Au(r,e,t=wo){const i=xi(e,r.fps),n=Zr(r.fps),s=Zt(r);for(let a=0;a<r.clips.length;a++){const o=r.clips[a],c=s[a],l=c+ft(o);if(i-c>=n-us&&l-i>=n-us){const u=i-c,d={...o,out:o.in+u},f={...o,id:t(),in:o.in+u},m=[...r.clips];return m.splice(a,1,d,f),{...r,clips:m}}}return r}function To(r,e,t,i){const n=r.clips.findIndex(f=>f.id===e);if(n<0)return r;const s=r.clips[n],a=r.sources.find(f=>f.id===s.sourceId),o=a?As(a.duration,r.fps):Number.POSITIVE_INFINITY,c=Zr(r.fps),l=Math.min(Math.max(xi(i,r.fps),0),o),u=t==="in"?{...s,in:Math.min(l,s.out-c)}:{...s,out:Math.max(l,s.in+c)};if(u.in===s.in&&u.out===s.out)return r;const d=[...r.clips];return d[n]=u,{...r,clips:d}}function zu(r,e,t){const i=r.clips.findIndex(o=>o.id===e);if(i<0)return r;const n=Math.min(Math.max(Math.trunc(t),0),r.clips.length-1);if(n===i)return r;const s=[...r.clips],[a]=s.splice(i,1);return s.splice(n,0,a),{...r,clips:s}}function Fu(r,e){return r.clips.some(t=>t.id===e)?{...r,clips:r.clips.filter(t=>t.id!==e)}:r}/*! 152 * Copyright (c) 2026-present, Vanilagy and contributors 153 * 154 * This Source Code Form is subject to the terms of the Mozilla Public 155 * License, v. 2.0. If a copy of the MPL was not distributed with this 156 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 157 */function g(r){if(!r)throw new Error("Assertion failed.")}const zs=r=>{const e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},Be=r=>r&&r[r.length-1],fr=r=>r>=0&&r<2**32,Q=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},Qt=r=>{const e=Q(r);return(e&1)===0?-(e>>1):e+1>>1},Ge=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),_e=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),Ye=new TextDecoder,Ct=new TextEncoder,Fs=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),ei={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Gi=Fs(ei),ti={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Xi=Fs(ti),ri={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Qi=Fs(ri),Bu=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,hn=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class ii{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(n=>{let s=!1;e=()=>{s||(n(),this.pending--,s=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const Ru=/^[0-9a-fA-F]+$/,Ti=r=>[...r].map(e=>
157e.toString(16).padStart(2,"0")).join(""),Mu=r=>{g(r.length%2===0);const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},oa=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Ei=(r,e,t)=>{let i=0,n=r.length-1,s=-1;for(;i<=n;){const a=i+n>>1,o=t(r[a]);o===e?(s=a,n=a-1):o<e?i=a+1:n=a-1}return s},ye=(r,e,t)=>{let i=0,n=r.length-1,s=-1;for(;i<=n;){const a=i+(n-i+1)/2|0;t(r[a])<=e?(s=a,i=a+1):n=a-1}return s},ca=(r,e,t)=>{const i=ye(r,t(e),t);r.splice(i+1,0,e)},Ue=()=>{let r,e;return{promise:new Promise((i,n)=>{r=i,e=n}),resolve:r,reject:e}},ds=(r,e)=>{const t=r.indexOf(e);t!==-1&&r.splice(t,1)},_o=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Bs=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},Ou=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Du=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},Et=r=>{throw new Error(`Unexpected value: ${r}`)},mn=(r,e,t)=>{const i=r.getUint8(e),n=r.getUint8(e+1),s=r.getUint8(e+2);return t?i|n<<8|s<<16:i<<16|n<<8|s},Nu=(r,e,t)=>mn(r,e,t)<<8>>8,Rs=(r,e,t,i)=>{t=t>>>0,t=t&16777215,i?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},Uu=(r,e,t,i)=>{t=De(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),Rs(r,e,t,i)},Yi=(r,e)=>({async next(){const t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),De=(r,e,t)=>Math.max(e,Math.min(t,r)),He="und",_i=r=>{const e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},fs=(r,e)=>Math.round(r/e)*e,Zi=(r,e)=>Math.round(r*e)/e,Bn=(r,e)=>Math.floor(r/e)*e,la=(r,e)=>Math.floor(r*e)/e,Vu=r=>{let e=0;for(;r;)e++,r>>=1;return e},Lu=/^[a-z]{3}$/,Ms=r=>Lu.test(r),lr=1e6*(1+Number.EPSILON),Wu=(r,e)=>{const t={...r,...e};if(r.headers||e.headers){const i=r.headers?hs(r.headers):{},n=e.headers?hs(e.headers):{},s={...i};Object.entries(n).forEach(([a,o])=>{const c=Object.keys(s).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),t.headers=s}return t},hs=r=>{if(r instanceof Headers){const e={};return r.forEach((t,i)=>{e[i]=t}),e}if(Array.isArray(r)){const e={};return r.forEach(([t,i])=>{e[t]=i}),e}return r},Hu=async(r,e,t,i,n)=>{let s=0;for(;;)try{return await r(e,t)}catch(a){if(n())throw a;s++;const o=i(s,a,e);if(o===null)throw a;if(ue._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await bn(1e3*o),n())throw a}},qu=(r,e)=>{const t=r<0?-1:1;r=Math.abs(r);let i=0,n=1,s=1,a=0,o=r;for(;;){const c=Math.floor(o),l=c*s+i,u=c*a+n;if(u>e)return{num:t*s,den:a};if(i=s,n=a,s=l,a=u,o=1/(o-c),!isFinite(o))break}return{num:t*s,den:a}};class pn{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Rn=null;const bi=()=>{var r;return Rn!==null?Rn:Rn=!!(typeof navigator<"u"&&((r=navigator.vendor)!=null&&r.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))};let Mn=null;const Ji=()=>{var r;return Mn!==null?Mn:Mn=typeof navigator<"u"&&((r=navigator.userAgent)==null?void 0:r.includes("Firefox"))};let On=null;const ms=()=>{var r;return On!==null?On:On=!!(typeof navigator<"u"&&((r=navigator.vendor)!=null&&r.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))};let Dn=null;const $u=()=>{if(Dn!==null)return Dn;if(typeof navigator>"u")return null;const r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?Dn=Number(r[1]):null},Nr=(r,e)=>r!==-1?r:e,ps=(r,e,t,i)=>r<=i&&t<=e,So=function*(r){for(const e in r){const t=r[e];t!==void 0&&(yield{key:e,value:t})}},vo=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t},ju=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},Os=()=>{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},gn=r=>typeof r=="number"&&!Number.isNaN(r),cr=(r,e)=>{if(e.includes("://"))return e;if(r.includes("://")){const o=r.indexOf("?");o!==-1&&(r=r.slice(0,o))}let t;if(e.startsWith("/")){const o=r.indexOf("://");if(o===-1)t=e;else{const c=r.indexOf("/",o+3);c===-1?t=r+e:t=r.slice(0,c)+e}}else{const o=r.lastIndexOf("/");o===-1?t=e:t=r.slice(0,o+1)+e}let i="";const n=t.indexOf("://");if(n!==-1){const o=t.indexOf("/",n+3);o!==-1&&(i=t.slice(0,o),t=t.slice(o))}const s=t.split("/"),a=[];for(const o of s)o===".."?a.pop():o!=="."&&a.push(o);return i+a.join("/")},mi=(r,e)=>{let t=0;for(let i=0;i<r.length;i++)e(r[i])&&t++;return t},Ds=(r,e)=>{let t=-1,i=1/0;for(let n=0;n<r.length;n++){const s=e(r[n]);s<i&&(i=s,t=n)}return t},en=r=>{g(Number.isInteger(r.num)),g(Number.isInteger(r.den)),g(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){const n=e%t;e=t,t=n}const i=e||1;return{num:r.num/i,den:r.den/i}},ua=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},bn=r=>new Promise(e=>setTimeout(e,r)),da=r=>Array.isArray(r)?r:[r];class Ai{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:t,once:(i==null?void 0:i.once)??!1};return this._listeners.get(e).add(n),()=>{var s;(s=this._listeners.get(e))==null||s.delete(n)}}_emit(...e){const[t,i]=e,n=this._listeners.get(t);if(n)for(const s of n){try{s.fn(i)}catch(a){console.error(a)}s.once&&n.delete(s)}}}const Ku=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");/*! 158 * Copyright (c) 2026-present, Vanilagy and contributors 159 * 160 * This Source Code Form is subject to the terms of the Mozilla Public 161 * License, v. 2.0. If a copy of the MPL was not distributed with this 162 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 163 */var vt;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(vt||(vt={}));class ue{constructor(){}static get level(){return ue._level}static set level(e){if(e!==vt.Silent&&e!==vt.Errors&&e!==vt.Warnings&&e!==vt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ue._level=e}static get _emitter(){return ue._emitterInstance??(ue._emitterInstance=new Ai)}static on(e,t,i){return ue._emitter.on(e,t,i)}
163static _error(...e){ue._emitter._emit("error",e),ue._level>=vt.Errors&&console.error(...e)}static _warn(...e){ue._emitter._emit("warn",e),ue._level>=vt.Warnings&&console.warn(...e)}static _info(...e){ue._emitter._emit("info",e),ue._level>=vt.Info&&console.info(...e)}}ue._level=vt.Info;ue._emitterInstance=null;/*! 164 * Copyright (c) 2026-present, Vanilagy and contributors 165 * 166 * This Source Code Form is subject to the terms of the Mozilla Public 167 * License, v. 2.0. If a copy of the MPL was not distributed with this 168 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 169 */class Xr{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class Po{constructor(e,t,i,n){if(this.data=e,this.mimeType=t,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}}const Gu=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Xr)&&!(e instanceof Po)&&!Ku(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},rr={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Xu=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};/*! 170 * Copyright (c) 2026-present, Vanilagy and contributors 171 * 172 * This Source Code Form is subject to the terms of the Mozilla Public 173 * License, v. 2.0. If a copy of the MPL was not distributed with this 174 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 175 */class Se{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),n=(t&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let n=this.pos;n<i;n++){const s=Math.floor(n/8);let a=this.bytes[s];const o=7-(n&7);a&=~(1<<o),a|=(t&1<<i-n-1)>>i-n-1<<o,this.bytes[s]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}
175getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new Se(this.bytes);return e.pos=this.pos,e}}/*! 176 * Copyright (c) 2026-present, Vanilagy and contributors 177 * 178 * This Source Code Form is subject to the terms of the Mozilla Public 179 * License, v. 2.0. If a copy of the MPL was not distributed with this 180 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 181 */const Er=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],zi=[-1,1,2,3,4,5,6,8],Ns=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new Se(r);let t=e.readBits(5);t===31&&(t=32+e.readBits(6));const i=e.readBits(4);let n=null;i===15?n=e.readBits(24):i<Er.length&&(n=Er[i]);const s=e.readBits(4);let a=null;return s>=1&&s<=7&&(a=zi[s]),{objectType:t,frequencyIndex:i,sampleRate:n,channelConfiguration:s,numberOfChannels:a}},Co=r=>{let e=Er.indexOf(r.sampleRate),t=null;e===-1&&(e=15,t=r.sampleRate);const i=zi.indexOf(r.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${r.numberOfChannels}`);let n=13;r.objectType>=32&&(n+=6),e===15&&(n+=24);const s=Math.ceil(n/8),a=new Uint8Array(s),o=new Se(a);return r.objectType<32?o.writeBits(5,r.objectType):(o.writeBits(5,31),o.writeBits(6,r.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,t),o.writeBits(4,i),a};/*! 182 * Copyright (c) 2026-present, Vanilagy and contributors 183 * 184 * This Source Code Form is subject to the terms of the Mozilla Public 185 * License, v. 2.0. If a copy of the MPL was not distributed with this 186 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 187 */const wt=["avc","hevc","vp9","av1","vp8","prores"],Xe=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Us=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Jt=[...Us,...Xe],Si=["webvtt"],tn=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],fa=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],ur=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],ha=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],ma=".01.01.01.01.00",pa=".0.110.01.01.01.0",vr=["ap4x","ap4h","apch","apcn","apcs","apco"],Qu=[{fourCc:"apco",bitrate:45e6,alph
187a:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],Yu=(r,e,t,i,n)=>{if(r==="avc"){const a=Math.ceil(e/16)*Math.ceil(t/16),o=tn.find(f=>a<=f.maxMacroblocks&&i<=f.maxBitrate)??Be(tn),c=o?o.level:0,l="64".padStart(2,"0"),u="00",d=c.toString(16).padStart(2,"0");return`avc1.${l}${u}${d}`}else if(r==="hevc"){const c=e*t,l=fa.find(d=>c<=d.maxPictureSize&&i<=d.maxBitrate)??Be(fa);return`hev1.1.6.${l.tier}${l.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){const a=e*t;return`vp09.00.${(ur.find(l=>a<=l.maxPictureSize&&i<=l.maxBitrate)??Be(ur)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){const a=e*t,o=ha.find(u=>a<=u.maxPictureSize&&i<=u.maxBitrate)??Be(ha);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}else if(r==="prores"){const a=Math.pow(e*t/2073600,.95),o=Qu.filter(u=>u.alpha===n);let c=o[0].fourCc,l=1/0;for(const{fourCc:u,bitrate:d}of o){const f=Math.abs(d*a-i);f<l&&(l=f,c=u)}return c}else Et(r)}throw new TypeError(`Unhandled codec '${String(r)}'.`)},Zu=r=>{const e=r.split("."),n=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(s<<5)+o,l=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,f=0,m=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,h=e[5]?Number(e[5][1]):1,b=e[5]?Number(e[5][2]):0,y=(l<<7)+(d<<6)+(f<<5)+(m<<4)+(p<<3)+(h<<2)+b;return[n,c,y,0]},Vs=r=>{const{codec:e,codecDescription:t,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=r;if(e==="avc"){if(g(r.avcType!==null),n){const l=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${r.avcType}.${Ti(l)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${Ti(t.subarray(1,4))}`}else if(e==="hevc"){let l,u,d,f,m,p;if(s)l=s.generalProfileSpace,u=s.generalProfileIdc,d=oa(s.generalProfileCompatibilityFlags),f=s.generalTierFlag,m=s.generalLevelIdc,p=[...s.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const b=_e(t),y=b.getUint8(1);l=y>>6&3,u=y&31,d=oa(b.getUint32(2)),f=y>>5&1,m=b.getUint8(12),p=[];for(let x=0;x<6;x++)p.push(b.getUint8(6+x))}let h="hev1.";for(h+=["","A","B","C"][l]+u,h+=".",h+=d.toString(16).toUpperCase(),h+=".",h+=f===0?"L":"H",h+=m;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(h+=".",h+=p.map(b=>b.toString(16).toUpperCase()).join(".")),h}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const x=r.width*r.height;let T=Be(ur).level;for(const P of ur)if(x<=P.maxPictureSize){T=P.level;break}return`vp09.00.${T.toString().padStart(2,"0")}.08`}const l=a.profile.toString().padStart(2,"0"),u=a.level.toString().padStart(2,"0"),d=a.bitDepth.toString().padStart(2,"0"),f=a.chromaSubsampling.toString().padStart(2,"0"),m=a.colourPrimaries.toString().padStart(2,"0"),p=a.transferCharacteristics.toString().padStart(2,"0"),h=a.matrixCoefficients.toString().padStart(2,"0"),b=a.videoFullRangeFlag.toString().padStart(2,"0");let y=`vp09.${l}.${u}.${d}.${f}`;return y+=`.${m}.${p}.${h}.${b}`,y.endsWith(ma)&&(y=y.slice(0,-ma.length)),y}else if(e==="av1"){if(!o){const P=r.width*r.height;let _=Be(ur).level;for(const S of ur)if(P<=S.maxPictureSize){_=S.level;break}return`av01.0.${_.toString().padStart(2,"0")}M.08`}const l=o.profile,u=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",f=o.bitDepth.toString().padStart(2,"0"),m=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),h=i!=null&&i.primaries?ei[i.primaries]:1,b=i!=null&&i.transfer?ti[i.transfer]:1,y=i!=null&&i.matrix?ri[i.matrix]:1,x=i!=null&&i.fullRange?1:0;let T=`av01.${l}.${u}${d}.${f}`;return T+=`.${m}.${p.toString().padStart(3,"0")}`,T+=`.${h.toString().padStart(2,"0")}`,T+=`.${b.toString().padStart(2,"0")}`,T+=`.${y.toString().padStart(2,"0")}`,T+=`.${x}`,T.endsWith(pa)&&(T=T.slice(0,-pa.length)),T}else{if(e==="prores")return c??"apch";e!==null&&Et(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},Ju=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(Xe.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},Ls=r=>{const{codec:e,codecDescription:t,aacCodecInfo:i}=r;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";{let n;return i.objectType!==null?n=i.objectType:n=Ns(t).objectType,`mp4a.40.${n}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&Xe.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},kn=48e3,Io=/^pcm-([usf])(\d+)(be)?$/,er=r=>
vendor: 9,159 bytes, line 187
187{if(g(Xe.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Io.exec(r);g(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,n=e[3]!=="be",s=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:n,silentValue:s}},Pr=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":vr.includes(r)?"prores":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":r==="ulaw"?"ulaw":r==="alaw"?"alaw":Io.test(r)?r:r==="webvtt"?"webvtt":null,ed=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},td=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},rd=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...vr],id=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,nd=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,sd=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ad=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,od=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!rd.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!hn(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){const{colorSpace:e}=r.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const t=Object.keys(ei);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);const i=Object.keys(ti);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const n=Object.keys(ri);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!id.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!nd.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!sd.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")){if(!ad.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(vr.some(e=>r.decoderConfig.codec.startsWith(e))&&!vr.some(e=>r.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${vr.join(", ")}.`)},cd=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],ld=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!cd.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!hn(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described
187in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!Xe.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Xe.join(", ")}).`)},ud=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*! 188 * Copyright (c) 2026-present, Vanilagy and contributors 189 * 190 * This Source Code Form is subject to the terms of the Mozilla Public 191 * License, v. 2.0. If a copy of the MPL was not distributed with this 192 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 193 */const Cr=4,dd=[44100,48e3,32e3],fd=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Eo=1483304551,Ao=1231971951,hd=(r,e,t,i,n)=>e===0?0:e===1?Math.floor(144*t/(i<<r))+n:e===2?Math.floor(144*t/i)+n:(Math.floor(12*t/i)+n)*4,md=(r,e,t,i)=>e===0?0:e===1?144*t/(i<<r):e===2?144*t/i:12*t/i*4,zo=(r,e)=>r===3?e===3?21:36:e===3?13:21,Ws=(r,e)=>{const t=r>>>24,i=r>>>16&255,n=r>>>8&255,s=r&255;if(t!==255&&i!==255&&n!==255&&s!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((i&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;i&16?a=i&8?0:1:(a=1,o=1);const c=i>>3&3,l=i>>1&3,u=n>>4&15,d=(n>>2&3)%3,f=n>>1&1,m=s>>6&3,p=s>>4&3,h=s>>3&1,b=s>>2&1,y=s&3,x=fd[a*16*4+l*16+u];if(x===-1)return{header:null,bytesAdvanced:1};const T=x*1e3,P=dd[d]>>a+o,_=hd(a,l,T,P,f);if(e!==null&&e<_)return{header:null,bytesAdvanced:1};let S;return c===3?S=l===3?384:1152:l===3?S=384:l===2?S=1152:S=576,{header:{totalSize:_,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:T,frequencyIndex:d,sampleRate:P,channel:m,modeExtension:p,copyright:h,original:b,emphasis:y,audioSamplesInFrame:S},bytesAdvanced:1}},gs=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var rn;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(rn||(rn={}));const vi=r=>r===3?1:2;/*! 194 * Copyright (c) 2026-present, Vanilagy and contributors 195 * 196 * This Source Code Form is subject to the terms of the Mozilla Public 197 * License, v. 2.0. If a copy of the MPL was not distributed with this 198 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 199 */const yn=[48e3,44100,32e3],Fo=[24e3,22050,16e3];/*! 200 * Copyright (c) 2026-present, Vanilagy and contributors 201 * 202 * This Source Code Form is subject to the terms of the Mozilla Public 203 * License, v. 2.0. If a copy of the MPL was not distributed with this 204 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 205 */var Le;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(Le||(Le={}));var Ne;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(Ne||(Ne={}));const Fi=function*(r){let e=0,t=-1;for(;e<r.length-2;){const i=r.indexOf(0,e);if(i===-1||i>=r.length-2)break;e=i;let n=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?n=4:r[e+1]===0&&r[e+2]===1&&(n=3),n===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+n,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},Bo=function*(r,e){let t=0;const i=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let n;e===1?n=i.getUint8(t):e===2?n=i.getUint16(t,!1):e===3?n=mn(i,t,!1):(g(e===4),n=i.getUint32(t,!1)),t+=e,yield{offset:t,length:n},t+=n}},Ro=(r,e)=>{if(e.description){const n=(Ge(e.description)[4]&3)+1;return Bo(r,n)}else return Fi(r)},wn=r=>r&31,xn=r=>{const e=[],t=r.length;for(let i=0;i<t;
205i++)i+2<t&&r[i]===0&&r[i+1]===0&&r[i+2]===3?(e.push(0,0),i+=2):e.push(r[i]);return new Uint8Array(e)},Nn=new Uint8Array([0,0,0,1]),Mo=r=>{const e=r.reduce((n,s)=>n+Nn.byteLength+s.byteLength,0),t=new Uint8Array(e);let i=0;for(const n of r)t.set(Nn,i),i+=Nn.byteLength,t.set(n,i),i+=n.byteLength;return t},Hs=(r,e)=>{const t=r.reduce((s,a)=>s+e+a.byteLength,0),i=new Uint8Array(t);let n=0;for(const s of r){const a=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:a.setUint8(n,s.byteLength);break;case 2:a.setUint16(n,s.byteLength,!1);break;case 3:Rs(a,n,s.byteLength,!1);break;case 4:a.setUint32(n,s.byteLength,!1);break}n+=e,i.set(s,n),n+=s.byteLength}return i},pd=(r,e)=>{if(e.description){const n=(Ge(e.description)[4]&3)+1;return Hs(r,n)}else return Mo(r)},qs=r=>{try{const e=[],t=[],i=[];for(const o of Fi(r)){const c=r.subarray(o.offset,o.offset+o.length),l=wn(c[0]);l===Le.SPS?e.push(c):l===Le.PPS?t.push(c):l===Le.SPS_EXT&&i.push(c)}if(e.length===0||t.length===0)return null;const n=e[0],s=$s(n);g(s!==null);const a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?i:null}}catch(e){return ue._error("Error building AVC Decoder Configuration Record:",e),null}},gd=r=>{const e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(const t of r.sequenceParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}e.push(r.pictureParameterSets.length);for(const t of r.pictureParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}if(r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144){g(r.chromaFormat!==null),g(r.bitDepthLumaMinus8!==null),g(r.bitDepthChromaMinus8!==null),g(r.sequenceParameterSetExt!==null),e.push(252|r.chromaFormat&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.sequenceParameterSetExt.length);for(const t of r.sequenceParameterSetExt){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}}return new Uint8Array(e)},bd=r=>{try{const e=_e(r);let t=0;const i=e.getUint8(t++),n=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let m=0;m<c;m++){const p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}const u=e.getUint8(t++),d=[];for(let m=0;m<u;m++){const p=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+p)),t+=p}const f={configurationVersion:i,avcProfileIndication:n,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&t+4<=r.length){const m=e.getUint8(t++)&3,p=e.getUint8(t++)&7,h=e.getUint8(t++)&7,b=e.getUint8(t++);f.chromaFormat=m,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=h;const y=[];for(let x=0;x<b;x++){const T=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+T)),t+=T}f.sequenceParameterSetExt=y}return f}catch(e){return ue._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Oo={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},$s=r=>{try{const e=new Se(xn(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const i=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();Q(e);let a=1,o=0,c=0,l=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=Q(e),a===3&&(l=e.readBits(1)),o=Q(e),c=Q(e),e.skipBits(1),e.readBits(1))){for(let M=0;M<(a!==3?8:12);M++)if(e.readBits(1)){const $=M<6?16:64;let B=8,O=8;for(let X=0;X<$;X++){if(O!==0){const ae=Qt(e);O=(B+ae+256)%256}B=O===0?B:O}}}Q(e);const u=Q(e);if(u===0)Q(e);else if(u===1){e.skipBits(1),Qt(e),Qt(e);const H=Q(e);for(let M=0;M<H;M++)Qt(e)}Q(e),e.skipBits(1);const d=Q(e),f=Q(e),m=16*(d+1),p=16*(f+1);let h=m,b=p;const y=e.readBits(1);if(y||e.skipBits(1),e.skipBits(1),e.readBits(1)){const H=Q(e),M=Q(e),D=Q(e),$=Q(e);let B,O;if((l===0?a:0)===0)B=1,O=2-y;else{const ae=a===3?1:2,ve=a===1?2:1;B=ae,O=ve*(2-y)}h-=B*(H+M),b-=O*(D+$)}let T=2,P=2,_=2,S=0,I={num:1,den:1},C=null,v=null;if(e.readBits(1)){if(e.readBits(1)){const ve=e.readBits(8);if(ve===255)I={num:e.readBits(16),den:e.readBits(16)};else{const Ie=Oo[ve];Ie&&(I=Ie)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),S=e.readBits(1),e.readBits(1)&&(T=e.readBits(8),P=e.readBits(8),_=e.readBits(8))),e.readBits(1)&&(Q(e),Q(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const O=e.readBits(1);O&&ga(e);const X=e.readBits(1);X&&ga(e),(O||X)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),Q(e),Q(e),Q(e),Q(e),C=Q(e),v=Q(e))}if(C===null){g(v===null);const H=n&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&H)C=0,v=0;else{const M=d+1,D=f+1,$=(2-y)*D,B=tn.find(X=>X.level>=s)??Be(tn),O=Math.min(Math.floor(B.maxDpbMbs/(M*$)),16);C=O,v=O}}return g(v!==null),{profileIdc:i,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:y,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:p,displayWidth:h,displayHeight:b,pixelAspectRatio:I,colourPrimaries:T,matrixCoefficients:_,transferCharacteristics:P,fullRangeFlag:S,numReorderFrames:C,maxDecFrameBuffering:v}}catch(e){return ue._error("Error parsing AVC SPS:",e),null}},ga=r=>{const e=Q(r);
205r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)Q(r),Q(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},kd=(r,e)=>{if(e.description){const n=(Ge(e.description)[21]&3)+1;return Hs(r,n)}else return Mo(r)},nn=(r,e)=>{if(e.description){const n=(Ge(e.description)[21]&3)+1;return Bo(r,n)}else return Fi(r)},Jr=r=>r>>1&63,Do=r=>{try{const e=new Se(xn(r));e.skipBits(16),e.readBits(4);const t=e.readBits(3),i=e.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=yd(e,t);Q(e);const u=Q(e);let d=0;u===3&&(d=e.readBits(1));const f=Q(e),m=Q(e);let p=f,h=m;if(e.readBits(1)){const M=Q(e),D=Q(e),$=Q(e),B=Q(e);let O=1,X=1;const ae=d===0?u:0;ae===1?(O=2,X=2):ae===2&&(O=2,X=1),p-=(M+D)*O,h-=($+B)*X}const b=Q(e),y=Q(e);Q(e);const T=e.readBits(1)?0:t;let P=0;for(let M=T;M<=t;M++)Q(e),P=Q(e),Q(e);Q(e),Q(e),Q(e),Q(e),Q(e),Q(e),e.readBits(1)&&e.readBits(1)&&wd(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),Q(e),Q(e),e.skipBits(1));const _=Q(e);if(xd(e,_),e.readBits(1)){const M=Q(e);for(let D=0;D<M;D++)Q(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let S=2,I=2,C=2,v=0,A=0,H={num:1,den:1};if(e.readBits(1)){const M=_d(e,t);H=M.pixelAspectRatio,S=M.colourPrimaries,I=M.transferCharacteristics,C=M.matrixCoefficients,v=M.fullRangeFlag,A=M.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:h,pixelAspectRatio:H,colourPrimaries:S,transferCharacteristics:I,matrixCoefficients:C,fullRangeFlag:v,maxDecFrameBuffering:P+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:b,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:A}}catch(e){return ue._error("Error parsing HEVC SPS:",e),null}},js=r=>{try{const e=[],t=[],i=[],n=[];for(const l of Fi(r)){const u=r.subarray(l.offset,l.offset+l.length),d=Jr(u[0]);d===Ne.VPS_NUT?e.push(u):d===Ne.SPS_NUT?t.push(u):d===Ne.PPS_NUT?i.push(u):(d===Ne.PREFIX_SEI_NUT||d===Ne.SUFFIX_SEI_NUT)&&n.push(u)}if(t.length===0||i.length===0)return null;const s=Do(t[0]);if(!s)return null;let a=0;if(i.length>0){const l=i[0],u=new Se(xn(l));u.skipBits(16),Q(u),Q(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),Q(u),Q(u),Qt(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&Q(u),Qt(u),Qt(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);const d=u.readBits(1),f=u.readBits(1);!d&&!f?a=0:d&&!f?a=2:!d&&f?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:Ne.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:Ne.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ne.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Jr(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return ue._error("Error building HEVC Decoder Configuration Record:",e),null}},yd=(r,e)=>{const t=r.readBits(2),i=r.readBits(1),n=r.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|r.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);const o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},wd=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))Q(r);else{const n=Math.min(64,1<<4+(e<<1));e>1&&Qt(r);for(let s=0;s<n;s++)Qt(r)}},xd=(r,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=Td(r,i,e,t)},Td=(r,e,t,i)=>{let n=0,s=0,a=0;if(e!==0&&(s=r.readBits(1)),s){if(e===t){const c=Q(r);a=e-(c+1)}else a=e-1;r.readBits(1),Q(r);const o=i[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);n=i[a]}else{const o=Q(r),c=Q(r);for(let l=0;l<o;l++)Q(r),r.readBits(1);for(let l=0;l<c;l++)Q(r),r.readBits(1);n=o+c}return n},_d=(r,e)=>{let t=2,i=2,n=2,s=0,a=0,o={num:1,den:1};if(r.readBits(1)){const c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{const l=Oo[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),s=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),i=r.readBits(8),n=r.readBits(8))),r.readBits(1)&&(Q(r),Q(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(Q(r),Q(r),Q(r),Q(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&Q(r),r.readBits(1)&&Sd(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=Q(r),Q(r),Q(r),Q(r),Q(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Sd=(r,e,t)=>{let i=!1,n=!1,s=!1;i=r.readBits(1)===1,n=r.readBits(1)===1,(i||n)&&(s=r.readBits(1)===1,s&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),s&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let a=0;a<=t;a++){const o=r.readBits(1)===1;let c=!0;o||(c=r.readBits(1)===1);let l=!1;c?Q(r):l=r.readBits(1)===1;let u=1;l||(u=Q(r)+1),i&&ba(r,u,s),n&&ba(r,u,s)}},ba=(r,e,t)=>{for(let i=0;i<e;i++)Q(r),Q(r),t&&(Q(r),Q(r)),r.readBits(1)},vd=r=>{const e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(const t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nal
205UnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)};var We;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(We||(We={}));const Pd=(r,e)=>{const t=new Set;let i=We.audAllowed;for(const s of nn(r,e)){if(i===We.noMoreDataAllowed){t.add(s.offset);continue}const a=Jr(r[s.offset]);if(i===We.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?i>We.audAllowed?o=!0:i=We.beforeFirstVcl:a<=31?i>We.afterFirstVcl?o=!0:i=We.afterFirstVcl:a===36?i!==We.afterFirstVcl?o=!0:i=We.eoBitstreamAllowed:a===37?i<We.afterFirstVcl?o=!0:i=We.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?i>We.beforeFirstVcl?o=!0:i=We.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&i<We.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;const n=[];for(const s of nn(r,e))t.has(s.offset)||n.push(r.subarray(s.offset,s.offset+s.length));return kd(n,e)},No=r=>{const e=new Se(r);if(e.readBits(2)!==2)return null;const i=e.readBits(1),s=(e.readBits(1)<<1)+i;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=e.readBits(1)?12:10);const u=e.readBits(3);let d=0,f=0;if(u!==7)if(f=e.readBits(1),s===1||s===3){const I=e.readBits(1),C=e.readBits(1);d=!I&&!C?3:I&&!C?2:1,e.skipBits(1)}else d=1;else d=3,f=1;const m=e.readBits(16),p=e.readBits(16),h=m+1,b=p+1,y=h*b;let x=Be(ur).level;for(const S of ur)if(y<=S.maxPictureSize){x=S.level;break}return{profile:s,level:x,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Uo=function*(r){const e=new Se(r),t=()=>{let i=0;for(let n=0;n<8;n++){const s=e.readAlignedByte();if(i|=(s&127)<<n*7,!(s&128))break;if(n===7&&s&128)return null}return i>=2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);const i=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let a;if(s){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);g(e.pos%8===0),yield{type:i,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Vo=r=>{for(const{type:e,data:t}of Uo(r)){if(e!==1)continue;const i=new Se(t),n=i.readBits(3);i.readBits(1);const s=i.readBits(1);let a=0,o=0,c=0;if(s)a=i.readBits(5);else{if(i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.readBits(1)))return null;const _=i.readBits(1);_&&(c=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5));const S=i.readBits(5);for(let I=0;I<=S;I++){i.skipBits(12);const C=i.readBits(5);if(I===0&&(a=C),C>7){const A=i.readBits(1);I===0&&(o=A)}if(_&&i.readBits(1)){const H=c+1;i.skipBits(H),i.skipBits(H),i.skipBits(1)}i.readBits(1)&&i.skipBits(4)}}const l=i.readBits(4),u=i.readBits(4),d=l+1;i.skipBits(d);const f=u+1;i.skipBits(f);let m=0;if(s?m=0:m=i.readBits(1),m&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!s){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const P=i.readBits(1);P&&(i.skipBits(1),i.skipBits(1));const _=i.readBits(1);let S=0;_?S=2:S=i.readBits(1),S>0&&(i.readBits(1)||i.skipBits(1)),P&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);const p=i.readBits(1);let h=8;n===2&&p?h=i.readBits(1)?12:10:n<=2&&(h=p?10:8);let b=0;n!==1&&(b=i.readBits(1));let y=1,x=1,T=0;return b||(n===0?(y=1,x=1):n===1?(y=0,x=0):h===12&&(y=i.readBits(1),y&&(x=i.readBits(1))),y&&x&&(T=i.readBits(2))),{profile:n,level:a,tier:o,bitDepth:h,monochrome:b,chromaSubsamplingX:y,chromaSubsamplingY:x,chromaSamplePosition:T}}return null},Lo=r=>{const e=_e(r),t=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},Cd=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Id=r=>{const e=r[0]>>3;return{durationInSamples:Cd[e]}},Ed=r=>
205{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const t=r.length,i=new Uint8Array(t);for(let d=0;d<t;d++)i[d]=r[t-1-d];const n=new Se(i);let s=0;for(;n.getBitsLeft()>97;)if(n.readBits(1)===1){s=n.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;n.getBitsLeft()>=97;){const d=n.pos,f=n.readBits(8),m=n.readBits(16),p=n.readBits(16);if(f>63||m!==0||p!==0){n.pos=d;break}if(n.skipBits(1),a++,a>64)break;n.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const l=c;n.pos=0,n.skipBits(s);const u=Array(l).fill(0);for(let d=l-1;d>=0;d--)n.skipBits(40),u[d]=n.readBits(1);return{modeBlockflags:u}},Tn=(r,e,t)=>{switch(r){case"avc":{for(const i of Ro(t,e)){const n=t[i.offset],s=wn(n);if(s>=Le.NON_IDR_SLICE&&s<=Le.SLICE_DPC)return"delta";if(s===Le.IDR)return"key";if(s===Le.SEI&&(!ms()||$u()>=144)){const a=t.subarray(i.offset,i.offset+i.length),o=xn(a);let c=1;do{let l=0;for(;;){const f=o[c++];if(f===void 0||(l+=f,f<255))break}let u=0;for(;;){const f=o[c++];if(f===void 0||(u+=f,f<255))break}if(l===6){const f=new Se(o);f.pos=8*c;const m=Q(f),p=f.readBits(1);if(m===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(const i of nn(t,e)){const n=Jr(t[i.offset]);if(n<Ne.BLA_W_LP)return"delta";if(n<=Ne.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new Se(t);if(i.readBits(2)!==2)return null;const n=i.readBits(1);return(i.readBits(1)<<1)+n===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:n,data:s}of Uo(t))if(n===1){const a=new Se(s);a.skipBits(4),i=!!a.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";const a=new Se(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:Et(r),g(!1)}};var Qr;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Qr||(Qr={}));const bs=(r,e)=>{var o,c;const t=_e(r);let i=0;const n=t.getUint32(i,!0);i+=4;const s=Ye.decode(r.subarray(i,i+n));i+=n,n>0&&(e.raw??(e.raw={}),(o=e.raw).vendor??(o.vendor=s));const a=t.getUint32(i,!0);i+=4;for(let l=0;l<a;l++){const u=t.getUint32(i,!0);i+=4;const d=Ye.decode(r.subarray(i,i+u));i+=u;const f=d.indexOf("=");if(f===-1)continue;const m=d.slice(0,f).toUpperCase(),p=d.slice(f+1);switch(e.raw??(e.raw={}),(c=e.raw)[m]??(c[m]=p),m){case"TITLE":e.title??(e.title=p);break;case"DESCRIPTION":e.description??(e.description=p);break;case"ARTIST":e.artist??(e.artist=p);break;case"ALBUM":e.album??(e.album=p);break;case"ALBUMARTIST":e.albumArtist??(e.albumArtist=p);break;case"COMMENT":e.comment??(e.comment=p);break;case"LYRICS":e.lyrics??(e.lyrics=p);break;case"TRACKNUMBER":{const h=p.split("/"),b=Number.parseInt(h[0],10),y=h[1]&&Number.parseInt(h[1],10);Number.isInteger(b)&&b>0&&(e.trackNumber??(e.trackNumber=b)),y&&Number.isInteger(y)&&y>0&&(e.tracksTotal??(e.tracksTotal=y))}break;case"TRACKTOTAL":{const h=Number.parseInt(p,10);Number.isInteger(h)&&h>0&&(e.tracksTotal??(e.tracksTotal=h))}break;case"DISCNUMBER":{const h=p.split("/"),b=Number.parseInt(h[0],10),y=h[1]&&Number.parseInt(h[1],10);Number.isInteger(b)&&b>0&&(e.discNumber??(e.discNumber=b)),y&&Number.isInteger(y)&&y>0&&(e.discsTotal??(e.discsTotal=y))}break;case"DISCTOTAL":{const h=Number.parseInt(p,10);Number.isInteger(h)&&h>0&&(e.discsTotal??(e.discsTotal=h))}break;case"DATE":{const h=new Date(p);Number.isNaN(h.getTime())||(e.date??(e.date=h))}break;case"GENRE":e.genre??(e.genre=p);break;case"METADATA_BLOCK_PICTURE":{const h=vo(p),b=_e(h),y=b.getUint32(0,!1),x=b.getUint32(4,!1),T=String.fromCharCode(...h.subarray(8,8+x)),P=b.getUint32(8+x,!1),_=Ye.decode(h.subarray(12+x,12+x+P)),S=b.getUint32(x+P+28),I=h.subarray(x+P+32,x+P+32+S);e.images??(e.images=[]),e.images.push({data:I,mimeType:T,kind:y===3?"coverFront":y===4?"coverBack":"unknown",name:void 0,description:_||void 0})}break}}},Ks=[2,1,2,3,3,4,4,5],Wo=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;const e=new Se(r);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const i=e.readBits(6),n=e.readBits(5);if(n>8)return null;const s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);const o=e.readBits(1),c=Math.floor(i/2);
205return{fscod:t,bsid:n,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},Ad=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],zd=1536,Ho=[1,2,3,6],qo=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;const e=new Se(r);e.skipBits(16);const t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;const i=e.readBits(11),n=e.readBits(2);let s=0,a;n===3?(s=e.readBits(2),a=3):a=e.readBits(2);const o=e.readBits(3),c=e.readBits(1),l=e.readBits(5);if(l<11||l>16)return null;const u=Ho[a];let d;return n<3?d=yn[n]/1e3:d=Fo[s]/1e3,{dataRate:Math.round((i+1)*d/(u*16)),substreams:[{fscod:n,fscod2:s,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},Fd=r=>{if(r.length<2)return null;const e=new Se(r),t=e.readBits(13),i=e.readBits(3),n=[];for(let s=0;s<=i&&!(Math.ceil(e.pos/8)+3>r.length);s++){const a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);const c=e.readBits(3),l=e.readBits(3),u=e.readBits(1);e.skipBits(3);const d=e.readBits(4);let f=0;d>0?f=e.readBits(9):e.skipBits(1),n.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:f})}return n.length===0?null:{dataRate:t,substreams:n}},$o=r=>{const e=r.substreams[0];return g(e),e.fscod<3?yn[e.fscod]:e.fscod2!==null&&e.fscod2<3?Fo[e.fscod2]:null},jo=r=>{const e=r.substreams[0];g(e);let t=Ks[e.acmod]+e.lfeon;if(e.numDepSub>0){const i=[2,2,1,1,2,2,2,1,1];for(let n=0;n<9;n++)e.chanLoc&1<<8-n&&(t+=i[n])}return t};/*! 206 * Copyright (c) 2026-present, Vanilagy and contributors 207 * 208 * This Source Code Form is subject to the terms of the Mozilla Public 209 * License, v. 2.0. If a copy of the MPL was not distributed with this 210 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 211 */class ir{constructor(e){this.input=e}dispose(){}}/*! 212 * Copyright (c) 2026-present, Vanilagy and contributors 213 * 214 * This Source Code Form is subject to the terms of the Mozilla Public 215 * License, v. 2.0. If a copy of the MPL was not distributed with this 216 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 217 */const ot=new Uint8Array(0);class Ae{constructor(e,t,i,n,s=-1,a,o){if(this.data=e,this.type=t,this.timestamp=i,this.duration=n,this.sequenceNumber=s,e===ot&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if((o==null?void 0:o.alpha)!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if((o==null?void 0:o.alphaByteLength)!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===ot}get microsecondTimestamp(){return Math.trunc(lr*this.timestamp)}get microsecondDuration(){return Math.trunc(lr*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");
217return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new Ae(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if((e==null?void 0:e.data)!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if((e==null?void 0:e.type)!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if((e==null?void 0:e.timestamp)!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if((e==null?void 0:e.duration)!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if((e==null?void 0:e.sequenceNumber)!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if((e==null?void 0:e.sideData)!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new Ae((e==null?void 0:e.data)??this.data,(e==null?void 0:e.type)??this.type,(e==null?void 0:e.timestamp)??this.timestamp,(e==null?void 0:e.duration)??this.duration,(e==null?void 0:e.sequenceNumber)??this.sequenceNumber,this.byteLength,(e==null?void 0:e.sideData)??this.sideData)}}/*! 218 * Copyright (c) 2026-present, Vanilagy and contributors 219 * 220 * This Source Code Form is subject to the terms of the Mozilla Public 221 * License, v. 2.0. If a copy of the MPL was not distributed with this 222 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 223 */const Ko=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t},Go=r=>{const e=_e(r);let t=0;const i=e.getUint8(t);t+=1,t+=3;const n=Ti(r.subarray(t,t+16));t+=16;let s=null;if(i>0){const o=e.getUint32(t);if(t+=4,o>0){s=[];for(let c=0;c<o;c++)s.push(Ti(r.subarray(t,t+16))),t+=16}}const a=e.getUint32(t);return t+=4,{systemId:n,keyIds:s,data:r.slice(t,t+a)}},Xo=(r,e)=>r.systemId===e.systemId&&ju(r.data,e.data);/*! 224 * Copyright (c) 2026-present, Vanilagy and contributors 225 * 226 * This Source Code Form is subject to the terms of the Mozilla Public 227 * License, v. 2.0. If a copy of the MPL was not distributed with this 228 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 229 */const $t=8,wr=16,ar=r=>{let e=K(r);const t=Re(r,4);let i=8;e===1&&(e=ut(r),i=16);const s=e-i;return s<0?null:{name:t,totalSize:e,headerSize:i,contentSize:s}},mr=r=>Tr(r)/65536,Un=r=>Tr(r)/1073741824,Vn=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;const i=ie(r);if(e|=i&127,(i&128)===0)break}return e},Tt=r=>{let e=Oe(r);return r.skip(2),e=Math.min(e,r.remainingLength),Ye.decode(se(r,e))},Bd=r=>{const e=ar(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;const t=K(r);r.skip(4);const i=se(r,e.contentSize-8);switch(t){case 1:return Ye.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Xr(i,"image/jpeg");case 14:return new Xr(i,"image/png");case 27:return new Xr(i,"image/bmp");default:return i}};/*! 230 * Copyright (c) 2026-present, Vanilagy and contributors 231 * 232 * This Source Code Form is subject to the terms of the Mozilla Public 233 * License, v. 2.0. If a copy of the MPL was not distributed with this 234 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 235 */const Pt=16,Nt=new Uint32Array(256),Ur=new Uint32Array(256),Vr=new Uint32Array(256),Lr=new Uint32Array(256),Wr=new Uint32Array(256),Ve=new Uint32Array(256),Qo=new Uint32Array(10);let Yo=!1;const Rd=()=>
235{const r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let s=0,a=1;s<256;s++)t[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);const i=(s,a)=>s&&a?t[(e[s]+e[a])%255]:0;r[0]=99;for(let s=1;s<256;s++){const a=t[255-e[s]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[s]=o}for(let s=0;s<256;s++){const a=r[s],o=r.indexOf(s);Nt[s]=a<<24|a<<16|a<<8|a,Ve[s]=o<<24|o<<16|o<<8|o;const c=i(o,14),l=i(o,9),u=i(o,13),d=i(o,11),f=c<<24|l<<16|u<<8|d;Ur[s]=f,Vr[s]=f>>>8|f<<24,Lr[s]=f>>>16|f<<16,Wr[s]=f>>>24|f<<8}let n=1;for(let s=0;s<10;s++)Qo[s]=n<<24,n=n<<1^(n&128?283:0);Yo=!0};class Zo{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Pt/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Pt),this.out=new Uint8Array(Pt),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){g(e.byteLength===16),g(t.byteLength===16),Yo||Rd();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=n.getUint32(0,!1),this.iv[1]=n.getUint32(4,!1),this.iv[2]=n.getUint32(8,!1),this.iv[3]=n.getUint32(12,!1);for(let s=4;s<44;s+=4){const a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^Nt[a>>>16&255]&4278190080^Nt[a>>>8&255]&16711680^Nt[a>>>0&255]&65280^Nt[a>>>24&255]&255^Qo[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){const o=this.roundkey[s+a];this.roundkey[s+a]=Ur[Nt[o>>>24&255]&255]^Vr[Nt[o>>>16&255]&255]^Lr[Nt[o>>>8&255]&255]^Wr[Nt[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],n=this.inView.getUint32(12,!1)^this.roundkey[3];const s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1);let l,u,d,f;for(let y=1;y<10;y++){const x=y*4;l=Ur[e>>>24]^Vr[n>>>16&255]^Lr[i>>>8&255]^Wr[t&255]^this.roundkey[x],u=Ur[t>>>24]^Vr[e>>>16&255]^Lr[n>>>8&255]^Wr[i&255]^this.roundkey[x+1],d=Ur[i>>>24]^Vr[t>>>16&255]^Lr[e>>>8&255]^Wr[n&255]^this.roundkey[x+2],f=Ur[n>>>24]^Vr[i>>>16&255]^Lr[t>>>8&255]^Wr[e&255]^this.roundkey[x+3],e=l,t=u,i=d,n=f}const m=Ve[e>>>24&255]&4278190080^Ve[n>>>16&255]&16711680^Ve[i>>>8&255]&65280^Ve[t>>>0&255]&255^this.roundkey[40],p=Ve[t>>>24&255]&4278190080^Ve[e>>>16&255]&16711680^Ve[n>>>8&255]&65280^Ve[i>>>0&255]&255^this.roundkey[41],h=Ve[i>>>24&255]&4278190080^Ve[t>>>16&255]&16711680^Ve[e>>>8&255]&65280^Ve[n>>>0&255]&255^this.roundkey[42],b=Ve[n>>>24&255]&4278190080^Ve[i>>>16&255]&16711680^Ve[t>>>8&255]&65280^Ve[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,m^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,h^this.iv[2],!1),this.outView.setUint32(12,b^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const Md=(r,e,t)=>{let i=!1,n=0;const s=2**16,a=16,o=new Zo;return new ReadableStream({pull:async c=>{i||(o.init(await e()),i=!0);const l=s+a;let u=r.requestSliceRange(n,0,l);if(u instanceof Promise&&(u=await u),!u||u.length===0)throw new Error("Invalid ciphertext.");const d=u.length;if(d%16!==0)throw new Error("Invalid ciphertext.");const f=d===l?d-a:d,m=se(u,f),p=new Uint8Array(f);for(let h=0;h<f;h+=16)o.in.set(m.subarray(h,h+16)),o.decrypt(),p.set(o.out,h);if(f<d)c.enqueue(p),n+=f;else{const h=p[f-1];if(h===0||h>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const b=p.subarray(0,f-h);c.enqueue(b),c.close(),t()}},cancel:()=>{t()}})};/*! 236 * Copyright (c) 2026-present, Vanilagy and contributors 237 * 238 * This Source Code Form is subject to the terms of the Mozilla Public 239 * License, v. 2.0. If a copy of the MPL was not distributed with this 240 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 241 */class Gs extends ir{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.pss
241hBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(n=>(n==null?void 0:n.codec)??null)));return Ko({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(i=>{var n;return((n=i.info)==null?void 0:n.type)==="video"}),hasAudio:this.tracks.some(i=>{var n;return((n=i.info)==null?void 0:n.type)==="audio"}),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1;for(;;){let i=this.reader.requestSliceRange(e,$t,wr);if(i instanceof Promise&&(i=await i),!i)break;const n=e,s=ar(i);if(!s)break;if(s.name==="ftyp"||s.name==="styp"){const a=Re(i,4);this.isQuickTime=a==="qt "}else if(s.name==="moov"){let a=this.reader.requestSlice(i.filePos,s.contentSize);if(a instanceof Promise&&(a=await a),!a)break;this.moovSlice=a,this.readContiguousBoxes(this.moovSlice);for(const o of this.tracks){const c=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(c*o.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>n+s.totalSize;break}else if(s.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');const a=await this.input._initInput._getDemuxer();if(a.constructor!==Gs)throw new Error("Init input must match the input's format.");await a.readMetadata(),this.movieTimescale=a.movieTimescale,this.movieDurationInTimescale=a.movieDurationInTimescale,this.metadataTags=a.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=a.fragmentTrackDefaults,this.psshBoxes=a.psshBoxes;for(const o of a.tracks){const c={id:o.id,demuxer:this,trackBacking:null,disposition:o.disposition,timescale:o.timescale,durationInMediaTimescale:o.durationInMediaTimescale,durationInMovieTimescale:o.durationInMovieTimescale,rotation:o.rotation,internalCodecId:o.internalCodecId,name:o.name,languageCode:o.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:o.editListPreviousSegmentDurations,editListOffset:o.editListOffset,encryptionInfo:o.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:o.info};if(o.trackBacking){if(g(c.info),c.info.type==="video"&&c.info.width!==-1){const l=c;c.trackBacking=new ka(l),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){const l=c;c.trackBacking=new ya(l),this.tracks.push(c)}}}t=!1;break}e=n+s.totalSize}if(t){g(this.reader.fileSize!==null);let i=this.reader.requestSlice(this.reader.fileSize-4,4);i instanceof Promise&&(i=await i),g(i);const n=K(i),s=this.reader.fileSize-n;if(s>=0&&s<=this.reader.fileSize-wr){let a=this.reader.requestSliceRange(s,$t,wr);if(a instanceof Promise&&(a=await a),a){const o=ar(a);if(o&&o.name==="mfra"){let c=this.reader.requestSlice(a.filePos,o.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})())}getSampleTableForTrack(e){var s,a;if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;g(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,((s=e.info)==null?void 0:s.type)==="audio"&&e.info.codec&&Xe.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){g(((a=e.info)==null?void 0:a.type)==="audio");const o=er(e.info.codec),c=[],l=[];for(let u=0;u<t.sampleToChunk.length;u++){const d=t.sampleToChunk[u],f=t.sampleToChunk[u+1],m=(f?f.startChunkIndex:t.chunkOffsets.length)-d.startChunkIndex;for(let p=0;p<m;p++){const h=d.startSampleIndex+p*d.samplesPerChunk,b=h+d.samplesPerChunk,y=ye(t.sampleTimingEntries,h,A=>A.startIndex),x=t.sampleTimingEntries[y],T=ye(t.sampleTimingEntries,b,A=>A.startIndex),P=t.sampleTimingEntries[T],_=x.startDecodeTimestamp+(h-x.startIndex)*x.delta,I=P.startDecodeTimestamp+(b-P.startIndex)*P.delta-_,C=Be(c);C&&C.delta===I?C.count++:c.push({startIndex:d.startChunkIndex+p,startDecodeTimestamp:_,count:1,delta:I});const v=d.samplesPerChunk*o.sampleSize*e.info.numberOfChannels;l.push(v)}d.startSampleIndex=d.startChunkIndex,d.samplesPerChunk=1}
241t.sampleTimingEntries=c,t.sampleSizes=l}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const o of t.sampleTimingEntries)for(let c=0;c<o.count;c++)t.presentationTimestamps.push({presentationTimestamp:o.startDecodeTimestamp+c*o.delta,sampleIndex:o.startIndex+c});for(const o of t.sampleCompositionTimeOffsets)for(let c=0;c<o.count;c++){const l=o.startIndex+c,u=t.presentationTimestamps[l];u&&(u.presentationTimestamp+=o.offset)}t.presentationTimestamps.sort((o,c)=>o.presentationTimestamp-c.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let o=0;o<t.presentationTimestamps.length;o++)t.presentationTimestampIndexMap[t.presentationTimestamps[o].sampleIndex]=o}return t}async readFragment(e){var a;if(((a=this.lastReadFragment)==null?void 0:a.moofOffset)===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,$t,wr);t instanceof Promise&&(t=await t),g(t);const i=ar(t);g((i==null?void 0:i.name)==="moof");let n=this.reader.requestSlice(e,i.totalSize);n instanceof Promise&&(n=await n),g(n),this.traverseBox(n);const s=this.lastReadFragment;g(s&&s.moofOffset===e);for(const[,o]of s.trackData){const c=o.track,{fragmentPositionCache:l}=c;if(!o.startTimestampIsFinal){const d=c.fragmentLookupTable.find(f=>f.moofOffset===s.moofOffset);if(d)Ln(o,d.timestamp);else{const f=ye(l,s.moofOffset-1,m=>m.moofOffset);if(f!==-1){const m=l[f];Ln(o,m.endTimestamp)}}o.startTimestampIsFinal=!0}const u=ye(l,o.startTimestamp,d=>d.startTimestamp);if((u===-1||l[u].moofOffset!==s.moofOffset)&&l.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp}),o.encryptionAuxInfo&&c.encryptionInfo){const d=await ec(this.reader,c.encryptionInfo,o.encryptionAuxInfo);for(let f=0;f<Math.min(o.samples.length,d.length);f++){const m=d[f];o.samples[f].encryption=m}}}return s}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-$t&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-$t;){const i=e.filePos,n=ar(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=i+n.totalSize}}traverseBox(e){var a,o,c,l,u,d,f,m,p,h,b,y,x,T,P,_,S,I,C,v,A,H,M,D,$,B,O,X,ae,ve,Ie,ct,de,qe,xt,Ft,Bt,Rt,Mt,pt,te,J,Te,ge,ce;const t=e.filePos,i=ar(e);if(!i)return!1;const n=e.filePos,s=t+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mvhd":{const k=ie(e);e.skip(3),k===1?(e.skip(16),this.movieTimescale=K(e),this.movieDurationInTimescale=ut(e)):(e.skip(8),this.movieTimescale=K(e),this.movieDurationInTimescale=K(e))}break;case"trak":{const k={id:-1,demuxer:this,trackBacking:null,disposition:{...rr,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:He,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=k,this.readContiguousBoxes(e.slice(n,i.contentSize)),k.id!==-1&&k.timescale!==-1&&k.info!==null){if(k.info.type==="video"&&k.info.width!==-1){const N=k;k.trackBacking=new ka(N),this.tracks.push(k)}else if(k.info.type==="audio"&&k.info.numberOfChannels!==-1){const N=k;k.trackBacking=new ya(N),this.tracks.push(k)}}this.currentTrack=null}break;case"tkhd":{const k=this.currentTrack;if(!k)break;const N=ie(e),F=!!(Ut(e)&1);if(k.disposition.default=F,N===0)e.skip(8),k.id=K(e),e.skip(4),k.durationInMovieTimescale=K(e);else if(N===1)e.skip(16),k.id=K(e),e.skip(4),k.durationInMovieTimescale=ut(e);else throw new Error(`Incorrect track header version ${N}.`);e.skip(16);const G=[mr(e),mr(e),Un(e),mr(e),mr(e),Un(e),mr(e),mr(e),Un(e)],U=zs(fs(Ud(G),90));g(U===0||U===90||U===180||U===270),k.rotation=U}break;case"elst":{const k=this.currentTrack;if(!k)break;const N=ie(e);e.skip(3);let E=!1,F=0;const G=K(e);for(let U=0;U<G;U++){const z=N===1?ut(e):K(e),R=N===1?Fh(e):Tr(e),V=mr(e);if(z!==0){if(E){ue._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(R===-1){F+=z;continue}if(V!==1){ue._warn("Unsupported edit list entry: media rate must be 1.");break}k.editListPreviousSegmentDurations=F,k.editListOffset=R,E=!0}}}break;case"mdhd":{const k=this.currentTrack;if(!k)break;const N=ie(e);e.skip(3),N===0?(e.skip(8),k.timescale=K(e),k.durationInMediaTimescale=K(e)):N===1&&(e.skip(16),k.timescale=K(e),k.durationInMediaTimescale=ut(e));let E=Oe(e);if(E>0){k.languageCode="";for(let F=0;F<3;F++)k.languageCode=String.fromCharCode(96+(E&31))+k.languageCode,E>>=5;Ms(k.languageCode)||(k.languageCode=He)}}break;case"hdlr":{const k=this.currentTrack;if(!k)break;e.skip(8);const N=Re(e,4);N==="vide"?k.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}:N==="soun"&&(k.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const k=this.currentTrack;if(!k)break;k.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(n,i.contentSize))}break;case"stsd":{const k=this.currentTrack;if(!k||k.info===null||k.sampleTable)break;const N=ie(e);e.skip(3);const E=K(e);for(let F=0;F<E;F++){const G=e.filePos,U=ar(e);if(!U)break;k.internalCodecId=U.name;const z=U.name.toLowerCase();if(k.info.type==="video"){e.skip(24),k.info.width=Oe(e),k.info.height=Oe(e),k.info.squarePixelWidth=k.info.width,k.info.squarePixelHeight=k.info.height,e.skip(50),k.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,G+U.totalSize-e.filePos));const R=z==="encv"?k.frmaCodecString:z;k.frmaCodecString=null,R==="avc1"||R==="avc3"?(k.info.codec="avc",k.info.avcType=R==="avc1"?1:3):R==="hvc1"||R==="hev1"?k.info.codec="hevc":R==="vp08"?k.info.codec="vp8":R==="vp09"?k.info.codec="vp9":R==="av01"?k.info.codec="av1":vr.includes(z)?(k.info.codec="prores",k.info.proresFormat=z):R===null?ue._warn("Unknown encrypted video codec due to missing frma box."):ue._warn(`Unsupported video codec (sample entry type '${U.name}').`)}else{e.skip(8);const R=Oe(e);e.skip(6);let V=Oe(e),j=Oe(e);e.skip(4);let ne=K(e)/65536,we=null;N===0&&R>0&&(R===1?(e.skip(4),j=8*K(e),e.skip(8)):R===2&&(e.skip(4),ne=Uc(e),V=K(e),e.skip(4),j=K(e),we=K(e),e.skip(8))),k.info.numberOfChannels=V,k.info.sampleRate=ne,k.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,G+U.totalSize-e.filePos));const ee=z==="enca"?k.frmaCodecString:z;if(k.frmaCodecString=null,ee!=="mp4a")if(ee==="opus")k.info.codec="opus",k.info.sampleRate=kn;else if(ee==="flac")k.info.codec="flac";else if(ee==="ulaw")k.info.codec="ulaw";else if(ee==="alaw")k.info.codec="alaw";else if(ee==="ac-3")k.info.codec="ac3";else if(ee==="ec-3")k.info.codec="eac3";else if(ee==="twos")j===8?k.info.codec="pcm-s8":j===16?k.info.codec=k.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(ue._warn(`Unsupported sample size ${j} for codec 'twos'.`),k.info.codec=null);else if(ee==="sowt")j===8?k.info.codec="pcm-s8":j===16?k.info.codec="pcm-s16":(ue._warn(`Unsupported sample size ${j} for codec 'sowt'.`),k.info.codec=null);else if(ee==="raw ")k.info.codec="pcm-u8";else if(ee==="in24")k.info.codec=k.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(ee==="in32")k.info.codec=k.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(ee==="fl32")k.info.codec=k.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(ee==="fl64")k.info.codec=k.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(ee==="ipcm"){const he=k.info.pcmSampleSize;k.info.pcmLittleEndian?he===16?k.info.codec="pcm-s16":he===24?k.info.codec="pcm-s24":he===32?k.info.codec="pcm-s32":(ue._warn(`Invalid ipcm sample size ${he}.`),k.info.codec=null):he===16?k.info.codec="pcm-s16be":he===24?k.info.codec="pcm-s24be":he===32?k.info.codec="pcm-s32be":(ue._warn(`Invalid ipcm sample size ${he}.`),k.info.codec=null)}else if(ee==="fpcm"){const he=k.info.pcmSampleSize;k.info.pcmLittleEndian?he===32?k.info.codec="pcm-f32":he===64?k.info.codec="pcm-f64":(ue._warn(`Invalid fpcm sample size ${he}.`),k.info.codec=null):he===32?k.info.codec="pcm-f32be":he===64?k.info.codec="pcm-f64be":(ue._warn(`Invalid fpcm sample size ${he}.`),k.info.codec=null)}else if(ee==="lpcm"&&we!==null){const he=j+7>>3,lt=!!(we&1),Ot=!!(we&2),Mr=we&4?-1:0;j>0&&j<=64&&(lt?j===32&&(k.info.codec=Ot?"pcm-f32be":"pcm-f32"):Mr&1<<he-1?he===1?k.info.codec="pcm-s8":he===2?k.info.codec=Ot?"pcm-s16be":"pcm-s16":he===3?k.info.codec=Ot?"pcm-s24be":"pcm-s24":he===4&&(k.info.codec=Ot?"pcm-s32be":"pcm-s32"):he===1&&(k.info.codec="pcm-u8")),k.info.codec===null&&ue._warn("Unsupported PCM format.")}else ee===null?ue._warn("Unknown encrypted audio codec due to missing frma box."):ue._warn(`Unsupported audio codec (sample entry type '${U.name}').`)}e.filePos=G+U.totalSize}}break;case"frma":{const k=this.currentTrack;if(!k)break;const E=Re(e,4).toLowerCase();k.frmaCodecString=E}break;case"schm":{const k=this.currentTrack;if(!k)break;e.skip(4);const N=Re(e,4);
241N==="cenc"||N==="cens"||N==="cbcs"?k.encryptionInfo={scheme:N,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:ue._warn(`Unsupported encryption scheme '${N}'.`)}break;case"tenc":{const k=this.currentTrack;if(!k||!k.encryptionInfo)break;const N=ie(e);e.skip(3),e.skip(1);const E=ie(e);if(N>0?(k.encryptionInfo.defaultCryptByteBlock=E>>4,k.encryptionInfo.defaultSkipByteBlock=E&15):(k.encryptionInfo.defaultCryptByteBlock=0,k.encryptionInfo.defaultSkipByteBlock=0),k.encryptionInfo.defaultIsProtected=ie(e)!==0,k.encryptionInfo.defaultPerSampleIvSize=ie(e),k.encryptionInfo.defaultKid=Ti(se(e,16)),k.encryptionInfo.defaultIsProtected&&k.encryptionInfo.defaultPerSampleIvSize===0){const F=ie(e),G=new Uint8Array(16);G.set(se(e,F),0),k.encryptionInfo.defaultConstantIv=G}}break;case"avcC":{const k=this.currentTrack;if(!k)break;g(k.info),k.info.codecDescription=se(e,i.contentSize)}break;case"hvcC":{const k=this.currentTrack;if(!k)break;g(k.info),k.info.codecDescription=se(e,i.contentSize)}break;case"vpcC":{const k=this.currentTrack;if(!k)break;g(((a=k.info)==null?void 0:a.type)==="video"),e.skip(4);const N=ie(e),E=ie(e),F=ie(e),G=F>>4,U=F>>1&7,z=F&1,R=ie(e),V=ie(e),j=ie(e);k.info.vp9CodecInfo={profile:N,level:E,bitDepth:G,chromaSubsampling:U,videoFullRangeFlag:z,colourPrimaries:R,transferCharacteristics:V,matrixCoefficients:j}}break;case"av1C":{const k=this.currentTrack;if(!k)break;g(((o=k.info)==null?void 0:o.type)==="video"),e.skip(1);const N=ie(e),E=N>>5,F=N&31,G=ie(e),U=G>>7,z=G>>6&1,R=G>>5&1,V=G>>4&1,j=G>>3&1,ne=G>>2&1,we=G&3,ee=E===2&&z?R?12:10:z?10:8;k.info.av1CodecInfo={profile:E,level:F,tier:U,bitDepth:ee,monochrome:V,chromaSubsamplingX:j,chromaSubsamplingY:ne,chromaSamplePosition:we}}break;case"colr":{const k=this.currentTrack;if(!k)break;g(((c=k.info)==null?void 0:c.type)==="video");const N=Re(e,4);
241if(N!=="nclx"&&N!=="nclc")break;const E=Oe(e),F=Oe(e),G=Oe(e);let U;N==="nclx"&&(U=!!(ie(e)&128)),k.info.colorSpace={primaries:Gi[E],transfer:Xi[F],matrix:Qi[G],fullRange:U}}break;case"pasp":{const k=this.currentTrack;if(!k)break;g(((l=k.info)==null?void 0:l.type)==="video");const N=K(e),E=K(e);N>0&&E>0&&(N>E?k.info.squarePixelWidth=Math.round(k.info.width*N/E):k.info.squarePixelHeight=Math.round(k.info.height*E/N))}break;case"wave":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"esds":{const k=this.currentTrack;if(!k)break;g(((u=k.info)==null?void 0:u.type)==="audio"),e.skip(4);const N=ie(e);g(N===3),Vn(e),e.skip(2);const E=ie(e),F=(E&128)!==0,G=(E&64)!==0,U=(E&32)!==0;if(F&&e.skip(2),G){const ne=ie(e);e.skip(ne)}U&&e.skip(2);const z=ie(e);g(z===4);const R=Vn(e),V=e.filePos,j=ie(e);if(j===64||j===103?(k.info.codec="aac",k.info.aacCodecInfo={isMpeg2:j===103,objectType:null}):j===105||j===107?k.info.codec="mp3":j===221?k.info.codec="vorbis":ue._warn(`Unsupported audio codec (objectTypeIndication ${j}) - discarding track.`),e.skip(12),R>e.filePos-V){const ne=ie(e);g(ne===5);const we=Vn(e);if(k.info.codecDescription=se(e,we),k.info.codec==="aac"){const ee=Ns(k.info.codecDescription);ee.numberOfChannels!==null&&(k.info.numberOfChannels=ee.numberOfChannels),ee.sampleRate!==null&&(k.info.sampleRate=ee.sampleRate)}}}break;case"enda":{const k=this.currentTrack;if(!k)break;g(((d=k.info)==null?void 0:d.type)==="audio"),k.info.pcmLittleEndian=!!(Oe(e)&255)}break;case"pcmC":{const k=this.currentTrack;if(!k)break;g(((f=k.info)==null?void 0:f.type)==="audio"),e.skip(4);const N=ie(e);k.info.pcmLittleEndian=!!(N&1),k.info.pcmSampleSize=ie(e)}break;case"dOps":{const k=this.currentTrack;if(!k)break;g(((m=k.info)==null?void 0:m.type)==="audio"),e.skip(1);const N=ie(e),E=Oe(e),F=K(e),G=Ps(e),U=ie(e);let z;U!==0?z=se(e,2+N):z=new Uint8Array(0);const R=new Uint8Array(19+z.byteLength),V=new DataView(R.buffer);V.setUint32(0,1332770163,!1),V.setUint32(4,1214603620,!1),V.setUint8(8,1),V.setUint8(9,N),V.setUint16(10,E,!0),V.setUint32(12,F,!0),V.setInt16(16,G,!0),V.setUint8(18,U),R.set(z,19),k.info.codecDescription=R,k.info.numberOfChannels=N}break;case"dfLa":{const k=this.currentTrack;if(!k)break;g(((p=k.info)==null?void 0:p.type)==="audio"),e.skip(4);const N=127,E=128,F=e.filePos;for(;e.filePos<s;){const V=ie(e),j=Ut(e);if((V&N)===Qr.STREAMINFO){e.skip(10);const we=K(e),ee=we>>>12,he=(we>>9&7)+1;k.info.sampleRate=ee,k.info.numberOfChannels=he,e.skip(20)}else e.skip(j);if(V&E)break}const G=e.filePos;e.filePos=F;const U=se(e,G-F),z=new Uint8Array(4+U.byteLength);new DataView(z.buffer).setUint32(0,1716281667,!1),z.set(U,4),k.info.codecDescription=z}break;case"dac3":{const k=this.currentTrack;if(!k)break;g(((h=k.info)==null?void 0:h.type)==="audio");const N=se(e,3),E=new Se(N),F=E.readBits(2);E.skipBits(8);const G=E.readBits(3),U=E.readBits(1);F<3&&(k.info.sampleRate=yn[F]),k.info.numberOfChannels=Ks[G]+U}break;case"dec3":{const k=this.currentTrack;if(!k)break;g(((b=k.info)==null?void 0:b.type)==="audio");const N=se(e,i.contentSize),E=Fd(N);if(!E){ue._warn("Invalid dec3 box contents, ignoring.");break}const F=$o(E);F!==null&&(k.info.sampleRate=F),k.info.numberOfChannels=jo(E)}break;case"stts":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const N=K(e);let E=0,F=0;for(let G=0;G<N;G++){const U=K(e),z=K(e);k.sampleTable.sampleTimingEntries.push({startIndex:E,startDecodeTimestamp:F,count:U,delta:z}),E+=U,F+=U*z}}break;case"ctts":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const N=K(e);let E=0;for(let F=0;F<N;F++){const G=K(e),U=Tr(e);k.sampleTable.sampleCompositionTimeOffsets.push({startIndex:E,count:G,offset:U}),E+=G}}break;case"stsz":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const N=K(e),E=K(e);if(N===0)for(let F=0;F<E;F++){const G=K(e);k.sampleTable.sampleSizes.push(G)}else k.sampleTable.sampleSizes.push(N)}break;case"stz2":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4),e.skip(3);const N=ie(e),E=K(e),F=se(e,Math.ceil(E*N/8)),G=new Se(F);for(let U=0;U<E;U++){const z=G.readBits(N);k.sampleTable.sampleSizes.push(z)}}break;case"stss":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4),k.sampleTable.keySampleIndices=[];const N=K(e);for(let E=0;E<N;E++){const F=K(e)-1;k.sampleTable.keySampleIndices.push(F)}k.sampleTable.keySampleIndices[0]!==0&&k.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const N=K(e);for(let F=0;F<N;F++){const G=K(e)-1,U=K(e),z=K(e);k.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:G,samplesPerChunk:U,sampleDescriptionIndex:z})}let E=0;for(let F=0;F<k.sampleTable.sampleToChunk.length;F++)if(k.sampleTable.sampleToChunk[F].startSampleIndex=E,F<k.sampleTable.sampleToChunk.length-1){const U=k.sampleTable.sampleToChunk[F+1].startChunkIndex-k.sampleTable.sampleToChunk[F].startChunkIndex;E+=U*k.sampleTable.sampleToChunk[F].samplesPerChunk}}break;case"stco":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const N=K(e);for(let E=0;E<N;E++){const F=K(e);k.sampleTable.chunkOffsets.push(F)}}break;case"co64":{const k=this.currentTrack;if(!k||!k.sampleTable)break;e.skip(4);const N=K(e);for(let E=0;E<N;E++){const F=ut(e);k.sampleTable.chunkOffsets.push(F)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mehd":{const k=ie(e);e.skip(3);const N=k===1?ut(e):K(e);this.movieDurationInTimescale=N}break;case"trex":{e.skip(4);const k=K(e),N=K(e),E=K(e),F=K(e),G=K(e);this.fragmentTrackDefaults.push({trackId:k,defaultSampleDescriptionIndex:N,defaultSampleDuration:E,defaultSampleSize:F,defaultSampleFlags:G})}break;case"tfra":{const k=ie(e);e.skip(3);const N=K(e),E=this.tracks.find(ee=>ee.id===N);if(!E)break;const F=K(e),G=(F&48)>>4,U=(F&12)>>2,z=F&3,R=[ie,Oe,Ut,K],V=R[G],j=R[U],ne=R[z],we=K(e);for(let ee=0;ee<we;ee++){const he=k===1?ut(e):K(e),lt=k===1?ut(e):K(e);V(e),j(e),ne(e),E.fragmentLookupTable.push({timestamp:he,moofOffset:lt})}E.fragmentLookupTable.sort((ee,he)=>
241ee.timestamp-he.timestamp);for(let ee=0;ee<E.fragmentLookupTable.length-1;ee++){const he=E.fragmentLookupTable[ee],lt=E.fragmentLookupTable[ee+1];he.timestamp===lt.timestamp&&(E.fragmentLookupTable.splice(ee+1,1),ee--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:i.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(n,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(g(this.currentFragment),this.readContiguousBoxes(e.slice(n,i.contentSize)),this.currentTrack){const k=this.currentFragment.trackData.get(this.currentTrack.id);e:if(k){if(k.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}k.presentationTimestamps=k.samples.map((G,U)=>({presentationTimestamp:G.presentationTimestamp,sampleIndex:U})).sort((G,U)=>G.presentationTimestamp-U.presentationTimestamp);for(let G=0;G<k.presentationTimestamps.length;G++){const U=k.presentationTimestamps[G],z=k.samples[U.sampleIndex];if(k.firstKeyFrameTimestamp===null&&z.isKeyFrame&&(k.firstKeyFrameTimestamp=z.presentationTimestamp),G<k.presentationTimestamps.length-1){const V=k.presentationTimestamps[G+1].presentationTimestamp-U.presentationTimestamp;z.duration=V}}const N=k.samples[k.presentationTimestamps[0].sampleIndex],E=k.samples[Be(k.presentationTimestamps).sampleIndex];k.startTimestamp=N.presentationTimestamp,k.endTimestamp=E.presentationTimestamp+E.duration;const{currentFragmentState:F}=this.currentTrack;g(F),F.startTimestamp!==null&&(Ln(k,F.startTimestamp),k.startTimestampIsFinal=!0),F.encryptionAuxInfo&&!k.samples[0].encryption&&(k.encryptionAuxInfo=F.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if((y=this.input._formatOptions.isobmff)!=null&&y._suppressPsshParsing)break;const k=Go(se(e,i.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(k):this.currentTrack||this.psshBoxes.push(k)}break;case"tfhd":{g(this.currentFragment),e.skip(1);const k=Ut(e),N=!!(k&1),E=!!(k&2),F=!!(k&8),G=!!(k&16),U=!!(k&32),z=!!(k&65536),R=!!(k&131072),V=K(e),j=this.tracks.find(we=>we.id===V);if(!j)break;const ne=this.fragmentTrackDefaults.find(we=>we.trackId===V);this.currentTrack=j,j.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:(ne==null?void 0:ne.defaultSampleDescriptionIndex)??null,defaultSampleDuration:(ne==null?void 0:ne.defaultSampleDuration)??null,defaultSampleSize:(ne==null?void 0:ne.defaultSampleSize)??null,defaultSampleFlags:(ne==null?void 0:ne.defaultSampleFlags)??null,startTimestamp:null,encryptionAuxInfo:null},N?j.currentFragmentState.baseDataOffset=ut(e):R&&(j.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),E&&(j.currentFragmentState.sampleDescriptionIndex=K(e)),F&&(j.currentFragmentState.defaultSampleDuration=K(e)),G&&(j.currentFragmentState.defaultSampleSize=K(e)),U&&(j.currentFragmentState.defaultSampleFlags=K(e)),z&&(j.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const k=this.currentTrack;if(!k)break;g(k.currentFragmentState);const N=ie(e);e.skip(3);const E=N===0?K(e):ut(e);k.currentFragmentState.startTimestamp=E}break;case"trun":{const k=this.currentTrack;if(!k)break;g(this.currentFragment),g(k.currentFragmentState);const N=ie(e),E=Ut(e),F=!!(E&1),G=!!(E&4),U=!!(E&256),z=!!(E&512),R=!!(E&1024),V=!!(E&2048),j=K(e);let ne=null;F&&(ne=Tr(e));let we=null;G&&(we=K(e));let ee;this.currentFragment.trackData.has(k.id)?(ee=this.currentFragment.trackData.get(k.id),ne!==null&&(ee.currentOffset=k.currentFragmentState.baseDataOffset+ne)):(ee={track:k,currentTimestamp:0,currentOffset:k.currentFragmentState.baseDataOffset+(ne??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(k.id,ee));for(let he=0;he<j;he++){let lt;U?lt=K(e):(g(k.currentFragmentState.defaultSampleDuration!==null),lt=k.currentFragmentState.defaultSampleDuration);let Ot;z?Ot=K(e):(g(k.currentFragmentState.defaultSampleSize!==null),Ot=k.currentFragmentState.defaultSampleSize);let Mr;R?Mr=K(e):(g(k.currentFragmentState.defaultSampleFlags!==null),Mr=k.currentFragmentState.defaultSampleFlags),he===0&&we!==null&&(Mr=we);let An=0;V&&(N===0?An=K(e):An=Tr(e));const nl=!(Mr&65536);ee.samples.push({presentationTimestamp:ee.currentTimestamp+An,duration:lt,byteOffset:ee.currentOffset,byteSize:Ot,isKeyFrame:nl,encryption:null}),ee.currentOffset+=Ot,ee.currentTimestamp+=lt}this.currentFragment.implicitBaseDataOffset=ee.currentOffset}break;case"saiz":{const k=this.currentTrack;if(!k||!k.encryptionInfo)break;if(e.skip(1),Ut(e)&1){const z=Re(e,4),R=K(e);if(z!==k.encryptionInfo.scheme||R!==0)break}const E=ie(e),F=K(e);let G=null;E===0&&F>0&&(G=se(e,F));const U=xa(k);U.defaultSampleInfoSize=E,U.sampleSizes=G,U.sampleCount=F}break;case"saio":{const k=this.currentTrack;if(!k||!k.encryptionInfo)break;const N=ie(e);if(Ut(e)&1){const z=Re(e,4),R=K(e);if(z!==k.encryptionInfo.scheme||R!==0)break}const F=K(e);if(F===0)break;F>1&&ue._warn("Multiple saio entries are not supported; using the first offset only.");let G=N===0?K(e):Number(ut(e));this.currentFragment&&(G+=this.currentFragment.moofOffset);const U=xa(k);U.offset=G}break;case"senc":{const k=this.currentTrack;if(!k||!k.encryptionInfo)break;g(this.currentFragment);const N=this.currentFragment.trackData.get(k.id);if(!N)break;e.skip(1);const F=!!(Ut(e)&2),G=K(e),U=k.encryptionInfo.defaultPerSampleIvSize;g(U!==null);for(let z=0;z<Math.min(G,N.samples.length);z++){const R=new Uint8Array(16);U>0?R.set(se(e,U),0):R.set(k.encryptionInfo.defaultConstantIv,0);let V=null;if(F){const ne=Oe(e);V=[];for(let we=0;we<ne;we++){const ee=Oe(e),he=K(e);V.push({clearLen:ee,protectedLen:he})}}const j=N.samples[z];j.encryption={iv:R,subsamples:V}}}break;case"udta":{const k=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(const{boxInfo:N,slice:E}of k){if(N.name!=="meta"&&!this.currentTrack){const F=E.filePos;(x=this.metadataTags).raw??(x.raw={}),N.name[0]==="©"?(T=this.metadataTags.raw)[P=N.name]??(T[P]=Tt(E)):(_=this.metadataTags.raw)[S=N.name]??(_[S]=se(E,N.contentSize)),E.filePos=F}switch(N.name){case"meta":E.skip(-N.headerSize),this.traverseBox(E);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=Ye.decode(se(E,N.contentSize)):(I=this.metadataTags).title??(I.title=Tt(E));break;case"©des":this.currentTrack||((C=this.metadataTags).description??(C.description=Tt(E)));break;case"©ART":this.currentTrack||((v=this.metadataTags).artist??(v.artist=Tt(E)));break;case"©alb":this.currentTrack||((A=this.metadataTags).album??(A.album=Tt(E)));break;case"albr":this.currentTrack||((H=this.metadataTags).albumArtist??(H.albumArtist=Tt(E)));break;case"©gen":this.currentTrack||((M=this.metadataTags).genre??(M.genre=Tt(E)));break;case"©day":if(!this.currentTrack){const F=new Date(Tt(E));Number.isNaN(F.getTime())||((D=this.metadataTags).date??(D.date=F))}break;case"©cmt":this.currentTrack||(($=this.metadataTags).comment??($.comment=Tt(E)));break;case"©lyr":this.currentTrack||((B=this.metadataTags).lyrics??(B.lyrics=Tt(E)));break}}}break;case"meta":{if(this.currentTrack)break;const N=K(e)!==0;this.currentMetadataKeys=new Map,N?this.readContiguousBoxes(e.slice(n,i.contentSize)):this.readContiguousBoxes(e.slice(n+4,
241i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const k=K(e);for(let N=0;N<k;N++){const E=K(e);e.skip(4);const F=Ye.decode(se(e,E-8));this.currentMetadataKeys.set(N+1,F)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const k=this.iterateContiguousBoxes(e.slice(n,i.contentSize));for(const{boxInfo:N,slice:E}of k){let F=N.name;const G=(F.charCodeAt(0)<<24)+(F.charCodeAt(1)<<16)+(F.charCodeAt(2)<<8)+F.charCodeAt(3);this.currentMetadataKeys.has(G)&&(F=this.currentMetadataKeys.get(G));const U=Bd(E);switch((O=this.metadataTags).raw??(O.raw={}),(X=this.metadataTags.raw)[F]??(X[F]=U),F){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof U=="string"&&((ae=this.metadataTags).title??(ae.title=U));break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof U=="string"&&((ve=this.metadataTags).description??(ve.description=U));break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof U=="string"&&((Ie=this.metadataTags).artist??(Ie.artist=U));break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof U=="string"&&((ct=this.metadataTags).album??(ct.album=U));break;case"aART":case"album_artist":typeof U=="string"&&((de=this.metadataTags).albumArtist??(de.albumArtist=U));break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof U=="string"&&((qe=this.metadataTags).comment??(qe.comment=U));break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof U=="string"&&((xt=this.metadataTags).genre??(xt.genre=U));break;case"©lyr":case"lyrics":typeof U=="string"&&((Ft=this.metadataTags).lyrics??(Ft.lyrics=U));break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof U=="string"){const z=new Date(U);Number.isNaN(z.getTime())||((Bt=this.metadataTags).date??(Bt.date=z))}break;case"covr":case"com.apple.quicktime.artwork":U instanceof Xr?((Rt=this.metadataTags).images??(Rt.images=[]),this.metadataTags.images.push({data:U.data,kind:"coverFront",mimeType:U.mimeType})):U instanceof Uint8Array&&((Mt=this.metadataTags).images??(Mt.images=[]),this.metadataTags.images.push({data:U,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof U=="string"){const z=U.split("/"),R=Number.parseInt(z[0],10),V=z[1]&&Number.parseInt(z[1],10);Number.isInteger(R)&&R>0&&((pt=this.metadataTags).trackNumber??(pt.trackNumber=R)),V&&Number.isInteger(V)&&V>0&&((te=this.metadataTags).tracksTotal??(te.tracksTotal=V))}break;case"trkn":if(U instanceof Uint8Array&&U.length>=6){const z=_e(U),R=z.getUint16(2,!1),V=z.getUint16(4,!1);R>0&&((J=this.metadataTags).trackNumber??(J.trackNumber=R)),V>0&&((Te=this.metadataTags).tracksTotal??(Te.tracksTotal=V))}break;case"disc":case"disk":if(U instanceof Uint8Array&&U.length>=6){const z=_e(U),R=z.getUint16(2,!1),V=z.getUint16(4,!1);R>0&&((ge=this.metadataTags).discNumber??(ge.discNumber=R)),V>0&&((ce=this.metadataTags).discsTotal??(ce.discsTotal=V))}break}}}break}return e.filePos=s,!0}}class Jo{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const n of e.tracks)if(n.trackBacking.getType()===t&&i++,n===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;g(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});
241return((t==null?void 0:t.timestamp)??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return _i(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=ks(n,i),a=await this.fetchPacketForSampleIndex(s,t);return!wa(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=ye(c.presentationTimestamps,i,f=>f.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,t)}async getNextPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,t);const n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const a=s.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<a.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Od(n,i),a=await this.fetchPacketForSampleIndex(s,t);return!wa(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=Bs(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=i),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,t)}async getNextKeyPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Nd(s,i);return this.fetchPacketForSampleIndex(a,t)}const n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>n.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return g(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Dd(i,e);if(!n)return null;let s;if(t.metadataOnly)s=ot;else{let l=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(l instanceof Promise&&(l=await l),!l)return null;if(s=se(l,n.sampleSize),this.internalTrack.encryptionAuxInfo){g(this.internalTrack.encryptionInfo);const u=await ec(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<u.length&&(s=await Ta(this.internalTrack,u[e],s,null))}}const a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,c=new Ae(s,n.isKeyFrame?"key":"delta",a,o,e,n.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,i){if(t===-1)return null;const s=e.trackData.get(this.internalTrack.id).samples[t];g(s);let a;if(i.metadataOnly)a=ot;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(u instanceof Promise&&(u=await u),!u)return null;
241a=se(u,s.byteSize),s.encryption&&(a=await Ta(this.internalTrack,s.encryption,a,e))}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new Ae(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,i,n,s){const a=this.internalTrack.demuxer;let o=null,c=null,l=-1;if(e){const{sampleIndex:b,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,b,s);b!==-1&&(c=e,l=b)}const u=ye(this.internalTrack.fragmentLookupTable,i,b=>b.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,f=ye(this.internalTrack.fragmentPositionCache,i,b=>b.startTimestamp),m=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max((d==null?void 0:d.moofOffset)??0,(m==null?void 0:m.moofOffset)??0)||null;let h;for(e?p===null||e.moofOffset>=p?(h=e.moofOffset+e.moofSize,o=e):h=p:h=p??0;;){if(o){const T=o.trackData.get(this.internalTrack.id);if(T&&T.startTimestamp>n)break}let b=a.reader.requestSliceRange(h,$t,wr);if(b instanceof Promise&&(b=await b),!b)break;const y=h,x=ar(b);if(!x)break;if(x.name==="moof"){o=await a.readFragment(y);const{sampleIndex:T,correctSampleFound:P}=t(o);if(P)return this.fetchPacketInFragment(o,T,s);T!==-1&&(c=o,l=T)}h=y+x.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){const b=this.internalTrack.fragmentLookupTable[u-1];g(!b||b.timestamp<d.timestamp);const y=(b==null?void 0:b.timestamp)??-1/0;return this.performFragmentedLookup(null,t,y,n,s)}return c?this.fetchPacketInFragment(c,l,s):null}}class ka extends Jo{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){var e,t,i,n;return{primaries:(e=this.internalTrack.info.colorSpace)==null?void 0:e.primaries,transfer:(t=this.internalTrack.info.colorSpace)==null?void 0:t.transfer,matrix:(i=this.internalTrack.info.colorSpace)==null?void 0:i.matrix,fullRange:(n=this.internalTrack.info.colorSpace)==null?void 0:n.fullRange}}
241async canBeTransparent(){return this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&No(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Vo(t.data)}const e={codec:Vs(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})()):null}}class ya extends Jo{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:Ls(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}const ks=(r,e)=>{if(r.presentationTimestamps){const t=ye(r.presentationTimestamps,e,i=>i.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{const t=ye(r.sampleTimingEntries,e,n=>n.startDecodeTimestamp);if(t===-1)return-1;const i=r.sampleTimingEntries[t];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},Od=(r,e)=>{if(!r.keySampleIndices)return ks(r,e);if(r.presentationTimestamps){const t=ye(r.presentationTimestamps,e,i=>i.presentationTimestamp);if(t===-1)return-1;for(let i=t;i>=0;i--){const n=r.presentationTimestamps[i].sampleIndex;if(Ei(r.keySampleIndices,n,a=>a)!==-1)return n}return-1}else{const t=ks(r,e),i=ye(r.keySampleIndices,t,n=>n);return r.keySampleIndices[i]??-1}},Dd=(r,e)=>{const t=ye(r.sampleTimingEntries,e,y=>y.startIndex),i=r.sampleTimingEntries[t];if(!i||i.startIndex+i.count<=e)return null;let s=i.startDecodeTimestamp+(e-i.startIndex)*i.delta;
241const a=ye(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);const c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=ye(r.sampleToChunk,e,y=>y.startSampleIndex),u=r.sampleToChunk[l];g(u);const d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),f=r.chunkOffsets[d],m=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let p=0,h=f;if(r.sampleSizes.length===1)h+=c*(e-m),p+=c*u.samplesPerChunk;else for(let y=m;y<m+u.samplesPerChunk;y++){const x=r.sampleSizes[y];y<e&&(h+=x),p+=x}let b=i.delta;if(r.presentationTimestamps){const y=r.presentationTimestampIndexMap[e];g(y!==void 0),y<r.presentationTimestamps.length-1&&(b=r.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:b,sampleOffset:h,sampleSize:c,chunkOffset:f,chunkSize:p,isKeyFrame:r.keySampleIndices?Ei(r.keySampleIndices,e,y=>y)!==-1:!0}},Nd=(r,e)=>{if(!r.keySampleIndices)return e+1;const t=ye(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t+1]??-1},Ln=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(const t of r.samples)t.presentationTimestamp+=e;for(const t of r.presentationTimestamps)t.presentationTimestamp+=e},Ud=r=>{const[e,t]=r,i=Math.atan2(t,e);return Number.isFinite(i)?i*(180/Math.PI):0},wa=r=>r.sampleSizes.length===0,xa=r=>{var e;return r.currentFragmentState?(e=r.currentFragmentState).encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):r.encryptionAuxInfo??(r.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},ec=async(r,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let i=0;if(t.defaultSampleInfoSize>
2410)i=t.defaultSampleInfoSize*t.sampleCount;else{g(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)i+=t.sampleSizes[o]}let n=r.requestSlice(t.offset,i);if(n instanceof Promise&&(n=await n),!n)throw new Error("Failed to read auxiliary encryption info.");const s=e.defaultPerSampleIvSize;g(s!==null);const a=[];for(let o=0;o<t.sampleCount;o++){const c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],l=new Uint8Array(16);s>0?l.set(se(n,s),0):l.set(e.defaultConstantIv,0);let u=null;if(c>s){const d=Oe(n);u=[];for(let f=0;f<d;f++){const m=Oe(n),p=K(n);u.push({clearLen:m,protectedLen:p})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},Ta=async(r,e,t,i)=>{var c;g(r.encryptionInfo);const n=r.encryptionInfo;g(n.defaultKid!==null);const s=n.defaultKid;let a;const o=r.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!((c=r.demuxer.input._formatOptions.isobmff)!=null&&c.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const l=(async()=>{let u=r.demuxer.psshBoxes;if(i){u=[...u,...i.psshBoxes].filter(f=>f.keyIds===null||f.keyIds.includes(s));for(let f=0;f<u.length-1;f++)for(let m=f+1;m<u.length;m++)Xo(u[f],u[m])&&(u.splice(m,1),m--)}const d=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:u});if(!(typeof d=="string"&&d.length===32&&Ru.test(d)||d instanceof Uint8Array&&d.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return d instanceof Uint8Array?d:Mu(d)})();r.demuxer.decryptionKeyCache.set(s,l),a=await l}return n.scheme==="cenc"||n.scheme==="cens"?Vd(a,n,e,t):Ld(a,n,e,t)},Vd=async(r,e,t,i)=>{const n=new Uint8Array(16);n.set(t.iv,0);const s=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const h=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,p);return new Uint8Array(h)};if(!t.subsamples)return a(i);g(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=tc(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock);let c=0;for(const p of o)for(const h of p.perSubsample)c+=h.length;const l=new Uint8Array(c);let u=0;for(const p of o)for(const h of p.perSubsample)l.set(i.subarray(h.offset,h.offset+h.length),u),u+=h.length;const d=await a(l),f=new Uint8Array(i);let m=0;for(const p of o)for(const h of p.perSubsample)f.set(d.subarray(m,m+h.length),h.offset),m+=h.length;return f},Ld=(r,e,t,i)=>{const n=new Zo;n.init({key:r,iv:t.iv});const s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(g(s!==null&&a!==null),!t.subsamples){const u=new Uint8Array(i),d=Math.floor(i.length/16);for(let f=0;f<d;f++){const m=f*16;n.in.set(i.subarray(m,m+16)),n.decrypt(),u.set(n.out,m)}return u}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(i),c=tc(t.subsamples,s,a),l=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(const u of c){n.iv[0]=l.getUint32(0,!1),n.iv[1]=l.getUint32(4,!1),n.iv[2]=l.getUint32(8,!1),n.iv[3]=l.getUint32(12,!1);for(const d of u.perSubsample){const f=d.length/16;for(let m=0;m<f;m++){const p=d.offset+m*16;n.in.set(i.subarray(p,p+16)),n.decrypt(),o.set(n.out,p)}}}return o},tc=(r,e,t)=>{const i=[],n=e!==0||t!==0;let s=0;for(const a of r){s+=a.clearLen;const o=[];if(!n)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let c=a.protectedLen,l=s;for(;c>0&&!(c<16*e);){const u=16*e;o.push({offset:l,length:u}),l+=u,c-=u;const d=Math.min(16*t,c);l+=d,c-=d}s+=a.protectedLen}i.push({perSubsample:o})}return i};/*! 242 * Copyright (c) 2026-present, Vanilagy and contributors 243 * 244 * This Source Code Form is subject to the terms of the Mozilla Public 245 * License, v. 2.0. If a copy of the MPL was not distributed with this 246 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 247 */var W;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=2
2471934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(W||(W={}));const Wd=[W.EBML,W.Segment],Pi=[W.SeekHead,W.Info,W.Cluster,W.Tracks,W.Cues,W.Attachments,W.Chapters,W.Tags],qi=[...Wd,...Pi],ys=8,dt=2,jt=2*ys,rc=r=>{if(r.remainingLength<1)return null;const e=ie(r);if(r.skip(-1),e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;return r.remainingLength<t?null:t},pi=r=>{if(r.remainingLength<1)return null;const e=ie(r);if(e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;if(r.remainingLength<t-1)return null;let n=e&i-1;for(let s=1;s<t;s++)n*=256,n+=ie(r);return n},me=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let i=0;i<e;i++)t*=256,t+=ie(r);return t},Hd=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let i=0;i<e;i++)t<<=8n,t+=BigInt(ie(r));return t},Xs=r=>{const e=rc(r);return e===null||r.remainingLength<e?null:me(r,e)},ic=r=>{if(r.remainingLength<1)return null;if(ie(r)===255)return;r.skip(-1);const t=pi(r);if(t===null)return null;if(t!==72057594037927940)return t},Ht=r=>{g(r.remainingLength>=dt);const e=Xs(r);if(e===null)return null;const t=ic(r);return t===null?null:{id:e,size:t}},Hr=(r,e)=>{const t=se(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return String.fromCharCode(...t.subarray(0,i))},si=(r,e)=>{const t=se(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return Ye.decode(t.subarray(0,i))},Wn=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Rh(r):Uc(r)},ws=async(r,e,t,i)=>{const n=new Set(t);let s=e;for(;i===null||s<i;){let a=r.requestSliceRange(s,dt,jt);if(a instanceof Promise&&(a=await a),!a)break;const o=Ht(a);if(!o)break;if(n.has(o.id))return{pos:s,found:!0};sr(o.size),s=a.filePos+o.size}return{pos:i!==null&&i>s?i:s,found:!1}},nc=async(r,e,t,i)=>{const s=new Set(t);let a=e;for(;a<i;){let o=r.requestSliceRange(a,0,Math.min(65536,i-a));if(o instanceof Promise&&(o=await o),!o||o.length<ys)break;for(let c=0;c<o.length-ys;c++){o.filePos=a;const l=Xs(o);if(l!==null&&s.has(l))return a;a++}}return null},Je={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3"};function sr(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}/*! 248 * Copyright (c) 2026-present, Vanilagy and contributors 249 * 250 * This Source Code Form is subject to the terms of the Mozilla Public 251 * License, v. 2.0. If a copy of the MPL was not distributed with this 252 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 253 */const qd=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>
2530){const i=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};/*! 254 * Copyright (c) 2026-present, Vanilagy and contributors 255 * 256 * This Source Code Form is subject to the terms of the Mozilla Public 257 * License, v. 2.0. If a copy of the MPL was not distributed with this 258 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 259 */var Vt;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Vt||(Vt={}));var sn;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(sn||(sn={}));var ki;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(ki||(ki={}));const Hn=[{id:W.SeekHead,flag:"seekHeadSeen"},{id:W.Info,flag:"infoSeen"},{id:W.Tracks,flag:"tracksSeen"},{id:W.Cues,flag:"cuesSeen"}],sc=10*2**20;class $d extends ir{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(n=>(n==null?void 0:n.codec)??null)));return qd({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(n=>{var s;return((s=n.info)==null?void 0:s.type)==="video"})),hasAudio:this.segments.some(i=>i.tracks.some(n=>{var s;return((s=n.info)==null?void 0:s.type)==="audio"})),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,dt,jt);if(t instanceof Promise&&(t=await t),!t)break;const i=Ht(t);if(!i)break;const n=i.id;let s=i.size;const a=t.filePos;if(n===W.EBML){sr(s);let o=this.reader.requestSlice(a,s);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(n===W.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(n===W.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await ws(this.reader,a,qi,this.reader.fileSize)).pos-a);const o=Be(this.segments);o&&(o.elementEndPos=a+s)}sr(s),e=a+s}})())}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(i,dt,jt);if(o instanceof Promise&&(o=await o),!o)break;const c=i,l=Ht(o);if(!l||!Pi.includes(l.id)&&l.id!==W.Void){const p=await nc(this.reader,c,Pi,Math.min(this.currentSegment.elementEndPos??1/0,c+sc));if(p){i=p;continue}else break}const{id:u,size:d}=l,f=o.filePos,m=Hn.findIndex(p=>p.id===u);if(m!==-1){const p=Hn[m].flag;this.currentSegment[p]=!0,sr(d);let h=this.reader.requestSlice(f,d);h instanceof Promise&&(h=await h),h&&this.readContiguousElements(h)}else if(u===W.Tags||u===W.Attachments){u===W.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,sr(d);let p=this.reader.requestSlice(f,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===W.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;i=f+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=Hn.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,dt,jt);if(l instanceof Promise&&(l=await l),!l)continue;const u=Ht(l);
259if(!u)continue;const{id:d,size:f}=u;if(d!==c.id)continue;sr(f),this.currentSegment[c.flag]=!0;let m=this.reader.requestSlice(l.filePos,f);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);const n=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=n.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){const l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,t){var d;if(((d=t.lastReadCluster)==null?void 0:d.elementStartPos)===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,dt,jt);i instanceof Promise&&(i=await i),g(i);const n=e,s=Ht(i);g(s);const a=s.id;g(a===W.Cluster);let o=s.size;const c=i.filePos;o===void 0&&(o=(await ws(this.reader,c,qi,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const u={segment:t,elementStartPos:n,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const f=this.readContiguousElements(l,qi);u.elementEndPos=f}for(const[,f]of u.trackData){const m=f.track;g(f.blocks.length>0);let p=!1;for(let x=0;x<f.blocks.length;x++){const T=f.blocks[x];T.timestamp+=u.timestamp,p||(p=T.lacing!==Vt.None)}f.presentationTimestamps=f.blocks.map((x,T)=>({timestamp:x.timestamp,blockIndex:T})).sort((x,T)=>x.timestamp-T.timestamp);for(let x=0;x<f.presentationTimestamps.length;x++){const T=f.presentationTimestamps[x],P=f.blocks[T.blockIndex];if(f.firstKeyFrameTimestamp===null&&P.isKeyFrame&&(f.firstKeyFrameTimestamp=P.timestamp),x<f.presentationTimestamps.length-1){const _=f.presentationTimestamps[x+1];P.duration=_.timestamp-P.timestamp}else P.duration===0&&m.defaultDuration!=null&&P.lacing===Vt.None&&(P.duration=m.defaultDuration)}p&&(this.expandLacedBlocks(f.blocks,m),f.presentationTimestamps=f.blocks.map((x,T)=>({timestamp:x.timestamp,blockIndex:T})).sort((x,T)=>x.timestamp-T.timestamp));const h=f.blocks[f.presentationTimestamps[0].blockIndex],b=f.blocks[Be(f.presentationTimestamps).blockIndex];f.startTimestamp=h.timestamp,f.endTimestamp=b.timestamp+b.duration;const y=ye(m.clusterPositionCache,f.startTimestamp,x=>x.startTimestamp);(y===-1||m.clusterPositionCache[y].elementStartPos!==n)&&m.clusterPositionCache.splice(y+1,0,{elementStartPos:u.elementStartPos,startTimestamp:f.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const n=e.segment.tracks.find(s=>s.id===t);if(!n)return null;i={track:n,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.lacing===Vt.None)continue;n.decoded||(n.data=this.decodeBlockData(t,n.data),n.decoded=!0);const s=at.tempFromBytes(n.data),a=[],o=ie(s)+1;switch(n.lacing){case Vt.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){const f=ie(s);if(d+=f,f<255){a.push(d),l+=d;break}}}a.push(s.length-(s.bufferPos+l))}break;case Vt.FixedSize:{const l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case Vt.Ebml:{const l=pi(s);g(l!==null);let u=l;a.push(u);let d=u;for(let f=1;f<o-1;f++){const m=s.bufferPos,p=pi(s);g(p!==null);const h=p,y=(1<<(s.bufferPos-m)*7-1)-1,x=h-y;u+=x,a.push(u),d+=u}a.push(s.length-(s.bufferPos+d))}break;default:g(!1)}g(a.length===o),e.splice(i,1);const c=n.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){const u=a[l],d=se(s,u),f=n.timestamp+c*l/o,m=c/o;e.splice(i+l,0,{timestamp:f,duration:m,isKeyFrame:n.isKeyFrame,data:d,lacing:Vt.None,decoded:!0,postProcessed:!1,mainAdditional:n.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===W.Tags&&!e.tagsSeen)){if(!(t.id===W.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,dt,jt);if(i instanceof Promise&&(i=await i),!i)continue;const n=Ht(i);if(!n||n.id!==t.id)continue;const{size:s}=n;sr(s),g(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(i.filePos,s);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===W.Tags?e.tagsSeen=!0:t.id===W.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=dt;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}
259traverseElement(e,t){var o,c,l,u,d,f,m,p,h,b,y,x,T,P,_,S,I,C,v,A,H,M,D,$,B,O,X,ae,ve,Ie,ct,de,qe,xt,Ft,Bt,Rt,Mt,pt,te,J,Te,ge,ce,k,N;const i=Ht(e);if(!i||t&&t.includes(i.id))return!1;const{id:n,size:s}=i,a=e.filePos;switch(sr(s),n){case W.DocType:this.isWebM=Hr(e,s)==="webm";break;case W.Seek:{if(!this.currentSegment)break;const E={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(E),this.readContiguousElements(e.slice(a,s)),(E.id===-1||E.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case W.SeekID:{const E=(o=this.currentSegment)==null?void 0:o.seekEntries[this.currentSegment.seekEntries.length-1];if(!E)break;E.id=me(e,s)}break;case W.SeekPosition:{const E=(c=this.currentSegment)==null?void 0:c.seekEntries[this.currentSegment.seekEntries.length-1];if(!E)break;E.segmentPosition=me(e,s)}break;case W.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=me(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case W.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Wn(e,s)}break;case W.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...rr,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(E=>{var F;return((F=E.data)==null?void 0:F.type)!=="decompress"||E.scope!==sn.Block||E.data.algorithm!==ki.HeaderStripping})&&(ue._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const E=this.currentTrack.codecId.indexOf("/"),F=E===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,E);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){const U=this.currentTrack.info.displayWidth*this.currentTrack.info.height,z=this.currentTrack.info.displayHeight*this.currentTrack.info.width;U>0&&z>0&&(U>z?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*U/z):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*z/U))}if(this.currentTrack.codecId===Je.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Je.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(F===Je.vp8)this.currentTrack.info.codec="vp8";else if(F===Je.vp9)this.currentTrack.info.codec="vp9";else if(F===Je.av1)this.currentTrack.info.codec="av1";else if(F===Je.prores){const U=this.currentTrack.codecPrivate?Ye.decode(this.currentTrack.codecPrivate):"";vr.includes(U)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=U)}const G=this.currentTrack;this.currentTrack.trackBacking=new jd(G),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){F===Je.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Je.mp3?this.currentTrack.info.codec="mp3":F===Je.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=kn):F===Je.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPr
259ivate):F===Je.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):F===Je.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):F===Je.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));const G=this.currentTrack;this.currentTrack.trackBacking=new Kd(G),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case W.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=me(e,s)}break;case W.TrackType:{if(!this.currentTrack)break;const E=me(e,s);E===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1,proresFormat:null}:E===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case W.FlagEnabled:{if(!this.currentTrack)break;me(e,s)||(this.currentTrack=null)}break;case W.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!me(e,s)}break;case W.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!me(e,s)}break;case W.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!me(e,s)}break;case W.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!me(e,s)}break;case W.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!me(e,s)}break;case W.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!me(e,s)}break;case W.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Hr(e,s)}break;case W.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=se(e,s)}break;case W.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=me(e,s)}break;case W.Name:{if(!this.currentTrack)break;this.currentTrack.name=si(e,s)}break;case W.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Hr(e,s),Ms(this.currentTrack.languageCode)||(this.currentTrack.languageCode=He)}break;case W.LanguageBCP47:{if(!this.currentTrack)break;const F=Hr(e,s).split("-")[0];F?this.currentTrack.languageCode=F:this.currentTrack.languageCode=He,this.currentTrack.hasLanguageBcp47=!0}break;case W.Video:{if(((u=(l=this.currentTrack)==null?void 0:l.info)==null?void 0:u.type)!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case W.PixelWidth:{if(((f=(d=this.currentTrack)==null?void 0:d.info)==null?void 0:f.type)!=="video")break;this.currentTrack.info.width=me(e,s)}break;case W.PixelHeight:{if(((p=(m=this.currentTrack)==null?void 0:m.info)==null?void 0:p.type)!=="video")break;this.currentTrack.info.height=me(e,s)}break;case W.DisplayWidth:{if(((b=(h=this.currentTrack)==null?void 0:h.info)==null?void 0:b.type)!=="video")break;this.currentTrack.info.displayWidth=me(e,s)}break;case W.DisplayHeight:{if(((x=(y=this.currentTrack)==null?void 0:y.info)==null?void 0:x.type)!=="video")break;this.currentTrack.info.displayHeight=me(e,s)}break;case W.DisplayUnit:{if(((P=(T=this.currentTrack)==null?void 0:T.info)==null?void 0:P.type)!=="video")break;this.currentTrack.info.displayUnit=me(e,s)}break;case W.AlphaMode:{if(((S=(_=this.currentTrack)==null?void 0:_.info)==null?void 0:S.type)!=="video")break;this.currentTrack.info.alphaMode=me(e,s)===1}break;case W.Colour:{if(((C=(I=this.currentTrack)==null?void 0:I.info)==null?void 0:C.type)!=="video")break;
259this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,s))}break;case W.MatrixCoefficients:{if(((A=(v=this.currentTrack)==null?void 0:v.info)==null?void 0:A.type)!=="video"||!this.currentTrack.info.colorSpace)break;const E=me(e,s),F=Qi[E]??null;this.currentTrack.info.colorSpace.matrix=F}break;case W.Range:{if(((M=(H=this.currentTrack)==null?void 0:H.info)==null?void 0:M.type)!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=me(e,s)===2}break;case W.TransferCharacteristics:{if((($=(D=this.currentTrack)==null?void 0:D.info)==null?void 0:$.type)!=="video"||!this.currentTrack.info.colorSpace)break;const E=me(e,s),F=Xi[E]??null;this.currentTrack.info.colorSpace.transfer=F}break;case W.Primaries:{if(((O=(B=this.currentTrack)==null?void 0:B.info)==null?void 0:O.type)!=="video"||!this.currentTrack.info.colorSpace)break;const E=me(e,s),F=Gi[E]??null;this.currentTrack.info.colorSpace.primaries=F}break;case W.Projection:{if(((ae=(X=this.currentTrack)==null?void 0:X.info)==null?void 0:ae.type)!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case W.ProjectionPoseRoll:{if(((Ie=(ve=this.currentTrack)==null?void 0:ve.info)==null?void 0:Ie.type)!=="video")break;const F=-Wn(e,s);try{this.currentTrack.info.rotation=zs(F)}catch{}}break;case W.Audio:{if(((de=(ct=this.currentTrack)==null?void 0:ct.info)==null?void 0:de.type)!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case W.SamplingFrequency:{if(((xt=(qe=this.currentTrack)==null?void 0:qe.info)==null?void 0:xt.type)!=="audio")break;this.currentTrack.info.sampleRate=Wn(e,s)}break;case W.Channels:{if(((Bt=(Ft=this.currentTrack)==null?void 0:Ft.info)==null?void 0:Bt.type)!=="audio")break;this.currentTrack.info.numberOfChannels=me(e,s)}break;case W.BitDepth:{if(((Mt=(Rt=this.currentTrack)==null?void 0:Rt.info)==null?void 0:Mt.type)!=="audio")break;this.currentTrack.info.bitDepth=me(e,s)}break;case W.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case W.CueTime:this.currentCueTime=me(e,s);break;case W.CueTrackPositions:{if(this.currentCueTime===null)break;g(this.currentSegment);const E={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(E),this.readContiguousElements(e.slice(a,s)),(E.trackId===-1||E.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case W.CueTrack:{const E=(pt=this.currentSegment)==null?void 0:pt.cuePoints[this.currentSegment.cuePoints.length-1];if(!E)break;E.trackId=me(e,s)}break;case W.CueClusterPosition:{const E=(te=this.currentSegment)==null?void 0:te.cuePoints[this.currentSegment.cuePoints.length-1];if(!E)break;g(this.currentSegment),E.clusterPosition=this.currentSegment.dataStartPos+me(e,s)}break;case W.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=me(e,s)}break;case W.SimpleBlock:{if(!this.currentCluster)break;const E=pi(e);if(E===null)break;const F=this.getTrackDataInCluster(this.currentCluster,E);if(!F)break;const G=Ps(e),U=ie(e),z=U>>1&3;let R=!!(U&128);((J=F.track.info)==null?void 0:J.type)==="audio"&&F.track.info.codec&&(R=!0);const V=se(e,s-(e.filePos-a)),j=F.track.decodingInstructions.length>0;F.blocks.push({timestamp:G,duration:0,isKeyFrame:R,data:V,lacing:z,decoded:!j,postProcessed:!1,mainAdditional:null})}break;case W.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case W.Block:{if(!this.currentCluster)break;const E=pi(e);if(E===null)break;const F=this.getTrackDataInCluster(this.currentCluster,E);if(!F)break;const G=Ps(e),z=ie(e)>>1&3,R=se(e,s-(e.filePos-a)),V=F.track.decodingInstructions.length>0;this.currentBlock={timestamp:G,duration:0,isKeyFrame:!0,data:R,lacing:z,decoded:!V,postProcessed:!1,mainAdditional:null},F.blocks.push(this.currentBlock)}break;case W.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case W.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;
259case W.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=se(e,s)}break;case W.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=me(e,s)}break;case W.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=me(e,s)}break;case W.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case W.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case W.Targets:this.readContiguousElements(e.slice(a,s));break;case W.TargetTypeValue:me(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case W.TagTrackUID:case W.TagEditionUID:case W.TagChapterUID:case W.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case W.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case W.TagName:this.currentSimpleTagName=si(e,s);break;case W.TagString:{if(!this.currentSimpleTagName)break;const E=si(e,s);this.processTagValue(this.currentSimpleTagName,E)}break;case W.TagBinary:{if(!this.currentSimpleTagName)break;const E=se(e,s);this.processTagValue(this.currentSimpleTagName,E)}break;case W.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));const E=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(E.raw??(E.raw={}),E.raw[this.currentAttachedFile.fileUid.toString()]=new Po(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),(Te=this.currentAttachedFile.fileMediaType)!=null&&Te.startsWith("image/")&&this.currentAttachedFile.fileData){const F=this.currentAttachedFile.fileName;let G="unknown";if(F){const U=F.toLowerCase();U.startsWith("cover.")?G="coverFront":U.startsWith("back.")&&(G="coverBack")}E.images??(E.images=[]),E.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:G,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case W.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Hd(e,s)}break;case W.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=si(e,s)}break;
259case W.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Hr(e,s)}break;case W.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=se(e,s)}break;case W.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=si(e,s)}break;case W.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((E,F)=>F.order-E.order)}break;case W.ContentEncoding:this.currentDecodingInstruction={order:0,scope:sn.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case W.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=me(e,s)}break;case W.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=me(e,s)}break;case W.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:ki.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case W.ContentCompAlgo:{if(((ce=(ge=this.currentDecodingInstruction)==null?void 0:ge.data)==null?void 0:ce.type)!=="decompress")break;this.currentDecodingInstruction.data.algorithm=me(e,s)}break;case W.ContentCompSettings:{if(((N=(k=this.currentDecodingInstruction)==null?void 0:k.data)==null?void 0:N.type)!=="decompress")break;this.currentDecodingInstruction.data.settings=se(e,s)}break;case W.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,t){g(e.decodingInstructions.length>0);let i=t;for(const n of e.decodingInstructions)switch(g(n.data),n.data.type){case"decompress":switch(n.data.algorithm){case ki.HeaderStripping:if(n.data.settings&&n.data.settings.length>0){const s=n.data.settings,a=new Uint8Array(s.length+i.length);a.set(s,0),a.set(i,s.length),i=a}break}break}return i}processTagValue(e,t){var n,s;if(!((n=this.currentSegment)!=null&&n.metadataTags))return;const i=this.currentSegment.metadataTags;if(i.raw??(i.raw={}),(s=i.raw)[e]??(s[e]=t),typeof t=="string")switch(e.toLowerCase()){case"title":i.title??(i.title=t);break;case"description":i.description??(i.description=t);break;case"artist":i.artist??(i.artist=t);break;case"album":i.album??(i.album=t);break;case"album_artist":i.albumArtist??(i.albumArtist=t);break;case"genre":i.genre??(i.genre=t);break;case"comment":i.comment??(i.comment=t);break;case"lyrics":i.lyrics??(i.lyrics=t);break;case"date":{const a=new Date(t);Number.isNaN(a.getTime())||(i.date??(i.date=a))}break;case"track_number":case"part_number":{const a=t.split("/"),o=Number.parseInt(a[0],10),c=a[1]&&Number.parseInt(a[1],10);Number.isInteger(o)&&o>0&&(i.trackNumber??(i.trackNumber=o)),c&&Number.isInteger(c)&&c>0&&(i.tracksTotal??(i.tracksTotal=c))}break;case"disc_number":case"disc":{const a=t.split("/"),o=Number.parseInt(a[0],10),c=a[1]&&Number.parseInt(a[1],10);Number.isInteger(o)&&o>0&&(i.discNumber??(i.discNumber=o)),c&&Number.isInteger(c)&&c>0&&(i.discsTotal??(i.discsTotal=c))}break}}}class ac{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const n of e.segments)for(const s of n.tracks)if(s.trackBacking.getType()===t&&i++,s===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor;const i=await this.getFirstPacket({metadataOnly:!0});return t+=(i==null?void 0:i.timestamp)??0,t}
259async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return _i(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{const s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=ye(s.presentationTimestamps,i,l=>l.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){const s=n.trackData.get(this.internalTrack.id);if(i.blockIndex+1<s.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{const s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=Bs(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=i),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextKeyPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){const a=n.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>i.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const s=n.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){const a=s.blocks.findIndex(o=>o.isKeyFrame);return g(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){var d,f;if(t===-1)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(g(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if(((d=this.internalTrack.info)==null?void 0:d.codec)==="prores"&&!(s.data.length>=8&&s.data[4]===105&&s.data[5]===99&&s.data[6]===112&&s.data[7]===102)){const p=new Uint8Array(s.data.length+8);_e(p).setUint32(0,p.length,!1),p[4]=105,p[5]=99,p[6]=112,p[7]=102,p.set(s.data,8),s.data=p}s.postProcessed=!0}const a=i.metadataOnly?ot:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,l={};s.mainAdditional&&((f=this.internalTrack.info)==null?void 0:f.type)==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?ot:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);const u=new Ae(a,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,s.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,i,n,s){const{demuxer:a,segment:o}=this.internalTrack;let c=null,l=null,u=-1;if(e){const{blockIndex:y,correctBlockFound:x}=t(e);if(x)return this.fetchPacketInCluster(e,y,s);y!==-1&&(l=e,u=y)}const d=ye(this.internalTrack.cuePoints,i,y=>y.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,m=ye(this.internalTrack.clusterPositionCache,i,y=>y.startTimestamp),p=m!==-1?this.internalTrack.clusterPositionCache[m]:null,h=Math.max((f==null?void 0:f.clusterPosition)??0,(p==null?void 0:p.elementStartPos)??0)||null;let b;for(e?h===null||e.elementStartPos>=h?(b=e.elementEndPos,c=e):b=h:b=h??o.clusterSeekStartPos;o.elementEndPos===null||b<=o.elementEndPos-dt;){if(c){const C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>n)break}let y=a.reader.requestSliceRange(b,dt,jt);if(y instanceof Promise&&(y=await y),!y)break;const x=b,T=Ht(y);if(!T||!Pi.includes(T.id)&&T.id!==W.Void){const C=await nc(a.reader,x,Pi,Math.min(o.elementEndPos??1/0,x+sc));if(C){b=C;continue}else break}const P=T.id;let _=T.size;const S=y.filePos;
259if(P===W.Cluster){c=await a.readCluster(x,o),_=c.elementEndPos-S;const{blockIndex:C,correctBlockFound:v}=t(c);if(v)return this.fetchPacketInCluster(c,C,s);C!==-1&&(l=c,u=C)}_===void 0&&(g(P!==W.Cluster),_=(await ws(a.reader,S,qi,o.elementEndPos)).pos-S);const I=S+_;if(o.elementEndPos===null){let C=a.reader.requestSliceRange(I,dt,jt);if(C instanceof Promise&&(C=await C),!C)break;if(Xs(C)===W.Segment){o.elementEndPos=I;break}}b=I}if(f&&(!l||l.elementStartPos<f.clusterPosition)){const y=this.internalTrack.cuePoints[d-1];g(!y||y.time<f.time);const x=(y==null?void 0:y.time)??-1/0;return this.performClusterLookup(null,t,x,n,s)}return l?this.fetchPacketInCluster(l,u,s):null}}class jd extends ac{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){var e,t,i,n;return{primaries:(e=this.internalTrack.info.colorSpace)==null?void 0:e.primaries,transfer:(t=this.internalTrack.info.colorSpace)==null?void 0:t.transfer,matrix:(i=this.internalTrack.info.colorSpace)==null?void 0:i.matrix,fullRange:(n=this.internalTrack.info.colorSpace)==null?void 0:n.fullRange}}
259async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const i={codec:Vs({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?qs(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?js(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?No(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Vo(e.data):null,proresFormat:this.internalTrack.info.proresFormat}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i})()):null}}class Kd extends ac{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:Ls({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}/*! 260 * Copyright (c) 2026-present, Vanilagy and contributors 261 * 262 * This Source Code Form is subject to the terms of the Mozilla Public 263 * License, v. 2.0. If a copy of the MPL was not distributed with this 264 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 265 */const xs=async(r,e,t,i=null)=>{let s=e;for(;t===null||s<t;){const a=t!==null?Math.min(65536,t-s):65536;let o=r.requestSliceRange(s,Cr,a);if(o instanceof Promise&&(o=await o),!o||o.length<Cr)break;for(;o.remainingLength>=Cr;){const c=o.filePos,l=K(o),u=r.fileSize!==null?r.fileSize-s:null,d=Ws(l,u);if(d.header&&(!i||d.header.sampleRate===i.sampleRate&&d.header.mpegVersionId===i.mpegVersionId&&d.header.layer===i.layer&&vi(d.header.channel)===vi(i.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};/*! 266 * Copyright (c) 2026-present, Vanilagy and contributors 267 * 268 * This Source Code Form is subject to the terms of the Mozilla Public 269 * License, v. 2.0. If a copy of the MPL was not distributed with this 270 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 271 */class Gd extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new ii,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Xd(this)]})())}
271async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,ht);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=tr(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await xs(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=zo(t.mpegVersionId,t.channel);let n=this.reader.requestSlice(e.startPos+i,4);if(n instanceof Promise&&(n=await n),n){const o=K(n);if(o===Eo||o===Ao){if(!this.xingData){let l=this.reader.requestSlice(e.startPos+i+4,12);if(l instanceof Promise&&(l=await l),l){const u=se(l,12),d=_e(u),f=d.getUint32(0,!1);this.xingData={frameCount:f&rn.FrameCount?d.getUint32(4,!1):null,fileSize:f&rn.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,i=!1;for(;;){let n=this.reader.requestSlice(t,ht);if(n instanceof Promise&&(n=await n),!n)break;const s=tr(n);if(!s)break;i=!0;let a=this.reader.requestSlice(n.filePos,s.size);if(a instanceof Promise&&(a=await a),!a)break;In(a,s,this.metadataTags),t=n.filePos+s.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=ji){let n=this.reader.requestSlice(this.reader.fileSize-ji,ji);n instanceof Promise&&(n=await n),g(n),Re(n,3)==="TAG"&&Mh(n,this.metadataTags)}return this.metadataTags}finally{e()}}}class Xd{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(g(e.firstFrameHeader!==null),g(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){const t=md(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),i=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(i)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}
271async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return He}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.firstFrameHeader),vi(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...rr}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:vi(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=ot;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;n=se(s,i.dataSize)}return new Ae(n,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=Ei(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");const s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=ye(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,t);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*! 272 * Copyright (c) 2026-present, Vanilagy and contributors 273 * 274 * This Source Code Form is subject to the terms of the Mozilla Public 275 * License, v. 2.0. If a copy of the MPL was not distributed with this 276 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 277 */const oc=1399285583,Qd=79764919,cc=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Qd:e<<1;cc[r]=e>>>0&4294967295}const Yd=r=>{const e=_e(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let i=0;for(let n=0;n<r.length;n++){const s=r[n];i=(i<<8^cc[i>>>24^s])>>>0}return e.setUint32(22,t,!0),i},Zd=(r,e,t)=>{let i=0,n=null;if(r.length>0)if(e.codec==="vorbis"){g(e.vorbisInfo);const s=e.vorbisInfo.modeBlockflags.length,o=(1<<Vu(s-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t;const u=e.vorbisInfo.modeBlockflags[c];if(n=e.vorbisInfo.blocksizes[u],u===1){const d=(o|1)+1,f=r[0]&d?1:0;l=e.vorbisInfo.blocksizes[f]}i=l!==null?l+n>>2:0}else e.codec==="opus"&&(i=Id(r).durationInSamples);return{durationInSamples:i,vorbisBlockSize:n}},Jd=r=>{let e="audio/ogg";if(r.codecStrings){const t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};/*! 278 * Copyright (c) 2026-present, Vanilagy and contributors 279 * 280 * This Source Code Form is subject to the terms of the Mozilla Public 281 * License, v. 2.0. If a copy of the MPL was not distributed with this 282 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 283 */const xr=27,Yr=282,ef=Yr+65025,yi=r=>{const e=r.filePos;if($r(r)!==oc)return null;r.skip(1);const i=ie(r),n=Bh(r),s=$r(r),a=$r(r),o=$r(r),c=ie(r),l=new Uint8Array(c);for(let m=0;m<c;m++)l[m]=ie(r);const u=27+c,d=l.reduce((m,p)=>m+p,0),f=u+d;return{headerStartPos:e,totalSize:f,dataStartPos:e+u,dataSize:d,headerType:i,granulePosition:n,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:l}},tf=(r,e)=>{for(;r.filePos<e-3;){const t=$r(r),i=t&255,n=t>>>8&255,s=t>>>16&255,a=t>>>24&255,o=79;if(!(i!==o&&n!==o&&s!==o&&a!==o)){if(r.skip(-4),t===oc)return!0;r.skip(1)}}return!1};/*! 284 * Copyright (c) 2026-present, Vanilagy and contributors 285 * 286 * This Source Code Form is subject to the terms of the Mozilla Public 287 * License, v. 2.0. If a copy of the MPL was not distributed with this 288 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 289 */class rf extends ir{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,xr,Yr);if(t instanceof Promise&&(t=await t),!t)break;const i=yi(t);if(!i||!!!(i.headerType&2))break;
289this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const i=await this.readPacket(t.bosPage,0);i&&(i.data.byteLength>=7&&i.data[0]===1&&i.data[1]===118&&i.data[2]===111&&i.data[3]===114&&i.data[4]===98&&i.data[5]===105&&i.data[6]===115?await this.readVorbisMetadata(i,t):i.data.byteLength>=8&&i.data[0]===79&&i.data[1]===112&&i.data[2]===117&&i.data[3]===115&&i.data[4]===72&&i.data[5]===101&&i.data[6]===97&&i.data[7]===100&&await this.readOpusMetadata(i,t),t.codecInfo.codec!==null&&this.trackBackings.push(new nf(t,this)))}})())}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n||(i=await this.findNextPacketStart(n),!i))return;const s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s||n.data[0]!==3||s.data[0]!==5)return;const a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(n.data.length);const c=new Uint8Array(1+a.length+e.data.length+n.data.length+s.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(n.data,1+a.length+e.data.length),c.set(s.data,1+a.length+e.data.length+n.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=s;const l=_e(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Ed(s.data).modeBlockflags},bs(n.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=n;const s=Lo(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=kn,t.codecInfo.opusInfo={preSkip:s.preSkip},bs(n.data.subarray(8),this.metadataTags)}async readPacket(e,t){g(t<e.lacingValues.length);let i=0;for(let d=0;d<t;d++)i+=e.lacingValues[d];let n=e,s=i,a=t;const o=[];e:for(;;){let d=this.reader.requestSlice(n.dataStartPos,n.dataSize);d instanceof Promise&&(d=await d),g(d);const f=se(d,n.dataSize);for(;;){if(a===n.lacingValues.length){o.push(f.subarray(i,s));break}const p=n.lacingValues[a];if(s+=p,p<255){o.push(f.subarray(i,s));break e}a++}let m=n.headerStartPos+n.totalSize;for(;;){let p=this.reader.requestSliceRange(m,xr,Yr);if(p instanceof Promise&&(p=await p),!p)return null;const h=yi(p);if(!h)return null;if(n=h,n.serialNumber===e.serialNumber)break;m=n.headerStartPos+n.totalSize}i=0,s=0,a=0}const c=o.reduce((d,f)=>d+f.length,0);if(c===0)return null;const l=new Uint8Array(c);let u=0;for(let d=0;d<o.length;d++){const f=o[d];l.set(f,u),u+=f.length}return{data:l,endPage:n,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let i=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(i,xr,Yr);if(n instanceof Promise&&(n=await n),!n)return null;const s=yi(n);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};i=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(i=>(i==null?void 0:i.codec)??null)));return Jd({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class nf{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ii,this.internalSampleRate=e.codecInfo.codec==="opus"?kn:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return g(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
289async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return g(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return He}getDisposition(){return{...rr,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(g(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:n,vorbisBlockSize:s}=Zd(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new Ae(i.metadataOnly?ot:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,n/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:n,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){g(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;this.bitstream.codecInfo.codec==="opus"&&(g(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const n=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const n=await this.demuxer.findNextPacketStart(i.packet);if(!n)return null;const s=i.timestampInSamples+i.durationInSamples,a=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);const i=_i(e*this.internalSampleRate);if(i===0)return this.getFirstPacket(t);if(i<0)return null;g(this.bitstream.lastMetadataPacket);const n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let s=n.startPage,a=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSize<a;){const x=s.headerStartPos,T=Math.floor((x+a)/2);let P=T;for(;;){const _=Math.min(P+ef,a-xr);let S=this.demuxer.reader.requestSlice(P,_-P);if(S instanceof Promise&&(S=await S),g(S),!tf(S,_)){a=T+xr;continue e}let C=this.demuxer.reader.requestSliceRange(S.filePos,xr,Yr);C instanceof Promise&&(C=await C),g(C);const v=yi(C);g(v);let A=!1;if(v.serialNumber===this.bitstream.serialNumber)A=!0;else{let M=this.demuxer.reader.requestSlice(v.headerStartPos,v.totalSize);M instanceof Promise&&(M=await M),g(M);const D=se(M,v.totalSize);A=Yd(D)===v.checksum}if(!A){P=v.headerStartPos+4;continue}if(A&&v.serialNumber!==this.bitstream.serialNumber){P=v.headerStartPos+v.totalSize;continue}if(v.granulePosition===-1){P=v.headerStartPos+v.totalSize;continue}this.granulePositionToTimestampInSamples(v.granulePosition)>i?a=v.headerStartPos:(s=v,o.push(v));continue e}}let c=n.startPage;for(const x of o){if(x.granulePosition===s.granulePosition)break;(!c||x.headerStartPos>c.headerStartPos)&&(c=x)}let l=c;const u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){const x=l.headerStartPos+l.totalSize;let T=this.demuxer.reader.requestSliceRange(x,xr,Yr);T instanceof Promise&&(T=await T),g(T);const P=yi(T);g(P),l=P,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}g(l.granulePosition!==-1);let d=null,f,m,p=l,h=0;if(l.headerStartPos===n.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),m=!0,d=0;else{f=0,m=!1;for(let P=l.lacingValues.length-1;P>=0;P--)if(l.lacingValues[P]<255){d=P+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");h=d-1;const x={data:ot,endPage:p,endSegmentIndex:h};if(await this.demuxer.findNextPacketStart(x)){const P=Sa(u,l,d);g(P);const _=_a(u,P.page,P.segmentIndex);_&&(l=_.page,d=_.segmentIndex)}else for(;;){const P=Sa(u,l,d);if(!P)break;const _=_a(u,P.page,P.segmentIndex);if(!_)break;if(l=_.page,d=_.segmentIndex,P.page.headerStartPos!==p.headerStartPos){p=P.page,h=P.segmentIndex;break}}}let b=null,y=null;for(;l!==null;){g(d!==null);const x=await this.demuxer.readPacket(l,d);if(!x)break;if(!(l.headerStartPos===n.startPage.headerStartPos&&d<n.startSegmentIndex)){let _=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:f,vorbisLastBlocksize:(y==null?void 0:y.vorbisBlockSize)??null},t);g(_);let S=this.encodedPacketToMetadata.get(_);if(g(S),!m&&x.endPage.headerStartPos===p.headerStartPos&&x.endSegmentIndex===h?(f=this.granulePositionToTimestampInSamples(l.granulePosition),m=!0,_=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:f-S.durationInSamples,vorbisLastBlocksize:(y==null?void 0:y.vorbisBlockSize)??null},t),g(_),S=this.encodedPacketToMetadata.get(_),g(S)):f+=S.durationInSamples,b=_,y=S,m&&(Math.max(f,0)>i||Math.max(S.timestampInSamples,0)===i))break}const P=await this.demuxer.findNextPacketStart(x);if(!P)break;l=P.startPage,d=P.startSegmentIndex}return b}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const n=_i(e*this.internalSampleRate);e=n/this.internalSampleRate;const s=ye(this.sequentialScanCache,n,c=>c.timestampInSamples);let a;if(s!==-1){const c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){const c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;const l=this.encodedPacketToMetadata.get(a);g(l),this.sequentialScanCache.length>0&&g(Be(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const _a=(r,e,t)=>{let i=e,n=t;e:for(;;){for(n--,n;n>=0;n--)if(i.lacingValues[n]<255){n++;break e}if(g(n===-1),!(i.headerType&1)){n=0;break}const a=_o(r,o=>o.headerStartPos<i.headerStartPos);if(!a)return null;i=a,n=i.lacingValues.length}if(g(n!==-1),n===i.lacingValues.length){const s=r[r.indexOf(i)+1];g(s),i=s,n=0}return{page:i,segmentIndex:n}},Sa=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const i=_o(r,n=>n.headerStartPos<e.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};/*! 290 * Copyright (c) 2026-present, Vanilagy and contributors 291 * 292 * This Source Code Form is subject to the terms of the Mozilla Public 293 * License, v. 2.0. If a copy of the MPL was not distributed with this 294 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 295 */var Lt;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Lt||(Lt={}));class sf extends ir{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),g(e);const t=Re(e,4),i=t!=="RIFX",n=t==="RF64",s=dr(e,i);let a=n?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(Re(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;a===null||u<a;){let f=this.reader.requestSlice(u,8);if(f instanceof Promise&&(f=await f),!f)break;const m=Re(f,4),p=dr(f,i),h=f.filePos;if(n&&c===0&&m!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(m==="fmt ")await this.parseFmtChunk(h,p,i);else if(m==="data"){if(l??(l=p),this.dataStart=f.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(m==="ds64"){let b=this.reader.requestSlice(h,p);if(b instanceof Promise&&(b=await b),!b)break;const y=to(b,i);l=to(b,i),a=Math.min(y+8,this.reader.fileSize??1/0)}else m==="LIST"?await this.parseListChunk(h,p,i):(m==="ID3 "||m==="id3 ")&&await this.parseId3Chunk(h,p);u=h+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');const d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new af(this))})())}async parseFmtChunk(e,t,i){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let s=fi(n,i);const a=fi(n,i),o=dr(n,i);n.skip(4);const c=fi(n,i);let l;if(t===14?l=8:l=fi(n,i),t>=18&&s!==357){const u=fi(n,i),d=t-18;if(Math.min(d,u)>=22&&s===Lt.EXTENSIBLE){n.skip(6);const m=se(n,16);s=m[0]|m[1]<<8}}(s===Lt.MULAW||s===Lt.ALAW)&&(l=8),this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}
295}async parseListChunk(e,t,i){var o,c,l,u,d,f,m,p,h,b,y;let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;const s=Re(n,4);if(s!=="INFO"&&s!=="INF0")return;let a=n.filePos;for(;a<=e+t-8;){n.filePos=a;const x=Re(n,4),T=dr(n,i),P=se(n,T);let _=0;for(let I=0;I<P.length&&P[I]!==0;I++)_++;const S=String.fromCharCode(...P.subarray(0,_));switch((o=this.metadataTags).raw??(o.raw={}),this.metadataTags.raw[x]=S,x){case"INAM":case"TITL":(c=this.metadataTags).title??(c.title=S);break;case"TIT3":(l=this.metadataTags).description??(l.description=S);break;case"IART":(u=this.metadataTags).artist??(u.artist=S);break;case"IPRD":(d=this.metadataTags).album??(d.album=S);break;case"IPRT":case"ITRK":case"TRCK":{const I=S.split("/"),C=Number.parseInt(I[0],10),v=I[1]&&Number.parseInt(I[1],10);Number.isInteger(C)&&C>0&&((f=this.metadataTags).trackNumber??(f.trackNumber=C)),v&&Number.isInteger(v)&&v>0&&((m=this.metadataTags).tracksTotal??(m.tracksTotal=v))}break;case"ICRD":case"IDIT":{const I=new Date(S);Number.isNaN(I.getTime())||((p=this.metadataTags).date??(p.date=I))}break;case"YEAR":{const I=Number.parseInt(S,10);Number.isInteger(I)&&I>0&&((h=this.metadataTags).date??(h.date=new Date(I,0,1)))}break;case"IGNR":case"GENR":(b=this.metadataTags).genre??(b.genre=S);break;case"ICMT":case"CMNT":case"COMM":(y=this.metadataTags).comment??(y.comment=S);break}a+=8+T+(T&1)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const n=tr(i);if(n){const s=t-ht;if(n.size=Math.min(n.size,s),n.size>0){const a=i.slice(e+ht,n.size);In(a,n,this.metadataTags)}}}getCodec(){if(g(this.audioInfo),this.audioInfo.format===Lt.MULAW)return"ulaw";if(this.audioInfo.format===Lt.ALAW)return"alaw";if(this.audioInfo.format===Lt.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===Lt.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Or=2048;class af{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(g(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return g(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}
295async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return He}getDisposition(){return{...rr}}async getPacketAtIndex(e,t){g(e>=0),g(this.demuxer.audioInfo);const i=e*Or*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const n=Math.min(Or*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);if(c instanceof Promise&&(c=await c),!c)return null}let s;if(t.metadataOnly)s=ot;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);c instanceof Promise&&(c=await c),g(c),s=se(c,n)}const a=e*Or/this.demuxer.audioInfo.sampleRate,o=n/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Ae(s,"key",a,o,e,n)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){g(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Or,(this.demuxer.dataSize-1)/(Or*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const n=await this.getPacketAtIndex(i,t);if(n)return n;if(i===0)return null;g(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const a=await this.getNextPacket(s,t);if(!a)break;s=a}return s}getNextPacket(e,t){g(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Or);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*! 296 * Copyright (c) 2026-present, Vanilagy and contributors 297 * 298 * This Source Code Form is subject to the terms of the Mozilla Public 299 * License, v. 2.0. If a copy of the MPL was not distributed with this 300 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 301 */const an=7,Ir=9,Ar=r=>{const e=r.filePos,t=se(r,9),i=new Se(t);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const a=i.readBits(1),o=i.readBits(2)+1,c=i.readBits(4);if(c===15)return null;i.skipBits(1);const l=i.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const u=i.readBits(13);i.skipBits(11);const d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return a===1?r.filePos-=2:f=i.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:f,startPos:e}};/*! 302 * Copyright (c) 2026-present, Vanilagy and contributors 303 * 304 * This Source Code Form is subject to the terms of the Mozilla Public 305 * License, v. 2.0. If a copy of the MPL was not distributed with this 306 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 307 */const on=1024;class of extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new ii,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();g(this.firstFrameHeader),this.trackBackings=[new cf(this)]})())}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,ht);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=tr(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,an,Ir);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=Ar(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);const i=Er[t.samplingFrequencyIndex];g(i!==void 0);const n=on/i,s={timestamp:this.nextTimestampInSamples/i,duration:n,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=on,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let i=this.reader.requestSlice(t,ht);if(i instanceof Promise&&(i=await i),!i)break;const n=tr(i);if(!n)break;let s=this.reader.requestSlice(i.filePos,n.size);if(s instanceof Promise&&(s=await s),!s)break;In(s,n,this.metadataTags),t=i.filePos+n.size}return this.metadataTags}finally{e()}}}class cf{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}
vendor: 4,870 bytes, lines 307-319
307getTimeResolution(){return this.getSampleRate()/on}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return He}getCodec(){return"aac"}getInternalCodecId(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){g(this.demuxer.firstFrameHeader);const e=zi[this.demuxer.firstFrameHeader.channelConfiguration];return g(e!==void 0),e}getSampleRate(){g(this.demuxer.firstFrameHeader);const e=Er[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return g(e!==void 0),e}getDisposition(){return{...rr}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=ot;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;n=se(s,i.dataSize)}return new Ae(n,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=Ei(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");const s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=ye(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,t);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*! 308 * Copyright (c) 2026-present, Vanilagy and contributors 309 * 310 * This Source Code Form is subject to the terms of the Mozilla Public 311 * License, v. 2.0. If a copy of the MPL was not distributed with this 312 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 313 */const lf=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,uf=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},df=r=>{let e=0;const t=new Se(se(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const i=[],n=e-1,s=new Se(se(r,n)),a=8-e-1;for(let c=0;c<a;c++)i.unshift(t.readBits(1));for(let c=0;c<n;c++)for(let l=0;l<8;l++){const u=s.readBits(1);l<2||i.unshift(u)}return i.reduce((c,l,u)=>c|l<<u,0)},ff=(r,e)=>{if(e==="uncommon-u16")return Oe(r)+1;if(e==="uncommon-u8")return ie(r)+1;if(typeof e=="number")return e;Et(e),g(!1)},hf=(r,e)=>e==="uncommon-u16"?Oe(r):e==="uncommon-u16-10"?Oe(r)*10:e==="uncommon-u8"?ie(r):typeof e=="number"?e:null,mf=r=>{let t=0;for(const i of r){t^=i;for(let n=0;n<8;n++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};/*! 314 * Copyright (c) 2026-present, Vanilagy and contributors 315 * 316 * This Source Code Form is subject to the terms of the Mozilla Public 317 * License, v. 2.0. If a copy of the MPL was not distributed with this 318 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 319 */class pf extends ir{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new ii,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),g(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{var t;let e=0;for(;;){let i=this.reader.requestSlice(e,ht);if(i instanceof Promise&&(i=await i),!i){this.lastSampleLoaded=!0;return}const n=tr(i);if(!n)break;let s=this.reader.requestSlice(i.filePos,n.size);s instanceof Promise&&(s=await s),g(s),In(s,n,this.metadataTags),e=i.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let i=this.reader.requestSlice(e,4);
319if(i instanceof Promise&&(i=await i),e+=4,i===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);g(i);const n=ie(i),s=Ut(i),a=(n&128)!==0;switch(n&127){case Qr.STREAMINFO:{let c=this.reader.requestSlice(e,s);if(c instanceof Promise&&(c=await c),g(c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const l=se(c,34),u=new Se(l),d=u.readBits(16),f=u.readBits(16),m=u.readBits(24),p=u.readBits(24),h=u.readBits(20),b=u.readBits(3)+1;u.readBits(5);const y=u.readBits(36);u.skipBits(128);const x=new Uint8Array(42);x.set(new Uint8Array([102,76,97,67]),0),x.set(new Uint8Array([128,0,0,34]),4),x.set(l,8),this.audioInfo={numberOfChannels:b,sampleRate:h,totalSamples:y,minimumBlockSize:d,maximumBlockSize:f,minimumFrameSize:m,maximumFrameSize:p,description:x},this.trackBacking=new gf(this);break}case Qr.VORBIS_COMMENT:{let c=this.reader.requestSlice(e,s);c instanceof Promise&&(c=await c),g(c),bs(se(c,s),this.metadataTags);break}case Qr.PICTURE:{let c=this.reader.requestSlice(e,s);c instanceof Promise&&(c=await c),g(c);const l=K(c),u=K(c),d=Ye.decode(se(c,u)),f=K(c),m=Ye.decode(se(c,f));c.skip(16);const p=K(c),h=se(c,p);(t=this.metadataTags).images??(t.images=[]),this.metadataTags.images.push({data:h,mimeType:d,kind:l===3?"coverFront":l===4?"coverBack":"unknown",description:m});break}}if(e+=s,a){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})())}async readNextFlacFrame({startPos:e,isFirstPacket:t}){g(this.audioInfo);const i=6,n=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+n+2,o=this.audioInfo.minimumFrameSize||s,l=(this.audioInfo.maximumFrameSize||a)+n,u=await this.reader.requestSliceRange(e,n,l);if(!u)return null;const d=this.readFlacFrameHeader({slice:u,isFirstPacket:t});if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-i)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(ie(u)===255){const m=u.filePos,p=ie(u),h=this.blockingBit===1?249:248;if(p!==h){u.filePos=m;continue}u.skip(-2);const b=u.filePos-e,y=this.readFlacFrameHeader({slice:u,isFirstPacket:!1});if(!y){u.filePos=m;continue}if(this.blockingBit===0){if(y.num-d.num!==1){u.filePos=m;continue}}else if(y.num-d.num!==d.blockSize){u.filePos=m;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:b,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,n=se(e,4),s=new Se(n);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){g(t);const b=s.readBits(1);this.blockingBit=b}else if(this.blockingBit===1){if(g(!t),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(g(!t),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=lf(s.readBits(4));if(!o)return null;g(this.audioInfo);const c=uf(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const u=df(e),d=ff(e,o),f=hf(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;const m=e.filePos-i,p=ie(e);e.skip(-m),e.skip(-1);const h=mf(se(e,m));return p!==h?null:{num:u,blockSize:d,sampleRate:f}}async advanceReader(){await this.readMetadata(),g(this.lastLoadedPos!==null),g(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}const i=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(s),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class gf{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return He}
319getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...rr}}async getDecoderConfig(){return g(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(g(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=ye(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}const s=this.demuxer.loadedSamples[n],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=ot;else{let o=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;n=se(o,i.byteSize)}g(this.demuxer.audioInfo);const s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Ae(n,"key",s,a,e,i.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}/*! 320 * Copyright (c) 2026-present, Vanilagy and contributors 321 * 322 * This Source Code Form is subject to the terms of the Mozilla Public 323 * License, v. 2.0. If a copy of the MPL was not distributed with this 324 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 325 */const Kt=9e4,et=188,bf=r=>{let e="video/MP2T";const t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};/*! 326 * Copyright (c) 2026-present, Vanilagy and contributors 327 * 328 * This Source Code Form is subject to the terms of the Mozilla Public 329 * License, v. 2.0. If a copy of the MPL was not distributed with this 330 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 331 */const lc="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",va=new Set;class kf extends ir{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{const e=et+16+1;let t=this.reader.requestSlice(0,e);t instanceof Promise&&(t=await t),g(t);const i=se(t,e);if(i[0]===71&&i[et]===71)this.packetOffset=0,this.packetStride=et;else if(i[0]===71&&i[et+16]===71)this.packetOffset=0,this.packetStride=et+16;else if(i[4]===71&&i[4+et+4]===71)this.packetOffset=4,this.packetStride=et+4;else throw new Error("Unreachable.");const n=256;this.minReferencePointByteDistance=n*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){const l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;
331continue}if(c&&!this.elementaryStreams.some(h=>h.pid===l.pid)){s+=this.packetStride;continue}const u=await this.readSection(s,!0,!c);if(!u)break;const d=3,f=32;let m=!1;if(!c&&u.pid!==0&&!(u.payload[0]===0&&u.payload[1]===0&&u.payload[2]===1)){const b=new Se(u.payload),y=b.readAlignedByte();b.skipBits(8*y),m=b.readBits(8)===2}if(u.pid===0&&!o){const h=new Se(u.payload),b=h.readAlignedByte();h.skipBits(8*b),h.skipBits(14);const y=h.readBits(10);for(h.skipBits(40);8*(y+d)-h.pos>f;){const x=h.readBits(16);h.skipBits(3);const T=h.readBits(13);if(x!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=T}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((u.pid===a||m)&&!c){const h=new Se(u.payload),b=h.readAlignedByte();h.skipBits(8*b),h.skipBits(12);const y=h.readBits(12);h.skipBits(43),h.readBits(13),h.skipBits(6);const x=h.readBits(10);for(h.skipBits(8*x);8*(y+d)-h.pos>f;){const T=h.readBits(8);h.skipBits(3);const P=h.readBits(13);h.skipBits(6);const _=h.readBits(10),S=h.pos+8*_;let I=!1,C=!1;for(;h.pos<S;){const A=h.readBits(8),H=h.readBits(8);A===106?I=!0:(A===122||A===204)&&(C=!0),h.skipBits(8*H)}let v=null;switch(T){case 27:case 36:v={type:"video",codec:T===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let A;if(T===3||T===4)A="mp3";else if(T===15)A="aac";else if(T===129)A="ac3";else if(T===135)A="eac3";else throw new Error("Unreachable.");v={type:"audio",codec:A,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:C?v={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:I&&(v={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:va.has(T)||(ue._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),va.add(T))}v&&this.elementaryStreams.push({demuxer:this,pid:P,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:v,referencePesPackets:[]})}c=!0}else{const h=this.elementaryStreams.find(b=>b.pid===u.pid);e:if(h&&!h.initialized){const b=qr(u,!0);if(!b)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${h.pid}`);if(h.firstSection=u,h.canBeTrustedWithKeyPackets=u.randomAccessIndicator===1,this.input._initInput){const T=(await this.input._initInput._getDemuxer()).elementaryStreams.find(P=>P.pid===u.pid&&P.info.codec===h.info.codec);if(T){h.info=T.info,h.initialized=!0;break e}}const y=new gi(h,b);if(h.info.type==="video"){for(;;){const x=y;if(x.suppliedPacket=null,await y.markNextPacket(),h.info.codec==="avc"){if(!y.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(h.info.avcCodecInfo=qs(y.suppliedPacket.data),!h.info.avcCodecInfo)continue;const T=h.info.avcCodecInfo.sequenceParameterSets[0];g(T);const P=$s(T);h.info.width=P.displayWidth,h.info.height=P.displayHeight;const _=P.pixelAspectRatio.num,S=P.pixelAspectRatio.den;_>0&&S>0&&(_>S?(h.info.squarePixelWidth=Math.round(h.info.width*_/S),h.info.squarePixelHeight=h.info.height):(h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=Math.round(h.info.height*S/_))),h.info.colorSpace={primaries:Gi[P.colourPrimaries],transfer:Xi[P.transferCharacteristics],matrix:Qi[P.matrixCoefficients],fullRange:!!P.fullRangeFlag},h.info.reorderSize=P.maxDecFrameBuffering;break}else if(h.info.codec==="hevc"){if(!y.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(h.info.hevcCodecInfo=js(y.suppliedPacket.data),!h.info.hevcCodecInfo)continue;const P=h.info.hevcCodecInfo.arrays.find(S=>S.nalUnitType===Ne.SPS_NUT).nalUnits[0];g(P);const _=Do(P);h.info.width=_.displayWidth,h.info.height=_.displayHeight,_.pixelAspectRatio.num>_.pixelAspectRatio.den?(h.info.squarePixelWidth=Math.round(h.info.width*_.pixelAspectRatio.num/_.pixelAspectRatio.den),h.info.squarePixelHeight=h.info.height):(h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=Math.round(h.info.height*_.pixelAspectRatio.den/_.pixelAspectRatio.num)),h.info.colorSpace
331={primaries:Gi[_.colourPrimaries],transfer:Xi[_.transferCharacteristics],matrix:Qi[_.matrixCoefficients],fullRange:!!_.fullRangeFlag},h.info.reorderSize=_.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}h.info.decoderConfig={codec:Vs({width:h.info.width,height:h.info.height,codec:h.info.codec,codecDescription:null,colorSpace:h.info.colorSpace,avcType:1,avcCodecInfo:h.info.avcCodecInfo,hevcCodecInfo:h.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:h.info.width,codedHeight:h.info.height,colorSpace:h.info.colorSpace},(h.info.width!==h.info.squarePixelWidth||h.info.height!==h.info.squarePixelHeight)&&(h.info.decoderConfig.displayAspectWidth=h.info.squarePixelWidth,h.info.decoderConfig.displayAspectHeight=h.info.squarePixelHeight),h.initialized=!0}else{if(await y.markNextPacket(),!y.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${h.pid}`);if(h.info.codec==="aac"){const x=at.tempFromBytes(y.suppliedPacket.data),T=Ar(x);if(!T)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");h.info.aacCodecInfo={isMpeg2:!1,objectType:T.objectType},h.info.numberOfChannels=zi[T.channelConfiguration],h.info.sampleRate=Er[T.samplingFrequencyIndex]}else if(h.info.codec==="mp3"){const x=K(at.tempFromBytes(y.suppliedPacket.data)),T=Ws(x,y.suppliedPacket.data.byteLength);if(!T.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");h.info.numberOfChannels=vi(T.header.channel),h.info.sampleRate=T.header.sampleRate}else if(h.info.codec==="ac3"){const x=Wo(y.suppliedPacket.data);if(!x)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(x.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=Ks[x.acmod]+x.lfeon,h.info.sampleRate=yn[x.fscod]}else if(h.info.codec==="eac3"){const x=qo(y.suppliedPacket.data);if(!x)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const T=$o(x);if(T===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=jo(x),h.info.sampleRate=T}else throw new Error("Unhandled.");h.info.decoderConfig={codec:Ls({codec:h.info.codec,codecDescription:null,aacCodecInfo:h.info.aacCodecInfo}),numberOfChannels:h.info.numberOfChannels,sampleRate:h.info.sampleRate},h.initialized=!0}}}if(c&&this.elementaryStreams.every(h=>h.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(const l of this.elementaryStreams)l.info.type==="video"?this.trackBackingEntries.push(new yf(l)):this.trackBackingEntries.push(new wf(l))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(i=>(i==null?void 0:i.codec)??null)));return bf(e)}async readSection(e,t,i=!1){let n=e,s=e;const a=[];let o=0,c=null,l=!0,u=0;for(;;){const f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(c){if(f.pid!==c.pid){if(i)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;c=f}const m=!!(f.adaptationFieldControl&2),p=!!(f.adaptationFieldControl&1);let h=0;if(m&&(h=1+f.body[0],f===c&&h>1&&(u=f.body[1]>>6&1)),p&&(h===0?(a.push(f.body),o+=f.body.byteLength):(a.push(f.body.subarray(h)),o+=f.body.byteLength-h)),n=s,!t&&o>=64){l=!1;break}if(Ei(this.sectionEndPositions,n,y=>y)!==-1){l=!1;break}}if(l){const f=ye(this.sectionEndPositions,n,m=>m);this.sectionEndPositions.splice(f+1,0,n)}if(!c)return null;let d;if(a.length===1)d=a[0];else{const f=a.reduce((p,h)=>p+h.length,0);d=new Uint8Array(f);let m=0;for(const p of a)d.set(p,m),m+=p.length}return{startPos:e,endPos:t?n:null,pid:c.pid,payload:d,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);
331if(t instanceof Promise&&(t=await t),!t)return null;if(ie(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const n=Oe(t),s=n>>14&1,a=n&8191,c=ie(t)>>4&3;return{payloadUnitStartIndicator:s,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,et);if(t instanceof Promise&&(t=await t),!t)return null;const i=se(t,et);if(i[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const s=(i[1]<<8)+i[2],a=s>>14&1,o=s&8191,l=i[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:l,body:i.subarray(4)}}}const br=(r,e)=>{if(r.payload.byteLength<3)return null;const t=new Se(r.payload);if(t.readBits(24)!==1)return null;const n=t.readBits(8);if(t.skipBits(16),n===188||n===190||n===191||n===240||n===241||n===255||n===242||n===248)return null;t.skipBits(8);const s=t.readBits(2);t.skipBits(14);let a=null;if(s===2||s===3)a=0,t.skipBits(4),a+=t.readBits(3)*(1<<30),t.skipBits(1),a+=t.readBits(15)*32768,t.skipBits(1),a+=t.readBits(15);else if(e)throw new Error(lc);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},qr=(r,e)=>{g(r.endPos!==null);const t=br(r,e);if(!t)return null;const i=new Se(r.payload);i.skipBits(32);const n=i.readBits(16),s=6;i.skipBits(16);const a=i.readBits(8),o=i.pos+8*a;i.pos=o;const c=o/8;g(Number.isInteger(c));const l=r.payload.subarray(c,n>0?s+n:r.payload.byteLength);return{...t,data:l}};class _n{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let i=0;for(const n of e.trackBackingEntries)if(n.getType()===t&&i++,g(n instanceof _n),n.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return He}getDisposition(){return{...rr,primary:!1}}getTimeResolution(){return Kt}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
331async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let n;return this.allPacketsAreKeyPackets()?n="key":n=e.randomAccessIndicator===1?"key":"delta",new Ae(i.metadataOnly?ot:e.data,n,e.pts/Kt,Math.max(t/Kt,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;g(t);const i=qr(t,!0);g(i);const n=new gi(this.elementaryStream,i),s=new qn(this,n),a=await s.readNext();if(!a)return null;const o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const u=await i.readNext();if(!u)return null;this.packetBuffers.delete(e);const d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,i),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}const n=this.packetSectionStarts.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");const a=await this.elementaryStream.demuxer.readSection(n,!0);g(a);const o=qr(a,!0);g(o);const c=new gi(this.elementaryStream,o);i=new qn(this,c);const l=e.sequenceNumber;for(;;){const u=await i.readNext();if(!u)return null;if(u.packet.sequenceNumber>l){const d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,i),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if(i.type==="key")return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){var P;const n=_i(e*Kt),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,l=async(_,S,I)=>{let C=_;for(;C<S;){const v=await s.readPacketHeader(C);if(!v)return null;if(v.pid===c&&v.payloadUnitStartIndicator===1){const A=await s.readSection(C,I);if(!A)return null;const H=br(A,!1);if(H&&H.pts!==null)return{pesPacketHeader:H,section:A}}C+=s.packetStride}return null},u=this.elementaryStream.firstSection;g(u);const d=br(u,!0);if(g(d),n<d.pts)return null;let f;const m=this.elementaryStream.referencePesPackets,p=ye(m,n,_=>_.pts),h=p!==-1?m[p]:null;if(h&&n-h.pts<Kt/2)f=h.sectionStartPos;else{let _=0;if(a.fileSize!==null){const S=Math.ceil(a.fileSize/o);if(S>1){let I=0,C=S-1;for(_=I;I<=C;){const v=Math.floor((I+C)/2),A=Bn(v*o,s.packetStride)+d.sectionStartPos,H=A+o,M=await l(A,H,!1);if(!M){C=v-1;continue}M.pesPacketHeader.pts<=n?(_=v,I=v+1):C=v-1}}}f=Bn(_*o,s.packetStride)+d.sectionStartPos}const b=await l(f,a.fileSize??1/0,!1);let y=(b==null?void 0:b.pesPacketHeader)??null;y||(y=d);const x=this.getReorderSize(),T=async(_,S)=>{var O;const I=await s.readSection(_,!0);g(I);const C=qr(I,!0);g(C);const v=new gi(this.elementaryStream,C),A=new qn(this,v);for(;!((((O=Be(A.presentationOrderPackets))==null?void 0:O.pts)??-1/0)>=n||!await A.readNextPacket()););const H=Bs(A.presentationOrderPackets,S);if(H===-1)return null;const M=A.presentationOrderPackets[H],D=H===0?0:M.pts-A.presentationOrderPackets[H-1].pts;for(;A.decodeOrderPackets[0]!==M;)A.decodeOrderPackets.shift();A.lastDuration=D;const $=await A.readNext();g($);const B=this.createEncodedPacket($.packet,$.duration,i);return this.packetBuffers.set(B,A),this.packetSectionStarts.set(B,$.packet.sectionStartPos),B};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let _=y.sectionStartPos+s.packetStride;for(;;){const S=await s.readPacketHeader(_);if(!S)break e;if(S.pid===c&&S.payloadUnitStartIndicator===1){const I=await s.readSection(_,!1);if(I){const C=br(I,!1);if(C&&C.pts!==null){if(C.pts>n)break e;y=C,Ts(this.elementaryStream,y);break}}}_+=s.packetStride}}e:for(let _=0;_<x+1;_++){let S=y.sectionStartPos-s.packetStride;for(;S>=s.packetOffset;){const I=await s.readPacketHeader(S);if(!I)break e;if(I.pid===c&&I.payloadUnitStartIndicator===1){const C=await s.readSection(S,!1);if(C){const v=br(C,!1);if(v&&v.pts!==null){y=v;break}}}S-=s.packetStride}}return T(y.sectionStartPos,_=>_.pts<=n)}else{let _=f,S=null;const I=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let C=null;const v=_<=d.sectionStartPos;let A,H=null;if(v)A=d,H=u;else{const $=await l(_,a.fileSize??1/0,I);A=($==null?void 0:$.pesPacketHeader)??null,H=($==null?void 0:$.section)??null}let M=!1,D=0;e:for(;A&&!(S!==null&&A.sectionStartPos>=S);){if(A.pts<=n){let B;if(this.elementaryStream.canBeTrustedWithKeyPackets)B=A.randomAccessIndicator===1;else{g(H);const O=qr(H,!0);g(O);const X=new gi(this.elementaryStream,O);await X.markNextPacket(),B=((P=X.suppliedPacket)==null?void 0:P.randomAccessIndicator)===1}B&&(C=A)}if(A.pts>n&&(M=!0),M&&(D++,D>x))break;let $=A.sectionStartPos+s.packetStride;for(;;){const B=await s.readPacketHeader($);if(!B)break e;if(B.pid===c&&B.payloadUnitStartIndicator===1){const O=await s.readSection($,I);if(O){const X=br(O,!1);if(X&&X.pts!==null){A=X,H=O,Ts(this.elementaryStream,A);break}}}$+=s.packetStride}}if(C){let $=C;if(D===0)e:for(let O=0;O<x;O++){let X=$.sectionStartPos-s.packetStride;for(;X>=s.packetOffset;){const ae=await s.readPacketHeader(X);if(!ae)break e;if(ae.pid===c&&ae.payloadUnitStartIndicator===1){const ve=await s.readSection(X,I);if(ve){const Ie=br(ve,!1);if(Ie&&Ie.pts!==null){$=Ie;break}}}X-=s.packetStride}}const B=await T($.sectionStartPos,O=>O.pts<=n&&O.randomAccessIndicator===1);return g(B),B}if(v)return null;S=_,_=Math.max(Bn(_-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class yf extends _n{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}
331async canBeTransparent(){return!1}async getDecoderConfig(){return g(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class wf extends _n{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return g(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Ts=(r,e)=>{const t=r.referencePesPackets,i=ye(t,e.sectionStartPos,n=>n.sectionStartPos);if(i>=0){const n=t[i];if(e.pts<=n.pts)return!1;const s=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-n.sectionStartPos<s)return!1;if(i<t.length-1){const a=t[i+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return t.splice(i+1,0,e),!0};class gi{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){const t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return g(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t;){let i;if(this.pesPackets.length===0)i=this.startingPesPacket;else{let n=Be(this.pesPackets).sectionEndPos;for(g(n!==null);;){const s=await this.demuxer.readPacketHeader(n);if(!s)return;if(s.pid===this.pid){const a=await this.demuxer.readSection(n,!0);if(!a)return;const o=qr(a,!1);if(o){i=o;break}}n+=this.demuxer.packetStride}}this.pesPackets.push(i),this.endPos+=i.data.byteLength}}readBytes(e){const t=this.getCurrentPesPacket(),i=this.currentPos-this.currentPesPacketPos,n=i+e;if(this.currentPos+=e,n<=t.data.byteLength)return t.data.subarray(i,n);const s=new Uint8Array(e);s.set(t.data.subarray(i));let a=t.data.byteLength-i;for(;;){this.advanceCurrentPacket();const o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket();const t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){const t=this.getCurrentPesPacket(),i=this.currentPesPacketPos+t.data.byteLength;if(e<i)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){g(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const t=e.info.codec,i=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");const n=t==="avc"?1:2;let s=null,a=!1,o=0;for(;;){let c=this.ensureBuffered(i);if(c instanceof Promise&&(c=await c),c===0)break;const l=this.currentPos,u=this.readBytes(c),d=u.byteLength;let f=0;for(;f<d;){const m=u.indexOf(0,f);if(m===-1||m>=d)break;f=m;const p=l+f;if(f+3>=d){this.seekTo(p);break}const h=u[f+1],b=u[f+2],y=u[f+3];let x=0;if(h===0&&b===0&&y===1?x=4:h===0&&b===1&&(x=3),x===0){f++;continue}const T=p;s??(s=T);const P=f+x,_=P+n,S=6;if(_+(t==="avc"?S:1)>d){this.seekTo(p);break}const C=u[P];let v,A,H;if(t==="avc")v=wn(C),A=v===Le.NON_IDR_SLICE||v===Le.SLICE_DPA||v===Le.IDR,H=v===Le.SEI||v===Le.SPS||v===Le.PPS||v===Le.AUD;else{if(v=Jr(C),((C&1)<<5|u[P+1]>>3)>0){f+=x;continue}A=v<=Ne.RASL_R||v>=Ne.BLA_W_LP&&v<=21,H=v>=Ne.VPS_NUT&&v<=37||v===Ne.PREFIX_SEI_NUT||v>=41&&v<=44||v>=48&&v<=55}let M=!1;if(A){let D;if(t==="avc"){const $=u.subarray(_,_+S),B=Q(new Se($));D=!a||B<=o,o=B}else D=u[_]>>7===1;D&&(a?M=!0:a=!0)}else H&&a&&(M=!0);if(M){const D=T-s;return this.seekTo(s),this.supplyPacket(D,0)}f+=x}if(c<i)break}if(s!==null&&this.endPos>s){const c=this.endPos-s;return this.seekTo(s),this.supplyPacket(c,0)}}else{const t=e.info.codec,i=128;for(;;){let n=this.ensureBuffered(i);n instanceof Promise&&(n=await n);const s=this.currentPos;for(;this.currentPos-s<n;){const a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Ir);if(c instanceof Promise&&(c=await c),c<Ir)return;const l=this.readBytes(Ir),u=Ar(at.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return d instanceof Promise&&(d=await d),this.supplyPacket(d,Math.round(on*Kt/e.info.sampleRate))}else this.seekTo(o+1)}else if(t==="mp3"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Cr);if(c instanceof Promise&&(c=await c),c<Cr)return;const l=this.readBytes(Cr),u=_e(l).getUint32(0),d=Ws(u,null);if(d.header){this.seekTo(o);let f=this.ensureBuffered(d.header.totalSize);f instanceof Promise&&(f=await f);const m=d.header.audioSamplesInFrame*Kt/e.info.sampleRate;return this.supplyPacket(f,Math.round(m))}else this.seekTo(o+1)}else if(t==="ac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}const u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}const f=Ad[3*d+u];g(f!==void 0),this.seekTo(o),c=this.ensureBuffered(f),c instanceof Promise&&(c=await c);const m=Math.round(zd*Kt/e.info.sampleRate);return this.supplyPacket(c,m)}else if(t==="eac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}const d=(((l[2]&7)<<8|l[3])+1)*2,m=l[4]>>6===3?3:l[4]>>4&3,p=Ho[m];this.seekTo(o),c=this.ensureBuffered(d),c instanceof Promise&&(c=await c);const h=p*256,b=Math.round(h*Kt/e.info.sampleRate);return this.supplyPacket(c,b)}else throw new Error("Unhandled.")}if(n<i)break}}}supplyPacket(e,t){const i=this.getCurrentPesPacket();let n;if(this.lastSuppliedPesPacket===i)g(this.nextPts!==null),n=this.nextPts;else{if(i.pts===null)throw new Error(lc);n=i.pts,Ts(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=n+t;const s=i.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=i.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){const l=Tn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(l)}}this.suppliedPacket={pts:n,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class qn{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),g(this.reorderSize>=0)}
331async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);g(t!==-1);let i;for(t===this.presentationOrderPackets.length-1?i=this.lastDuration:(i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const n=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(n))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(g(e);;){const t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let t=0;for(let n=1;n<this.reorderBuffer.length;n++)this.reorderBuffer[n].pts<this.reorderBuffer[t].pts&&(t=n);const i=this.reorderBuffer[t];this.presentationOrderPackets.push(i),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}/*! 332 * Copyright (c) 2026-present, Vanilagy and contributors 333 * 334 * This Source Code Form is subject to the terms of the Mozilla Public 335 * License, v. 2.0. If a copy of the MPL was not distributed with this 336 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 337 */const uc="application/vnd.apple.mpegurl",Pa="#EXT-X-STREAM-INF:",Ca="#EXT-X-I-FRAME-STREAM-INF:",Ia="#EXT-X-MEDIA:",_s="#EXTINF:",Ea="#EXT-X-MAP:",Aa="#EXT-X-KEY:",za="#EXT-X-MEDIA-SEQUENCE:",Fa="#EXT-X-BYTERANGE:",Ba="#EXT-X-PROGRAM-DATE-TIME:",xf="#EXT-X-DISCONTINUITY",Ra="#EXT-X-TARGETDURATION:",Tf="#EXT-X-ENDLIST",Ma="#EXT-X-PLAYLIST-TYPE:",_f="#EXT-X-I-FRAMES-ONLY",dc=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT");class wi{constructor(e){this._attributes={};let t="",i="",n=!1,s=!1;for(let a=0;a<e.length;a++){const o=e[a];o==='"'?s=!s:o==="="&&!n&&!s?n=!0:o===","&&!s?(t&&(this._attributes[t.trim().toLowerCase()]=i),t="",i="",n=!1):n?i+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=i)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const t=this.get(e);if(t===null)return null;const i=Number(t);return Number.isFinite(i)?i:null}merge(e){Object.assign(this._attributes,e._attributes)}}/*! 338 * Copyright (c) 2026-present, Vanilagy and contributors 339 * 340 * This Source Code Form is subject to the terms of the Mozilla Public 341 * License, v. 2.0. If a copy of the MPL was not distributed with this 342 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 343 */class Sf{constructor(e,t,i){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=i}
343async getDurationFromMetadata(e){const t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(t??(t=await this.getFirstSegment({})),!t||t.unixEpochTimestamp===null)return null;const i=e-t.timestamp;return t.unixEpochTimestamp+i}async getTrackBackings(){return this.trackBackingsPromise??(this.trackBackingsPromise=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if(t.type==="video"){const i=mi(e,n=>n.getType()==="video")+1;e.push(new Oa(this,t,i))}else if(t.type==="audio"){const i=mi(e,n=>n.getType()==="audio")+1;e.push(new Da(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const i=await this.getInputForSegment(this.firstSegment).getTracks();for(const n of i)if(n.type==="video"){const s=mi(e,a=>a.getType()==="video")+1;e.push(new Oa(this,{id:e.length+1,type:"video"},s))}else if(n.type==="audio"){const s=mi(e,a=>a.getType()==="audio")+1;e.push(new Da(this,{id:e.length+1,type:"audio"},s))}}return e})())}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(t!==void 0)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let n;if(this.firstSegmentFirstTimestamps.has(i))n=this.firstSegmentFirstTimestamps.get(i);else{const l=this.getInputForSegment(i);n=await this.getFirstTimestampForInput(l),this.firstSegmentFirstTimestamps.set(i,n)}if(i===e)return i.timestamp-n;const s=await this.getFirstTimestampForInput(t),a=e.timestamp-i.timestamp,c=s-n-a;return Math.abs(c)<=Math.min(.25,a)?i.timestamp-n:e.timestamp-s}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class fc{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var n;if((n=this.segmentedInput).firstSegment??(n.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");const i=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(s=>s.type===this.decl.type&&s.number===this.number);if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>{var e,t;return((t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??null})}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),g(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}
343getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){g(e.sequenceNumber>=0),g(this.segmentedInput.firstSegment);const n=await this.segmentedInput.getMediaOffset(t,i.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:Zi(e.timestamp+n,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:i,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),g(this.segmentedInput.firstSegment),g(this.firstInputTrack);const t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,i){const n=this.packetInfos.get(e);if(!n)throw new Error("Packet was not created from this track.");const s=i?await n.track._backing.getNextKeyPacket(n.sourcePacket,t):await n.track._backing.getNextPacket(n.sourcePacket,t);if(s)return this.createAdjustedPacket(s,n.segment,n.track);let a=n.segment;for(;;){const o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;const u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(f=>f.type===n.track.type&&f.number===n.track.number);if(!u){a=o;continue}const d=await u._backing.getFirstPacket(t);return d?this.createAdjustedPacket(d,o,u):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let n=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!n)return null;for(await this.hydrate();n;){const s=this.segmentedInput.getInputForSegment(n),o=(await s.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:t.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(n,s),l=e-c,u=i?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!u){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(u,n,o)}return null}}class Oa extends fc{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}
343async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Da extends fc{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}/*! 344 * Copyright (c) 2026-present, Vanilagy and contributors 345 * 346 * This Source Code Form is subject to the terms of the Mozilla Public 347 * License, v. 2.0. If a copy of the MPL was not distributed with this 348 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 349 */Os();const hc=0,mc=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(r=>{r()});class It extends Ai{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new tt;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,hc,mc),e=this._getFileSize(),g(e!==void 0)),e})())}async getSize(){if(this._disposed)throw new tt;
349const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new zf(this,e,t)}_dispatchRead(e,t){var i;(i=this.onread)==null||i.call(this,e,t),this._emit("read",{start:e,end:t})}ref(){return new Qs(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class Qs{constructor(e){var t;if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),(t=e._refFinalizationRegistry)==null||t.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){var t;if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;g(e._refCount>0),e._decrementRefCount(),(t=e._refFinalizationRegistry)==null||t.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class ni extends It{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=n=>{var a;if(!(n instanceof It||n instanceof Qs))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=n instanceof It?n.ref():n;return(a=s.source)._usedForHls||(a._usedForHls=this._usedForHls),s};return t instanceof Promise?t.then(i):i(t)}}const Na=(r,e)=>r.path===e.path;class vf extends ni{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,n){if(!this._root){if(!this._rootRequest){const s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{const c=o instanceof It?o.ref():o;return this._root=c,this._rootRequest=null,c};s instanceof Promise?this._rootRequest=s.then(a):(a(s),g(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,t,i,n))}return this._root.source._read(e,t,i,n)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class Ys extends It{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!gn(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new gc({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:pc.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,n){return this._orchestrator.read(e,t,i,n)}async _runWorker(e){g(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!bi()&&this._options.useStreamReader!==!1?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:i,value:n}=await t.read();if(i)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}else{const i=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(i))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await(t==null?void 0:t.cancel())}
349_dispose(){this._orchestrator.dispose()}}const Pf=.5*2**20,Cf=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let n=null;try{typeof window<"u"&&typeof window.location<"u"&&(n=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&n!==null&&n!==window.location.origin)return ue._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),Ua=new Set;class Sn extends ni{constructor(e,t={}){var a;if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!gn(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");const i=e instanceof Request?e.url:e instanceof URL?e.href:e;super(i,o=>new Sn(o.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Cf,this._requestInit={...t.requestInit};let n=null;if((a=t.requestInit)!=null&&a.headers){const o={...hs(t.requestInit.headers)},c=Object.keys(o).find(l=>l.toLowerCase()==="range");c!==void 0&&(n=o[c],delete o[c],this._requestInit.headers=o)}if(e instanceof Request){const o=e.headers.get("Range");if(o!==null){n??(n=o);const c=new Request(e);c.headers.delete("Range"),this._url=c}}if(n!==null){const o=Ef(n);o&&(this._offset=o.offset,this._length=o.length)}const s=2;this._orchestrator=new gc({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:pc.network})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;const e=this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:De(e-this._offset,0,this._length??1/0)}_read(e,t,i,n){if(this._length!==null&&t>this._length)return null;const s=this._offset,a=this._orchestrator.read(s+e,s+t,Math.max(s+i,s),s+Math.min(n,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return a instanceof Promise?a.then(o):o(a)}async _runWorker(e){for(;;){const t=new AbortController,i=await Hu(this._options.fetchFn??fetch,this._url,Wu(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);i.redirected&&(this.rootPath=i.url);e:if(this._orchestrator.fileSize===null){const s=i.headers.get("Content-Range");if(s){const o=/\/(\d+)/.exec(s);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}const a=i.headers.get("Content-Length");
349a&&this._orchestrator.supplyFileSize(e.currentPos+Number(a))}if(this._fileSizeDetermined=!0,i.status!==206){if(!this._usedForHls){const s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(Ua.has(s.origin)||(ue._warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),Ua.add(s.origin)))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize!==null?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!i.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const n=i.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await n.read()}catch(c){if(this._disposed)throw c;const l=this._getRetryDelay(1,c,this._url);if(l!==null){ue._error("Error while reading response stream. Attempting to resume.",c),await bn(1e3*l);break}else throw c}if(e.aborted)continue;const{done:a,value:o}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_dispose(){this._orchestrator.dispose()}}const If=/^bytes=(\d+)-(\d*)$/,Ef=r=>{const e=If.exec(r.trim());if(!e)return null;const t=Number(e[1]),i=e[2]===""?null:Number(e[2]);return i!==null&&i<t?null:{offset:t,length:i!==null?i-t+1:null}};class Af extends It{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!gn(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=ye(this._cache,e,u=>u.start),n=i!==-1?this._cache[i]:null;if(n&&n.start<=e&&t<=n.end)return{bytes:n.bytes,view:n.view,offset:n.start};let s=e;const a=new Uint8Array(t-e);if(i!==-1)for(let u=i;u<this._cache.length;u++){const d=this._cache[u];if(d.start>=t)break;const f=Math.max(e,d.start);f>s&&this._throwDueToCacheMiss();const m=Math.min(t,d.end);f<m&&(a.set(d.bytes.subarray(f-d.start,m-d.start),f-e),s=m)}if(s===t)return{bytes:a,view:_e(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:l}=Ue();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else throw u})),o}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await this._reader.read();if(e){for(const s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const i=this._currentIndex,n=this._currentIndex+t.byteLength;this._dispatchRead(i,n);for(let s=0;
349s<this._pendingSlices.length;s++){const a=this._pendingSlices[s],o=Math.max(i,a.start),c=Math.min(n,a.end);o<c&&(a.bytes.set(t.subarray(o-i,c-i),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:_e(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:i,end:n,bytes:t,view:_e(t),age:0});this._cache.length>0;){const s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){var e;this._pendingSlices.length=0,this._cache.length=0,(e=this._reader)==null||e.cancel()}}const pc={fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(const n of t){const a=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(ps(r,e,a,n.targetPos)){const o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,n.startPos+u)}}return e=Math.max(e,r+Pf),{start:r,end:e}}};class gc{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,n){g(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,i),o=Math.min(s.end,this.fileSize??1/0,n);g(a<=e&&t<=o);let c=null;const l=ye(this.cache,e,_=>_.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});const d=ye(this.cache,a,_=>_.start),f=c?null:new Uint8Array(t-e);let m=0,p=a;const h=[];if(d!==-1){for(let _=d;_<this.cache.length;_++){const S=this.cache[_];if(S.start>=o)break;if(S.end<=a)continue;const I=Math.max(a,S.start),C=Math.min(o,S.end);if(g(I<=C),p<I&&h.push({start:p,end:I}),p=C,f){const v=Math.max(e,S.start),A=Math.min(t,S.end);if(v<A){const H=v-e;f.set(S.bytes.subarray(v-S.start,A-S.start),H),H===m&&(m=A-e)}}S.age=this.nextAge++}p<o&&h.push({start:p,end:o})}else h.push({start:a,end:o});if(f&&m>=f.length&&(c={bytes:f,view:_e(f),offset:e}),h.length===0)return g(c),c;const{promise:b,resolve:y,reject:x}=Ue(),T=[];for(const _ of h){const S=Math.max(e,_.start),I=Math.min(t,_.end);S===_.start&&I===_.end?T.push(_):S<I&&T.push({start:S,end:I})}const P=f&&{start:e,bytes:f,holes:T,resolve:y,reject:x};e:for(const _ of h){for(const C of this.workers)if(this.checkHoleAgainstWorker(C,_,P?[P]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}const S=_.end<o||this.fileSize!==null,I=this.createWorker(_.start,_.end,S);if(I)P&&(I.pendingSlices=[P]),this.runWorker(I);else{let C=ye(this.queuedReads,_.start,A=>A.hole.start),v=C!==-1?this.queuedReads[C]:null;for(v&&_.start<=v.hole.end?(v.hole.end=Math.max(v.hole.end,_.end),v.strictTarget&&(v.strictTarget=S),P&&v.pendingSlices.push(P)):(C++,v={hole:{start:_.start,end:_.end},strictTarget:S,pendingSlices:P?[P]:[],age:this.nextAge++},this.queuedReads.splice(C,0,v));C+1<this.queuedReads.length;){const A=this.queuedReads[C+1];if(A.hole.start>v.hole.end)break;v.hole.end=Math.max(v.hole.end,A.hole.end),v.pendingSlices.push(...A.pendingSlices),v.strictTarget&&(v.strictTarget=A.strictTarget),v.age=Math.min(v.age,A.age),this.queuedReads.splice(C+1,1)}}}return c?b.catch(_=>{if(!this.disposed)throw _}):(g(f),c=b.then(_=>_&&{bytes:_,view:_e(_),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(ps(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let s=0;s<i.length;s++){const a=i[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){const n=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,n.hole,n.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,i){if(this.workers.length>=this.options.maxWorkerCount){let s=null,a=null;for(let o=0;o<this.workers.length;o++){const c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!s||c.age<s.age)&&(a=o,s=c)}if(s)g(a!==null),g(s.pendingSlices.length===0),this.workers.splice(a,1);else return null}const n={startPos:e,currentPos:e,targetPos:t,strictTarget:i,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(n),n}runWorker(e){g(!e.running),g(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).
349catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let t=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[t].age&&(t=s);const i=this.queuedReads[t],n=this.createWorker(i.hole.start,i.hole.end,i.strictTarget);if(!n)return;this.queuedReads.splice(t,1),n.pendingSlices=i.pendingSlices,this.runWorker(n)}})}consolidateEverythingIntoOneWorker(e){const t=new Set(e.pendingSlices);for(let i=0;i<this.workers.length;i++){const n=this.workers[i];if(n!==e){for(const s of n.pendingSlices)t.add(s);n.aborted=!0,n.pendingSlices.length=0,this.workers.splice(i,1),i--}}for(let i=0;i<this.queuedReads.length;i++){const n=this.queuedReads[i];for(const s of n.pendingSlices)t.add(s)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){g(!e.aborted);const i=e.currentPos,n=i+t.length;this.insertIntoCache({start:i,end:n,bytes:t,view:_e(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let s=0;s<e.pendingSlices.length;s++){const a=e.pendingSlices[s],o=Math.max(i,a.start),c=Math.min(n,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-i,c-i),o-a.start);for(let l=0;l<a.holes.length;l++){const u=a.holes[l];i<=u.start&&n>u.start&&(u.start=n),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){const a=this.workers[s];e===a||a.running||ps(i,n,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),s--)}}supplyFileSize(e){g(this.fileSize===null),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let i=0;i<t.pendingSlices.length;i++){const n=t.pendingSlices[i];for(const s of n.holes)if(s.end>e){n.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t<this.queuedReads.length;t++){const i=this.queuedReads[t];if(i.hole.start>=e){for(const n of i.pendingSlices)n.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let n=0;n<i.pendingSlices.length;n++){const s=i.pendingSlices[n];s.start>=e&&(s.resolve(null),i.pendingSlices.splice(n,1),n--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);g(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=ye(this.cache,e.start,i=>i.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const n=new Uint8Array(e.end-i.start);n.set(i.bytes,0),n.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=n,i.view=_e(n),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i<this.cache.length;i++){const n=this.cache[i];if(e.end<=n.start)break;if(e.end>=n.end){this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length,i--;continue}const s=new Uint8Array(n.end-e.start);s.set(e.bytes,0),s.set(n.bytes,n.start-e.start),this.currentCacheSize-=e.end-n.start,e.bytes=s,e.view=_e(s),e.end=n.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,n=this.cache[0];for(let s=1;s<this.cache.length;s++){const a=this.cache[s];a.age<n.age&&(i=s,n=a)}if(this.currentCacheSize-n.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=n.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}class zf extends It{constructor(e,t,i){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=i??null}_getFileSize(){const e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:De(e-this._offset,0,this._length??1/0)}_read(e,t,i,n){if(this._length!==null&&t>this._length)return null;const s=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+n),a=o=>o?(o.offset-=this._offset,o):null;return s instanceof Promise?s.then(a):a(s)}_dispose(){var e;(e=this._ref)==null||e.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}/*! 350 * Copyright (c) 2026-present, Vanilagy and contributors 351 * 352 * This Source Code Form is subject to the terms of the Mozilla Public 353 * License, v. 2.0. If a copy of the MPL was not distributed with this 354 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 355 */var Va=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},La=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}
355if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});const Ff=/^0[xX][0-9a-fA-F]+$/,Bf=/^data:.*;base64,/i;class Wa extends Sf{constructor(e,t,i,n){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=n}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await bn(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){var T;let e=this.nextLines;if(this.nextLines=null,!e){const P={stack:[],error:void 0,hasError:!1};try{const _=Va(P,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),I=await new $i(_.source).requestEntireFile();g(I),e=Vc(I,I.length,{ignore:dc}),_.source instanceof ni&&(this.rootPath=_.source.rootPath)}catch(_){P.error=_,P.hasError=!0}finally{La(P)}}const t=((T=this.input._formatOptions.hls)==null?void 0:T.offsetTimestampsByDateTime)!==!1;let i=!1,n=0,s=null,a=null,o=null,c=0,l=null,u=null,d=null,f=null,m=null,p=null,h=!1,b=Be(this.segments)??null;const y=P=>{const _=P.indexOf("@"),S=Number(_===-1?P:P.slice(0,_));if(!Number.isInteger(S)||S<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${P}'.`);let I=null;if(_!==-1&&(I=Number(P.slice(_+1)),!Number.isInteger(I)||I<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${P}'.`);return{length:S,offset:I}},x=P=>{c=P,b&&(g(b.sequenceNumber!==null),b.sequenceNumber<P&&(n=b.timestamp+b.duration,l=b.firstSegment,u=b.initSegment,m=b.lastProgramDateTimeSeconds,s=b.unixEpochTimestamp!==null?b.unixEpochTimestamp+b.duration:null,b=null))};for(let P=0;P<e.length;P++){const _=e[P];if(!i){if(_!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0;continue}if(!_.startsWith("#")){if(!b){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let S=o;if(S&&S.method==="AES-128"&&!S.iv){const A=new Uint8Array(Pt),H=_e(A);H.setUint32(8,Math.floor(c/2**32)),H.setUint32(12,c),S={...S,iv:A}}const C={path:cr(this.rootPath,_),offset:(f==null?void 0:f.offset)??0,length:(f==null?void 0:f.length)??null},v={timestamp:n,unixEpochTimestamp:s,firstSegment:l,sequenceNumber:c,location:C,duration:a,encryption:S,initSegment:u,lastProgramDateTimeSeconds:m};l??(l=v),n+=a,s!==null&&(s+=a),this.segments.push(v)}a=null,f===null?d=null:f=null,x(c+1)}if(_.startsWith(_s)){if(b){h=!0;continue}h||(m===null&&c>0&&p!==null&&(n=c*p),h=!0);const S=_.slice(_s.length),I=S.indexOf(","),C=I===-1?S:S.slice(0,I),v=Number(C);if(!Number.isFinite(v)||v<0)throw new Error(`Invalid #EXTINF tag duration '${C}'.`);a=v}else if(_.startsWith(Ea)){const S=new wi(_.slice(Ea.length)),I=S.get("uri");if(!I)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const C=S.get("byterange");let v=null;if(C!==null&&(v=y(C)),v&&v.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!b){const H={path:cr(this.rootPath,I),offset:(v==null?void 0:v.offset)??0,length:(v==null?void 0:v.length)??null};if((o==null?void 0:o.method)==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");u={timestamp:n,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:H,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:m}}a=null,f===null?d=null:f=null}else if(_.startsWith(Aa)){const S=new wi(_.slice(Aa.length)),I=S.get("method");if(I==="NONE")o=null;else if(I==="AES-128"){const C=S.get("uri");if(!C)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let v=null;const A=S.get("iv");if(A){if(!Ff.test(A))throw new Error(`Unsupported IV format '${A}'.`);let M=A.slice(2);M=M.padStart(Pt*2,"0"),v=new Uint8Array(Pt);for(let D=0;D<Pt;D++){const $=-Pt*2+D;v[D]=parseInt(M.slice($,$+2),16)}}const H=S.get("keyformat")??"identity";if(H!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");
355o={method:"AES-128",keyUri:cr(this.rootPath,C),iv:v,keyFormat:H}}else if(I==="SAMPLE-AES"||I==="SAMPLE-AES-CTR"){const C=S.get("uri");if(!C)throw new Error(`Invalid #EXT-X-KEY: ${I} requires a URI attribute.`);if((S.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let A=null;if(Bf.test(C)){const H=C.indexOf(","),M=vo(C.slice(H+1));if(M.length>=8&&M[4]===112&&M[5]===115&&M[6]===115&&M[7]===104){const D=_e(M).getUint32(0);A=Go(M.subarray(8,Math.min(D,M.length)))}}o={method:I,psshBox:A}}else throw new Error(`Unsupported encryption method '${I}'. If you think this method should be supported, please raise an issue.`)}else if(_.startsWith(za)){const S=_.slice(za.length),I=Number(S);if(!Number.isInteger(I)||I<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${S}'.`);x(I)}else if(_.startsWith(Fa)){const S=y(_.slice(Fa.length));if(S.offset===null){if(d===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");S.offset=d}f=S,d=S.offset+S.length}else if(_.startsWith(Ba)){if(b)continue;const S=_.slice(Ba.length),I=Date.parse(S);if(!Number.isFinite(I))continue;const C=I/1e3;if(m===C)continue;if(m===null&&this.segments.length>0){const v=Be(this.segments),A=v.timestamp+v.duration,H=C-A;for(const M of this.segments)M.unixEpochTimestamp=M.timestamp+H,t&&(M.timestamp=M.unixEpochTimestamp)}m=C,s=C,t&&(n=C)}else if(_===xf)l=null;else if(_.startsWith(Ra)){const S=_.slice(Ra.length),I=Number(S);if(!Number.isFinite(I)||I<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${S}'.`);this.refreshInterval=I,p=I}else if(_===Tf){this.streamHasEnded=!0;break}else _.startsWith(Ma)&&_.slice(Ma.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const n=ye(this.segments,e,a=>a.timestamp);if(n===-1)return null;if(n<this.segments.length-1||this.streamHasEnded||i)return this.segments[n];const s=this.segments[n];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getNextSegment(e,t){const i=this.segments.indexOf(e);g(i!==-1);const n=i+1;let s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(n<this.segments.length)return this.segments[n];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){const t=this.segments.indexOf(e);return g(t!==-1),this.segments[t-1]??null}getInputForSegment(e){var c;const t=e,i=this.inputCache.find(l=>l.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let n=null;(t.initSegment||t.firstSegment)&&(n=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:((c=this.input._formatOptions.isobmff)==null?void 0:c.resolveKeyId)&&(l=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(l);let u=l.psshBoxes;const{psshBox:d}=t.encryption;return(d.keyIds===null||d.keyIds.includes(l.keyId))&&!u.some(f=>Xo(f,d))&&(u=[...u,d]),this.input._formatOptions.isobmff.resolveKeyId({...l,psshBoxes:u})})}},a=new zr({source:new vf(t.location.path,async l=>{g(l.isRoot);const u={...l,isRoot:!1};let d;const f=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(d=await this.input._getSourceCached(u),f){const p=d.source.slice(t.location.offset,t.location.length??void 0).ref();d.free(),d=p}}else if(t.encryption.method==="AES-128"){const m=t.encryption;g(m.iv);
355let p=await this.input._getSourceCached(u);if(f){const x=p.source.slice(t.location.offset,t.location.length??void 0).ref();p.free(),p=x}const h=new $i(p.source),b=Md(h,async()=>{const y={stack:[],error:void 0,hasError:!1};try{const x=Va(y,await this.input._getSourceCached({path:m.keyUri,isRoot:!1},Ah),!1),P=await new $i(x.source).requestSlice(0,Pt);if(!P)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:se(P,Pt),iv:m.iv}}catch(x){y.error=x,y.hasError=!0}finally{La(y)}},()=>{p.free()});d=new Af(b).ref()}else g(!1);return d}),formats:this.input._formats.filter(l=>!(l instanceof Tc)),initInput:n??void 0,formatOptions:s});if(a._onFormatDetermined=l=>{var u,d;if((((u=t.encryption)==null?void 0:u.method)==="SAMPLE-AES"||((d=t.encryption)==null?void 0:d.method)==="SAMPLE-AES-CTR")&&!l._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){const l=Ds(this.inputCache,u=>u.age);g(l!==-1),this.inputCache.splice(l,1)}return a}
355async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}/*! 356 * Copyright (c) 2026-present, Vanilagy and contributors 357 * 358 * This Source Code Form is subject to the terms of the Mozilla Public 359 * License, v. 2.0. If a copy of the MPL was not distributed with this 360 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 361 */class Rf extends ir{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{g(this.input._rootSource instanceof ni);const e=await this.input._reader.requestEntireFile();g(e);const t=Vc(e,e.length,{ignore:dc}),{rootPath:i}=this.input._rootSource,n=[],s=[];for(let d=1;d<t.length;d++){const f=t[d];if(f.startsWith(Pa)){const m=d,p=t[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const h=cr(i,p),b=new wi(f.slice(Pa.length));if(b.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");n.push({fullPath:h,attributes:b,lineNumber:m,hasOnlyKeyPackets:!1})}else if(f.startsWith(Ca)){const m=new wi(f.slice(Ca.length)),p=m.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(m.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const b=cr(i,p);n.push({fullPath:b,attributes:m,lineNumber:d,hasOnlyKeyPackets:!0})}else if(f.startsWith(Ia)){const m=new wi(f.slice(Ia.length));if(m.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(m.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let b=null;const y=m.get("uri");y!==null&&(b=cr(i,y)),s.push({fullPath:b,attributes:m,lineNumber:d})}else if(f!==_f){if(f.startsWith(_s)){const m=new Wa(this,i,null,t);this.segmentedInputs=[m],this.hasMasterPlaylist=!1,this.trackBackings=await m.getTrackBackings();return}}}const a=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(n.map(async(d,f)=>{const m=[],p=d.attributes.get("codecs");let h;if(p)h=p.split(",").map(v=>v.trim());
361else{const A=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),H=await Promise.all(A.map(async M=>({track:M,codec:await M.getCodec()})));h=await Promise.all(H.filter(M=>M.codec!==null).map(M=>M.track.getDecoderConfig().then(D=>D.codec)))}const b=d.attributes.get("video"),y=d.attributes.get("audio"),x=h.some(v=>wt.includes(Pr(v))),T=h.some(v=>Jt.includes(Pr(v)));if(b!==null&&!x){if(!a.includes(b))throw new Error(`Invalid M3U8 file; variant stream references video group "${b}" which is not defined in any #EXT-X-MEDIA tags.`);const v=s.find(A=>{const H=A.attributes.get("group-id"),M=A.attributes.get("type");return H===b&&M.toLowerCase()==="video"});e:if(v){const A=v.attributes.get("uri");if(A===null)break e;const H=cr(i,A),$=(await this.getSegmentedInputForPath(H).getTrackBackings()).find(O=>O.getType()==="video");if(!$||await $.getCodec()===null)break e;const B=await $.getDecoderConfig().then(O=>(O==null?void 0:O.codec)??null);g(B!==null),h.push(B)}}if(y!==null&&!T){if(!o.includes(y))throw new Error(`Invalid M3U8 file; variant stream references audio group "${y}" which is not defined in any #EXT-X-MEDIA tags.`);const v=s.find(A=>{const H=A.attributes.get("group-id"),M=A.attributes.get("type");return H===y&&M.toLowerCase()==="audio"});e:if(v){const A=v.attributes.get("uri");if(A===null)break e;
361const H=cr(i,A),$=(await this.getSegmentedInputForPath(H).getTrackBackings()).find(O=>O.getType()==="audio");if(!$||await $.getCodec()===null)break e;const B=await $.getDecoderConfig().then(O=>(O==null?void 0:O.codec)??null);g(B!==null),h.push(B)}}h=[...new Set(h)];let P=null,_=null;const S=d.attributes.getAsNumber("bandwidth");g(S!==null);const I=d.attributes.getAsNumber("average-bandwidth"),C=d.attributes.get("name");for(const v of h){const A=Pr(v);if(A!==null){if(wt.includes(A)){if(P!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");P=v;const H=d.attributes.get("video");if(H===null){const M=d.attributes.get("resolution");let D=null,$=null;if(M){const B=M.match(/^(\d+)x(\d+)$/);B&&(D=Number(B[1]),$=Number(B[2]))}m.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:He,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:P,pairingMask:1n<<BigInt(f),peakBitrate:S,averageBitrate:I,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:D,height:$}})}else{if(!a.includes(H))throw new Error(`Invalid M3U8 file; variant stream references video group "${H}" which is not defined in any #EXT-X-MEDIA tags.`);for(const M of s){const D=M.attributes.get("group-id"),$=M.attributes.get("type");if(D!==H||$.toLowerCase()!=="video")continue;const B=M.attributes.get("resolution")??d.attributes.get("resolution");let O=null,X=null;if(B){const ae=B.match(/^(\d+)x(\d+)$/);ae&&(O=Number(ae[1]),X=Number(ae[2]))}m.push({id:-1,demuxer:this,backingTrack:null,default:Oi(M.attributes),autoselect:Oi(M.attributes)||Ha(M.attributes),languageCode:qa(M.attributes.get("language")),lineNumber:M.lineNumber,fullPath:M.fullPath??d.fullPath,fullCodecString:P,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:M.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:O,height:X}})}}}else if(Jt.includes(A)){if(_!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");_=v;const H=d.attributes.get("audio");if(H===null){const M=d.attributes.get("channels"),D=M!==null?Number(M.split("/")[0]):null;m.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:He,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:_,pairingMask:1n<<BigInt(f),peakBitrate:S,averageBitrate:I,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:D!==null&&Number.isInteger(D)&&D>0?D:null}})}else{if(!o.includes(H))throw new Error(`Invalid M3U8 file; variant stream references audio group "${H}" which is not defined in any #EXT-X-MEDIA tags.`);for(const M of s){const D=M.attributes.get("group-id"),$=M.attributes.get("type");if(D!==H||$.toLowerCase()!=="audio")continue;const B=M.attributes.get("channels")??d.attributes.get("channels"),O=B!==null?Number(B.split("/")[0]):null;m.push({id:-1,demuxer:this,backingTrack:null,default:Oi(M.attributes),autoselect:Oi(M.attributes)||Ha(M.attributes),languageCode:qa(M.attributes.get("language")),lineNumber:M.lineNumber,fullPath:M.fullPath??d.fullPath,fullCodecString:_,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:M.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:O!==null&&Number.isInteger(O)&&O>0?O:null}})}}}}}return m})),l=[],u=d=>{const f=l.find(m=>m.fullPath===d.fullPath&&m.info.type===d.info.type);f?(f.pairingMask|=d.pairingMask,f.default||(f.default=d.default),f.autoselect||(f.autoselect=d.autoselect),f.lineNumber=Math.min(f.lineNumber,d.lineNumber),d.peakBitrate!==null&&(f.peakBitrate=Math.max(f.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(f.averageBitrate=Math.max(f.averageBitrate??-1/0,d.averageBitrate)),f.languageCode===He&&(f.languageCode=d.languageCode)):(d.id=l.length+1,l.push(d))};for(const d of c)for(const f of d)u(f);l.sort((d,f)=>d.lineNumber-f.lineNumber),this.trackBackings=[];for(const d of l)d.info.type==="video"?this.trackBackings.push(new kc(d)):this.trackBackings.push(new yc(d));this.internalTracks=l})())}async getTrackBackings(){return await this.readMetadata(),g(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(n=>n.path===e);if(t)return t;let i=null;return this.internalTracks&&(i=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),t=new Wa(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return uc}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class bc{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const n=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(n.length===1)t=n[0];else if(this instanceof kc){for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}else{g(this instanceof yc);for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...rr,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){g(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}
vendor: 1,594 bytes, line 361
361async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class kc extends bc{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Pr(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}
361async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class yc extends bc{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Pr(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const Oi=r=>{const e=r.get("default");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},Ha=r=>{const e=r.get("autoselect");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},qa=r=>{if(r===null)return He;const e=r.split("-")[0];return e||He};/*! 362 * Copyright (c) 2026-present, Vanilagy and contributors 363 * 364 * This Source Code Form is subject to the terms of the Mozilla Public 365 * License, v. 2.0. If a copy of the MPL was not distributed with this 366 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 367 */class zt{constructor(){this._isIsobmff=!1}}class wc extends zt{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);const i=Re(t,4);return i!=="ftyp"&&i!=="styp"?null:Re(t,4)}_createDemuxer(e){return new Gs(e)}}class Mf extends wc{async _canReadInput(e){const t=await this._getMajorBrand(e);if(t!==null)return t!=="qt ";let i=e._reader.requestSlice(4,4);if(i instanceof Promise&&(i=await i),!i)return!1;const n=Re(i,4);return n==="moof"||n==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Of extends wc{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class xc extends zt{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,jt);if(i instanceof Promise&&(i=await i),!i)return!1;const n=rc(i);if(n===null||n<1||n>8||me(i,n)!==W.EBML)return!1;const a=ic(i);if(typeof a!="number")return!1;let o=e._reader.requestSlice(i.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;const c=i.filePos;for(;o.filePos<=c+a-dt;){const l=Ht(o);if(!l)break;const{id:u,size:d}=l,f=o.filePos;if(d===void 0)return!1;switch(u){case W.EBMLVersion:if(me(o,d)!==1)return!1;break;case W.EBMLReadVersion:if(me(o,d)!==1)return!1;break;case W.DocType:if(Hr(o,d)!==t)return!1;break;case W.DocTypeVersion:if(me(o,d)>4)return!1;break}o.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new $d(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Df extends xc{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Nf extends zt{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,ht);if(d instanceof Promise&&(d=await d),!d)break;const f=tr(d);if(!f)break;t=d.filePos+f.size}const i=await xs(e._reader,t,t+4096);if(!i)return!1;const n=i.header,s=zo(n.mpegVersionId,n.channel);let a=e._reader.requestSlice(i.startPos+s,4);if(a instanceof Promise&&(a=await a),!a)return!1;const o=K(a);if(o===Eo||o===Ao)return!0;t=i.startPos+i.header.totalSize;const l=await xs(e._reader,t,t+Cr);if(!l)return!1;const u=l.header;return!(n.channel!==u.channel||n.sampleRate!==u.sampleRate)}_createDemuxer(e){return new Gd(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}
367class Uf extends zt{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const i=Re(t,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(t.skip(4),Re(t,4)==="WAVE")}_createDemuxer(e){return new sf(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Vf extends zt{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?Re(t,4)==="OggS":!1}_createDemuxer(e){return new rf(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Lf extends zt{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,ht);if(n instanceof Promise&&(n=await n),!n)break;const s=tr(n);if(!s)break;t=n.filePos+s.size}let i=e._reader.requestSlice(t,4);return i instanceof Promise&&(i=await i),i?Re(i,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new pf(e)}}class Wf extends zt{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,ht);if(a instanceof Promise&&(a=await a),!a)break;const o=tr(a);if(!o)break;t=a.filePos+o.size}let i=e._reader.requestSliceRange(t,an,Ir);if(i instanceof Promise&&(i=await i),!i)return!1;const n=Ar(i);if(!n||(t+=n.frameLength,i=e._reader.requestSliceRange(t,an,Ir),i instanceof Promise&&(i=await i),!i))return!1;const s=Ar(i);return s?n.objectType===s.objectType&&n.samplingFrequencyIndex===s.samplingFrequencyIndex&&n.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new of(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Hf extends zt{async _canReadInput(e){const t=et+16+1;let i=e._reader.requestSlice(0,t);if(i instanceof Promise&&(i=await i),!i)return!1;const n=se(i,t);return n[0]===71&&n[et]===71||n[0]===71&&n[et+16]===71?!0:n[4]===71&&n[4+et+4]===71}_createDemuxer(e){return new kf(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Tc extends zt{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||!(Re(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof ni))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new Rf(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return uc}}const qf=new Mf,$f=new Of,jf=new xc,Kf=new Df,Gf=new Nf,Xf=new Uf,Qf=new Vf,Yf=new Wf,Zf=new Lf,Jf=new Hf,eh=new Tc,cn=[eh,qf,$f,jf,Kf,Xf,Qf,Zf,Gf,Yf,Jf],th=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(r.hls!==void 0){if(!r.hls||typeof r.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(r.hls.offsetTimestampsByDateTime!==void 0&&typeof r.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};/*! 368 * Copyright (c) 2026-present, Vanilagy and contributors 369 * 370 * This Source Code Form is subject to the terms of the Mozilla Public 371 * License, v. 2.0. If a copy of the MPL was not distributed with this 372 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 373 */var rh=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},ih=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else n|=1}catch(o){t(o)}
373if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});Os();let $a=-1/0,ja=-1/0,rt=null;typeof FinalizationRegistry<"u"&&(rt=new FinalizationRegistry(r=>{const e=performance.now();r.type==="video"?(e-$a>=1e3&&(ue._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),$a=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-ja>=1e3&&(ue._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),ja=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));class pr{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Ss=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],nh=new Set(Ss);class je{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(lr*this.timestamp)}get microsecondDuration(){return Math.trunc(lr*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var i,n,s,a,o,c,l,u;if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!nh.has(t.format))throw new TypeError("init.format must be one of: "+Ss.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const m of t.layout){if(!m||typeof m!="object"||Array.isArray(m))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(m.offset)||m.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(m.stride)||m.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&ua(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;const d=t.layout??oh(t.format,t.codedWidth,t.codedHeight);let f=t.colorSpace??null;f===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?f={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:f={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:((i=t.visibleRect)==null?void 0:i.left)??0,top:((n=t.visibleRect)==null?void 0:n.top)??0,width:((s=t.visibleRect)==null?void 0:s.width)??t.codedWidth,height:((a=t.visibleRect)==null?void 0:a.height)??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotC
373opy?Ge(e):Ge(e).slice(),this._layout=d,this.colorSpace=new $n(f)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if((t==null?void 0:t.rotation)!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if((t==null?void 0:t.timestamp)!==void 0&&!Number.isFinite(t==null?void 0:t.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if((t==null?void 0:t.duration)!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");(t==null?void 0:t.visibleRect)!==void 0&&ua(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:((o=e.visibleRect)==null?void 0:o.x)??0,top:((c=e.visibleRect)==null?void 0:c.y)??0,width:((l=e.visibleRect)==null?void 0:l.width)??e.codedWidth,height:((u=e.visibleRect)==null?void 0:u.height)??e.codedHeight},this.rotation=(t==null?void 0:t.rotation)??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=(t==null?void 0:t.timestamp)??e.timestamp/1e6,this.duration=(t==null?void 0:t.duration)??(e.duration??0)/1e6,this.colorSpace=new $n(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new je(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*lr),duration:Math.trunc((t.duration??0)*lr)||void 0}),t);let d=0,f=0;if("naturalWidth"in e?(d=e.naturalWidth,f=e.naturalHeight):"videoWidth"in e?(d=e.videoWidth,f=e.videoHeight):"width"in e&&(d=Number(e.width),f=Number(e.height)),!d||!f)throw new TypeError("Could not determine dimensions.");const m=new OffscreenCanvas(d,f),p=m.getContext("2d",{alpha:Ji(),willReadFrequently:!0});if(!p)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");p.drawImage(e,0,0),this._data=m,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:d,height:f},this.squarePixelWidth=d,this.squarePixelHeight=f,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new $n({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof pr){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!Ss.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace
373=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=(t==null?void 0:t.encodeOptions)??{},this.pixelAspectRatio=en({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),rt==null||rt.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),this._data instanceof pr?new je(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):oi(this._data)?new je(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(g(this._layout),new je(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new je(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(rt==null||rt.unregister(this),this._data instanceof pr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):oi(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ga(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return oi(this._data)?this._data.allocationSize(e):Xa(this,e).allocationSize}async copyTo(e,t={}){if(!hn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ga(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(g(this._data!==null),oi(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof pr){const l={stack:[],error:void 0,hasError:!1};try{const u=rh(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof je))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(u.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${u.format}' instead.`);return await u.copyTo(e,t)}catch(u){l.error=u,l.hasError=!0}finally{ih(l)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const l=this.toVideoFrame(),u=await l.copyTo(e,t);return l.close(),u}const i=Xa(this,t);g(this.format);const n=Ge(e);if(n.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${n.byteLength}`);const s=vn(this.format);let a;if(this._data instanceof pr){let l=this._data.getDataPlanes();if(l instanceof Promise&&(l=await l),!Array.isArray(l)||l.some(u=>!(u.data instanceof Uint8Array)||!Number.isInteger(u.stride)||u.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=l}else if(this._data instanceof Uint8Array)g(this._layout),g(this._layout.length===s.length),a=this._layout.map((l,u)=>{const d=Math.ceil(this.codedHeight/s[u].heightDivisor);return{data:this._data.subarray(l.offset,l.offset+l.stride*d),stride:l.stride}});else{const u=this._data.getContext("2d");g(u);const d=u.getImageData(0,0,this.codedWidth,this.codedHeight);
373a=[{data:Ge(d.data),stride:4*this.codedWidth}]}const o=[],c=s.length;for(let l=0;l<c;l++){const u=i.computedLayouts[l],d=a[l].stride,f=a[l].data;let m=u.sourceTop*d;m+=u.sourceLeftBytes;let p=u.destinationOffset;const h=u.sourceWidthBytes,b={offset:p,stride:u.destinationStride};for(let y=0;y<u.sourceHeight;y++){if(m+h>f.byteLength)throw new Error("Source buffer OOB read.");if(p+h>n.byteLength)throw new Error("Destination buffer OOB write.");const x=f.subarray(m,m+h);n.set(x,p),m+=d,p+=u.destinationStride}o.push(b)}if(t.format!==void 0){const l=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),u=this.format.includes("X")&&t.format.includes("A");if(l||u)for(let d=0;d<i.allocationSize;d+=4){if(l){const f=n[d],m=n[d+2];n[d]=m,n[d+2]=f}u&&(n[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof pr){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(e instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((a,o)=>a+o.data.byteLength,0),i=new Uint8Array(t);let n=0;const s=[];for(const a of e)i.set(a.data,n),s.push(n),n+=a.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return oi(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(g(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,n,s,a,o,c,l){let u=0,d=0,f=this.displayWidth,m=this.displayHeight,p=0,h=0,b=this.displayWidth,y=this.displayHeight;if(a!==void 0?(u=t,d=i,f=n,m=s,p=a,h=o,c!==void 0?(b=c,y=l):(b=f,y=m)):(p=t,h=i,n!==void 0&&(b=n,y=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(h))throw new TypeError("dy must be a number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:f,sHeight:m}=this._rotateSourceRegion(u,d,f,m,this.rotation));const x=this.toCanvasImageSource();e.save();const T=p+b/2,P=h+y/2;e.translate(T,P),e.rotate(this.rotation*Math.PI/180);const _=this.rotation%180===0?1:b/y;e.scale(1/_,_),e.drawImage(x,u,d,f,m,-b/2,-y/2,b,y),e.restore()}drawWithFit(e,t){var x,T,P,_;if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");
373if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&ln(t.crop,"options.");const i=e.canvas.width,n=e.canvas.height,s=t.rotation??this.rotation,[a,o]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=t.crop;c&&(c=vs(c,a,o));let l,u,d,f;const{sx:m,sy:p,sWidth:h,sHeight:b}=this._rotateSourceRegion(((x=t.crop)==null?void 0:x.left)??0,((T=t.crop)==null?void 0:T.top)??0,((P=t.crop)==null?void 0:P.width)??a,((_=t.crop)==null?void 0:_.height)??o,s);if(t.fit==="fill")l=0,u=0,d=i,f=n;else{const[S,I]=t.crop?[t.crop.width,t.crop.height]:[a,o],C=t.fit==="contain"?Math.min(i/S,n/I):Math.max(i/S,n/I);d=S*C,f=I*C,l=(i-d)/2,u=(n-f)/2}e.save();const y=s%180===0?1:d/f;e.translate(i/2,n/2),e.rotate(s*Math.PI/180),e.scale(1/y,y),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),m,p,h,b,l,u,d,f),e.restore()}_rotateSourceRegion(e,t,i,n,s){return s===90?[e,t,i,n]=[t,this.squarePixelHeight-e-i,n,i]:s===180?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-n]:s===270&&([e,t,i,n]=[this.squarePixelWidth-t-n,e,n,i]),{sx:e,sy:t,sWidth:i,sHeight:n}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof pr||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&ln(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=zs(this.rotation+(e.rotate??0)),[i,n]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=vs(s,i,n));const a=s?s.width:i,o=s?s.height:n,c=a/o;let l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=o),l=fs(l,e.roundDimensionsTo??1),u=fs(u,e.roundDimensionsTo??1);const d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:s??{left:0,top:0,width:i,height:n},alpha:e.alpha??"keep"};for(const h of sh){let b=h(this,d);if(b instanceof Promise&&(b=await b),b!==null)return b}let f=null,m=!1;for(const h of ai)if(h.canvas.width===d.width&&h.canvas.height===d.height){f=h.canvas,h.age=Ka++;break}if(f===null){if(typeof OffscreenCanvas<"u")f=new OffscreenCanvas(d.width,d.height);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");f=document.createElement("canvas"),f.width=d.width,f.height=d.height}m=!0,ai.length>=ah&&ai.splice(Ds(ai,h=>h.age),1),ai.push({canvas:f,age:Ka++})}const p=f.getContext("2d",{alpha:!0});if(!p)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return d.alpha==="discard"?(p.fillStyle="black",p.fillRect(0,0,d.width,d.height)):m||p.clearRect(0,0,d.width,d.height),this.drawWithFit(p,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new je(f,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const sh=[],ah=3,ai=[];let Ka=0;class $n{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(ei);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(ti);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const n=Object.keys(ri);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);
373if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=(e==null?void 0:e.primaries)??null,this.transfer=(e==null?void 0:e.transfer)??null,this.matrix=(e==null?void 0:e.matrix)??null,this.fullRange=(e==null?void 0:e.fullRange)??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const oi=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,vs=(r,e,t)=>{const i=Math.min(r.left,e),n=Math.min(r.top,t),s=Math.min(r.width,e-i),a=Math.min(r.height,t-n);return g(s>=0),g(a>=0),{left:i,top:n,width:s,height:a}},ln=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ga=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'dis
373play-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},oh=(r,e,t)=>{const i=vn(r),n=[];let s=0;for(const a of i){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),l=o*a.sampleBytes,u=l*c;n.push({offset:s,stride:l}),s+=u}return n},vn=r=>{const e=(t,i,n,s,a)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:s},{sampleBytes:i,widthDivisor:n,heightDivisor:s}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Et(r),g(!1)}},Xa=(r,e)=>{const t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},i=e.rect,n=ch(t,i,r.codedWidth,r.codedHeight,r.format),s=e.layout;let a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return uh(n,a,s)},ch=(r,e,t,i,n)=>{const s={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>i)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!lh(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},lh=(r,e)=>{if(r===null)return!0;const t=vn(r);for(let i=0;i<t.length;i++){const n=t[i],s=n.widthDivisor,a=n.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},uh=(r,e,t)=>{const i=vn(e),n=i.length;if(t!==void 0&&t.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const a=[],o=[];for(let c=0;c<n;c++){const l=i[c],u=l.sampleBytes,d=l.widthDivisor,f=l.heightDivisor,m={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(m.sourceTop=Math.ceil(Math.trunc(r.y||0)/f),m.sourceHeight=Math.ceil(Math.trunc(r.height||0)/f),m.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*u,m.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*u,t!==void 0){const b=t[c];
373if(b.stride<m.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);m.destinationOffset=b.offset,m.destinationStride=b.stride}else m.destinationOffset=s,m.destinationStride=m.sourceWidthBytes;const h=m.destinationStride*m.sourceHeight+m.destinationOffset;if(h>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(h),s=Math.max(s,h);for(let b=0;b<c;b++){const y=a[b];if(!(o[c]<=y.destinationOffset||o[b]<=m.destinationOffset))throw new TypeError("Planes overlap.")}a.push(m)}return{allocationSize:s,computedLayouts:a}},Di=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ci{constructor(){this._referenceCount=0}}class Ke{get microsecondTimestamp(){return Math.trunc(lr*this.timestamp)}get microsecondDuration(){return Math.trunc(lr*this.duration)}constructor(e){if(this._closed=!1,li(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof ci){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Di.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Di.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e==null?void 0:e.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(or(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*or(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}rt==null||rt.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Di.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const s=or(t),a=kr(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?n:n*this.numberOfChannels)*s}copyTo(e,t){if(!hn(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Di.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:n,frameOffset:s}=t;let{planeIndex:a}=t;const o=this.format,c=i??this.format;if(!c)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");const f=n!==void 0?n:l-d;if(f>l-d)throw new RangeError("frameCount out of range");const m=or(c),p=kr(c);if(p&&a>=u)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");const b=(p?f:f*u)*m;if(e.byteLength<b)throw new RangeError("Destination buffer is too small");const y=_e(e),x=Sc(c);if(li(this._data))bi()&&u>2&&c!==o?fh(this._data,y,o,c,u,a,d,f):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:c});else{const T=_c(o),P=or(o),_=kr(o);let S;if(this._data instanceof ci){const C=v=>{const A=this._data.getDataPlane(v);if(!(A instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const H=l*P*(_?1:u);if(A.byteLength!==H)throw new TypeError(`Data plane ${v}
373 has invalid size. Expected exactly ${H} bytes, got ${A.byteLength} bytes.`);return A};if(_)if(p)S=C(a),a=0;else{S=new Uint8Array(l*P*u);for(let v=0;v<u;v++){const A=C(v);S.set(A,v*l*P)}}else S=C(0)}else S=this._data;const I=_e(S);for(let C=0;C<f;C++)if(p){const v=C*m;let A;_?A=(a*l+(C+d))*P:A=((C+d)*u+a)*P;const H=T(I,A);x(y,v,H)}else for(let v=0;v<u;v++){const H=(C*u+v)*m;let M;_?M=(v*l+(C+d))*P:M=((C+d)*u+v)*P;const D=T(I,M);x(y,H,D)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof ci){const e=new Ke(this._data);return e.setTimestamp(this.timestamp),e}else if(li(this._data)){const e=new Ke(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new Ke({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endSample must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startSample out of range.");if(t>this.numberOfFrames)throw new RangeError("endSample out of range.");if(t<e)throw new RangeError("endSample must not be less than startSample.");if(this._closed)throw new Error("AudioSample is closed.");const i=t-e,n=or(this.format);let s;if(kr(this.format)){const a=i*n;if(s=new Uint8Array(a*this.numberOfChannels),i>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(s.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:i})}else s=new Uint8Array(i*this.numberOfChannels*n),i>0&&this.copyTo(s,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Ke({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(rt==null||rt.unregister(this),this._data instanceof ci?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):li(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof ci?this._createAudioDataFromData():li(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(kr(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let c=0,l=a;for(;l>0;){const u=Math.min(o,l),d=new Float32Array(n*u);for(let f=0;f<n;f++)e.copyFromChannel(d.subarray(f*u,(f+1)*u),f,c);yield new Ke({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:n,timestamp:t+c/s,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let c=0,l=a;const u=[];for(;l>0;){const d=Math.min(o,l),f=new Float32Array(n*d);for(let p=0;p<n;p++)e.copyFromChannel(f.subarray(p*d,(p+1)*d),p,c);const m=new Ke({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:n,timestamp:t+c/s,data:f});u.push(m),c+=d,l-=d}return u}}const or=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},kr=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_c=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Sc=r=>{switch(r){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,De((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,De(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,De(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},li=r=>typeof AudioData<"u"&&r instanceof AudioData,dh=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},fh=(r,e,t,i,n,s,a,o)=>{const c=_c(t),l=Sc(i),u=or(t),d=or(i),f=kr(t);if(kr(i))if(f){const p=new ArrayBuffer(o*u),h=_e(p);r.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){const y=b*u,x=b*d,T=c(h,y);l(e,x,T)}}else{const p=new ArrayBuffer(o*n*u),h=_e(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){const y=(b*n+s)*u,x=b*d,T=c(h,y);l(e,x,T)}}else if(f){const p=o*u,h=new ArrayBuffer(p),b=_e(h);for(let y=0;y<n;y++){r.copyTo(h,{planeIndex:y,frameOffset:a,frameCount:o,format:t});for(let x=0;x<o;x++){const T=x*u,P=(x*n+y)*d,_=c(b,T);l(e,P,_)}}}else{const p=new ArrayBuffer(o*n*u),h=_e(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++)for(let y=0;y<n;y++){const x=b*n+y,T=x*u,P=x*d,_=c(h,T);l(e,P,_)}}},hh=(r,e)=>{const t=r.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(t);return r.copyTo(i,{format:e,planeIndex:0}),new Ke({data:i,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};/*! 374 * Copyright (c) 2026-present, Vanilagy and contributors 375 * 376 * This Source Code Form is subject to the terms of the Mozilla Public 377 * License, v. 2.0. If a copy of the MPL was not distributed with this 378 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 379 */const Qa=new Map,Ya=new Map,mh=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!wt.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}
379'. Must be one of: ${wt.join(", ")}.`);if(!(r.bitrate instanceof hr)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.crop!==void 0&&ln(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");vc(r.codec,r)},vc=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Pr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},Pc=r=>{const e=r.bitrate instanceof hr?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??Yu(r.codec,r.width,r.height,e,r.alpha==="keep"),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:e,bitrateMode:r.bitrateMode,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...ed(r.codec)}},ph=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Jt.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${Jt.join(", ")}.`);
379if(r.bitrate===void 0&&!(Xe.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(r.bitrate!==void 0&&!(r.bitrate instanceof hr)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Cc(r.codec,r)},Cc=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Pr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},Ic=r=>{const e=r.bitrate instanceof hr?r.bitrate._toAudioBitrate(r.codec):r.bitrate;return{codec:r.fullCodecString??Ju(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:e,bitrateMode:r.bitrateMode,...td(r.codec)}};class hr{constructor(e){this._factor=e}_toVideoBitrate(e,t,i){const n=t*i,s=1920*1080,a=3e6,o=Math.pow(n/s,.95),c=a*o,l={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a},d=c*l[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(Xe.includes(e)||e==="flac")return;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let n=i*this._factor;return e==="aac"?n=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a):e==="opus"||e==="vorbis"?n=Math.max(6e3,n):e==="mp3"&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a)),Math.round(n/1e3)*1e3}}const Ec=new hr(1),Ac=new hr(2),gh=async(r,e={})=>{const{width:t=1280,height:i=720,bitrate:n=1e6,...s}=e;if(!wt.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(n instanceof hr)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer or a quality.");vc(r,s);const a=Pc({codec:r,width:t,height:i,bitrate:n,framerate:void 0,...s,alpha:"discard"}),o=JSON.stringify(a),c=Qa.get(o);if(c)return c;const l=(async()=>Bc.some(f=>f.supports(r,a))?!0:typeof VideoEncoder>"u"||(t%2===1||i%2===1)&&r==="avc"||!(await VideoEncoder.isConfigSupported(a)).supported?!1:Ji()?new Promise(async f=>{try{const m=new VideoEncoder({output:()=>{},error:()=>f(!1)});m.configure(a);const p=new Uint8Array(t*i*4),h=new VideoFrame(p,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});m.encode(h),h.close(),await m.flush(),f(!0)}catch{f(!1)}}):!0)();return Qa.set(o,l),l},bh=async(r,e={})=>{const{numberOfChannels:t=2,sampleRate:i=48e3,bitrate:n=128e3,...s}=e;if(!Jt.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(n instanceof hr)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer.");Cc(r,s);const a=Ic({codec:r,numberOfChannels:t,sampleRate:i,bitrate:n,...s}),o=JSON.stringify(a),c=Ya.get(o);if(c)return c;const l=(async()=>Rc.some(d=>d.supports(r,a))||Xe.includes(r)?!0:typeof AudioEncoder>"u"?!1:(await AudioEncoder.isConfigSupported(a)).supported===!0)();return Ya.set(o,l),l};/*! 380 * Copyright (c) 2026-present, Vanilagy and contributors 381 * 382 * This Source Code Form is subject to the terms of the Mozilla Public 383 * License, v. 2.0. If a copy of the MPL was not distributed with this 384 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 385 */const zc=[],Fc=[],Bc=[],Rc=[];/*! 386 * Copyright (c) 2026-present, Vanilagy and contributors 387 * 388 * This Source Code Form is subject to the terms of the Mozilla Public 389 * License, v. 2.0. If a copy of the MPL was not distributed with this 390 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 391 */const kh=r=>{let i=r,n=4096,s=0,a=12,o=0;for(i<0&&(i=-i,s=128),i+=33,i>8191&&(i=8191);
391(i&n)!==n&&a>=5;)n>>=1,a--;return o=i>>a-4&15,~(s|a-5<<4|o)&255},yh=r=>{let t=0,i=0,n=~r;n&128&&(n&=-129,t=-1),i=((n&240)>>4)+5;const s=(1<<i|(n&15)<<i-4|1<<i-5)-33;return t===0?s:-s},wh=r=>{let t=2048,i=0,n=11,s=0,a=r;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&t)!==t&&n>=5;)t>>=1,n--;return s=a>>(n===4?1:n-4)&15,(i|n-4<<4|s)^85},xh=r=>{let e=0,t=0,i=r^85;i&128&&(i&=-129,e=-1),t=((i&240)>>4)+4;let n=0;return t!==4?n=1<<t|(i&15)<<t-4|1<<t-5:n=i<<1|1,e===0?n:-n};/*! 392 * Copyright (c) 2026-present, Vanilagy and contributors 393 * 394 * This Source Code Form is subject to the terms of the Mozilla Public 395 * License, v. 2.0. If a copy of the MPL was not distributed with this 396 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 397 */const gr=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},Yt=r=>{if(!gn(r))throw new TypeError("timestamp must be a number.")},jn=(r,e,t)=>t.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;const n=await r.determinePacketType(i);return n&&(i.type=n),i}):e;class Zs{constructor(e){if(!(e instanceof Bi))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(gr(e),this._track.input._disposed)throw new tt;return jn(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){gr(e);const t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Yt(e),gr(t),this._track.input._disposed)throw new tt;return jn(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Ae))throw new TypeError("packet must be an EncodedPacket.");if(gr(t),this._track.input._disposed)throw new tt;return jn(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Yt(e),gr(t),this._track.input._disposed)throw new tt;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);return i&&(g(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i)}async getNextKeyPacket(e,t={}){if(!(e instanceof Ae))throw new TypeError("packet must be an EncodedPacket.");if(gr(t),this._track.input._disposed)throw new tt;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);return i&&(g(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,t):i)}packets(e,t,i={}){if(e!==void 0&&!(e instanceof Ae))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!(i!=null&&i.metadataOnly))throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof Ae))throw new TypeError("endPacket must be an EncodedPacket.");if(gr(i),this._track.input._disposed)throw new tt;const n=[];let{promise:s,resolve:a}=Ue(),{promise:o,resolve:c}=Ue(),l=!1,u=!1,d=null,f=!1;const m=[],p=()=>Math.max(2,m.length);(async()=>{let b=e??await this.getFirstPacket(i);for(;b&&!u&&!this._track.input._disposed&&!(t&&b.sequenceNumber>=(t==null?void 0:t.sequenceNumber));){if(n.length>p()){({promise:o,resolve:c}=Ue()),await o;continue}n.push(b),a(),{promise:s,resolve:a}=Ue(),b=await this.getNextPacket(b,i)}l=!0,a()})().catch(b=>{f||(d=b,f=!0,a())});const h=this._track;return{async next(){for(;;){if(h.input._disposed)throw new tt;if(u)return{value:void 0,done:!0};if(f)throw d;if(n.length>0){const b=n.shift(),y=performance.now();for(m.push(y);m.length>0&&y-m[0]>=1e3;)m.shift();return c(),{value:b,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}}
397,async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}}class Js{constructor(e,t){this.onSample=e,this.onError=t}}class Mc{mediaSamplesInRange(e=-1/0,t=1/0,i){Yt(e),Yt(t);const n=[];let s=!1,a=null,{promise:o,resolve:c}=Ue(),{promise:l,resolve:u}=Ue(),d=!1,f=!1,m=!1,p=null,h=!1;const b={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const T=await this._createDecoder(v=>{if(u(),v.timestamp>=t&&(f=!0),f){v.close();return}a&&(v.timestamp>e?(n.push(a),s=!0):a.close()),v.timestamp>=e&&(n.push(v),s=!0),a=s?null:v,n.length>0&&(c(),{promise:o,resolve:c}=Ue())},v=>{h||(p=v,h=!0,c())}),P=this._createPacketSink(),_=await P.getKeyPacket(e,b)??await P.getFirstKeyPacket(b);let S=_;const C=P.packets(_??void 0,void 0,b);for(await C.next();S&&!f&&!this._track.input._disposed;){const v=Za(n.length);if(n.length+T.getDecodeQueueSize()>v){({promise:l,resolve:u}=Ue()),await l;continue}T.decode(S);const A=await C.next();if(A.done)break;S=A.value}await C.return(),!m&&!this._track.input._disposed&&await T.flush(),T.close(),!s&&a&&n.push(a),d=!0,c()})().catch(T=>{h||(p=T,h=!0,c())});const y=this._track,x=()=>{a==null||a.close();for(const T of n)T.close()};return{async next(){for(;;){if(y.input._disposed)throw x(),new tt;if(m)return{value:void 0,done:!0};if(h)throw x(),p;if(n.length>0){const T=n.shift();return u(),{value:T,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return m=!0,f=!0,u(),c(),x(),{value:void 0,done:!0}},async throw(T){throw T},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){Du(e);const i=Ou(e),n=[],s=[];let{promise:a,resolve:o}=Ue(),{promise:c,resolve:l}=Ue(),u=!1,d=!1,f=null,m=!1;const p=x=>{s.push(x),o(),{promise:a,resolve:o}=Ue()},h={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const x=await this._createDecoder(v=>{if(l(),d){v.close();return}let A=0;for(;n.length>0&&v.timestamp-n[0]>-1e-10;)A++,n.shift();if(A>0)for(let H=0;H<A;H++)p(H<A-1?v.clone():v);else v.close()},v=>{m||(f=v,m=!0,o())}),T=this._createPacketSink();let P=null,_=null,S=-1;const I=async()=>{g(_);let v=_;for(x.decode(v);v.sequenceNumber<S;){const A=Za(s.length);for(;s.length+x.getDecodeQueueSize()>A&&!d;)({promise:c,resolve:l}=Ue()),await c;if(d)break;const H=await T.getNextPacket(v,h);g(H),x.decode(H),v=H}S=-1},C=async()=>{await x.flush();for(let v=0;v<n.length;v++)p(null);n.length=0};for await(const v of i){if(Yt(v),d||this._track.input._disposed)break;const A=await T.getPacket(v,h),H=A&&await T.getKeyPacket(v,h);if(!H){S!==-1&&(await I(),await C()),p(null),P=null;continue}P&&(H.sequenceNumber!==_.sequenceNumber||A.timestamp<P.timestamp)&&(await I(),await C()),n.push(A.timestamp),S=Math.max(A.sequenceNumber,S),P=A,_=H}!d&&!this._track.input._disposed&&(S!==-1&&await I(),await C()),x.close(),u=!0,o()})().catch(x=>{m||(f=x,m=!0,o())});const b=this._track,y=()=>{for(const x of s)x==null||x.close()};return{async next(){for(;;){if(b.input._disposed)throw y(),new tt;if(d)return{value:void 0,done:!0};if(m)throw y(),f;if(s.length>0){const x=s.shift();return g(x!==void 0),l(),{value:x,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),y(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}}const Za=r=>r===0?40:8;class Th extends Js{constructor(e,t,i,n,s,a){super(e,t),this.codec=i,this.decoderConfig=n,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new pn,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const o=zc.find(c=>c.supports(i,n));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=c=>{if(!(c instanceof je))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoder.onError=c=>{t(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>t(c));else{const c=u=>{if(this.alphaQueue.length>0){const d=this.alphaQueue.shift();g(d!==void 0),this.mergeAlpha(u,d)}else this.colorQueue.push(u)};if(i==="avc"&&this.decoderConfig.description&&ms()){const u=bd(Ge(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){const d=$s(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){var e;return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),Math.max(this.decoder.decodeQueueSize,((e=this.alphaDecoder)==null?void 0:e.decodeQueueSize)??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>
3970&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>this.customDecoderQueueSize--);else{if(g(this.decoder),bi()||ca(this.inputTimestamps,e.timestamp,t=>t),ms()&&this.currentPacketIndex===0){if(this.codec==="avc"){const t=[];let i=!1;for(const s of Ro(e.data,this.decoderConfig)){const a=wn(e.data[s.offset]);if(i||(i=a>=1&&a<=5),a===Le.AUD){if(i)break;t.length=0}a>=20&&a<=31||t.push(e.data.subarray(s.offset,s.offset+s.length))}const n=pd(t,this.decoderConfig);e=new Ae(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const t=Pd(e.data,this.decoderConfig);t&&(e=new Ae(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new _h),!this.alphaDecoder){const i=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();g(a!==void 0),this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();g(a!==void 0),this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},n=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{i(s)}catch(a){this.onError(a)}},error:s=>{s.stack=n,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=Tn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>
3970&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of nn(e,this.decoderConfig)){const i=Jr(e[t.offset]);if(i===Ne.RASL_N||i===Ne.RASL_R)return!0}return!1}sampleHandler(e){if(bi()){if(this.sampleQueue.length>0&&e.timestamp>=Be(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}ca(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();g(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){const i=Ue();this.mergeAlphaPromises.push(i.promise);const n={sample:null};this.finalSamples.push(n);try{if(!t)n.sample=new je(e);else{g(this.merger);const s=await this.merger.merge(e,t);n.sample=new je(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){ds(this.finalSamples,n),this.onError(s)}finally{ds(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){var e;if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),await Promise.all([this.decoder.flush(),(e=this.alphaDecoder)==null?void 0:e.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t==null?void 0:t.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),bi()){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){var e,t;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.close(),(e=this.alphaDecoder)==null||e.close(),this.colorQueue.forEach(i=>i.close()),this.colorQueue.length=0,this.alphaQueue.forEach(i=>i==null?void 0:i.close()),this.alphaQueue.length=0,(t=this.merger)==null||t.close());for(const i of this.sampleQueue)i.close();this.sampleQueue.length=0}}let Kn=null;class _h{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!Kn){const o=new Blob([`(${Sh.toString()})()`],{type:"application/javascript"});Kn=URL.createObjectURL(o)}const a=De(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(Kn);c.addEventListener("message",l=>{const u=l.data,d=this.pendingRequests.get(u.id);d&&(this.pendingRequests.delete(u.id),"error"in u?d.reject(new Error(u.error)):d.resolve(u.frame))}),c.addEventListener("error",l=>{const u=new Error(l.message||"Color/alpha merge worker error.");for(const d of this.pendingRequests.values())d.reject(u);this.pendingRequests.clear()}),this.workers.push(c)}}const i=this.nextRequestId++,n=Ue();this.pendingRequests.set(i,n);const s=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,s.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),n.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Sh=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{const{id:l,color:u,alpha:d}=c.data;t=t.then(async()=>{try{const f=await i(u,d);self.postMessage({id:l,frame:f},{transfer:[f]})}catch(f){self.postMessage({id:l,error:f.message})}finally{u.close(),d.close()}})});const i=async(c,l)=>{const u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const f=u.includes("P10"),m=u.includes("P12"),p=d.includes("P10"),h=d.includes("P12");
397if(p!==f||h!==m)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await n(c,l,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await s(c,l,u);if(u==="NV12")return await a(c,l);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},n=async(c,l,u)=>{var x,T;const d=((x=c.visibleRect)==null?void 0:x.width)??c.codedWidth,f=((T=c.visibleRect)==null?void 0:T.height)??c.codedHeight,m=d*f,p=new Uint8Array(m*4);await c.copyTo(p);const h=await o(l,d,f,1);for(let P=0,_=3;P<m;P++,_+=4)p[_]=h[P];const y={format:u==="RGBX"||u==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},s=async(c,l,u)=>{var D,$;const d=((D=c.visibleRect)==null?void 0:D.width)??c.codedWidth,f=(($=c.visibleRect)==null?void 0:$.height)??c.codedHeight,m=u.includes("P10"),p=u.includes("P12"),h=m||p?2:1;let b,y;u.startsWith("I420")?(b=Math.ceil(d/2),y=Math.ceil(f/2)):u.startsWith("I422")?(b=Math.ceil(d/2),y=f):(b=d,y=f);const x=d*f,T=b*y,P=x*h,_=T*h,S=x*h,I=P+2*_+S,C=new Uint8Array(I);await c.copyTo(C);const v=await o(l,d,f,h),A=P+2*_;C.set(v,A);const M={format:u.slice(0,4)+"A"+u.slice(4),codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,M)},a=async(c,l)=>{var I,C;const u=((I=c.visibleRect)==null?void 0:I.width)??c.codedWidth,d=((C=c.visibleRect)==null?void 0:C.height)??c.codedHeight,f=u*d,m=Math.ceil(u/2),p=Math.ceil(d/2),h=m*p,b=c.allocationSize();(!e||e.byteLength!==b)&&(e=new Uint8Array(b)),await c.copyTo(e);const y=new Uint8Array(f+2*h+f);y.set(e.subarray(0,f),0);const x=f,T=f+h,P=f;for(let v=0;v<h;v++)y[x+v]=e[P+v*2],y[T+v]=e[P+v*2+1];const _=await o(l,u,d,1);y.set(_,f+2*h);const S={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,S)},o=async(c,l,u,d)=>{const f=c.allocationSize();(!r||r.byteLength!==f)&&(r=new Uint8Array(f)),await c.copyTo(r);const m=c.format;if(m==="RGBA"||m==="BGRA"||m==="RGBX"||m==="BGRX"){const p=m==="RGBA"||m==="RGBX"?0:2,h=l*u;for(let b=0;b<h;b++)r[b]=r[b*4+p];return r.subarray(0,h)}else return r.subarray(0,l*u*d)}},Oc=r=>{if(!r||typeof r!="object")throw new TypeError("decoderOptions must be an object.");if(r.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r.optimizeForLatency!==void 0&&typeof r.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class Dc extends Mc{constructor(e,t={}){if(!(e instanceof Pn))throw new TypeError("videoTrack must be an InputVideoTrack.");Oc(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=await this._track.getCodec(),n=await this._track.getRotation();let s=await this._track.getDecoderConfig();const a=await this._track.getTimeResolution();return g(i&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Th(e,t,i,s,n,a)}_createPacketSink(){return new Zs(this._track)}async getSample(e,t={}){Yt(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Nc{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Pn
vendor: 6,548 bytes, line 397
397))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.alpha!==void 0&&typeof t.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.crop!==void 0&&ln(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");t.decoderOptions!==void 0&&Oc(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Dc(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),n=await t.getSquarePixelWidth(),s=await t.getSquarePixelHeight(),[a,o]=i%180===0?[n,s]:[s,n];let c=e.crop;c&&(c=vs(c,a,o));let[l,u]=c?[c.width,c.height]:[a,o];const d=l/u;e.width!==void 0&&e.height===void 0?(l=e.width,u=Math.round(l/d)):e.width===void 0&&e.height!==void 0?(u=e.height,l=Math.round(u*d)):e.width!==void 0&&e.height!==void 0&&(l=e.width,u=e.height),this._width=l,this._height=u,this._rotation=i,this._crop=c})())}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let n=this._canvasPool[this._nextCanvasIndex],s=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=t,n.height=i):n=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=n.getContext("2d",{alpha:this._alpha||Ji()});g(a),a.resetTransform(),s||(!this._alpha&&Ji()?(a.fillStyle="black",a.fillRect(0,0,t,i)):a.clearRect(0,0,t,i)),e.drawWithFit(a,{fit:this._fit,rotation:this._rotation,crop:this._crop});const o={canvas:n,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){Yt(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*Yi(this._videoSampleSink.samples(e,t,i),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Yi(this._videoSampleSink.samplesAtTimestamps(e,t),i=>i&&this._videoSampleToWrappedCanvas(i))}}class vh extends Js{constructor(e,t,i,n){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new pn,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const s=o=>{let c=o.timestamp;this.expectedFirstTimestamp&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-c),c+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(c-this.currentTimestamp)>=o.duration)&&(this.currentTimestamp=c);const l=this.currentTimestamp;if(this.currentTimestamp+=o.duration,o.numberOfFrames===0){o.close();return}const u=n.sampleRate;o.setTimestamp(Math.round(l*u)/u),e(o)},a=Fc.find(o=>o.supports(i,n));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=o=>{if(!(o instanceof Ke))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(o)},this.customDecoder.onError=o=>{t(o)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(o=>t(o));else{const o=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{s(new Ke(c))}catch(l){this.onError(l)}},error:c=>{c.stack=o,this.onError(c)}}),this.decoder.configure(n)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>this.customDecoderQueueSize--)):(g(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.close())}}class Ph extends Js{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,g(Xe.includes(i.codec)),this.codec=i.codec;const{dataType:n,sampleSize:s,littleEndian:a}=er(this.codec);switch(this.inputSampleSize=s,s){case 1:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:n==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):n==="ulaw"?this.readInputValue=(o,c)=>yh(o.getUint8(c)):n==="alaw"?this.readInputValue=(o,c)=>xh(o.getUint8(c)):g(!1);break;case 2:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:n==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):g(!1);break;case 3:n==="unsigned"?this.readInputValue=(o,c)=>mn(o,c,a)-2**23:n==="signed"?this.readInputValue=(o,c)=>Nu(o,c,a):g(!1);break;case 4:n==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:n==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):n==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):g(!1);break;case 8:n==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):g(!1);break;default:Et(s),g(!1)}switch(s){case 1:n==="ulaw"||n==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(o,c,l)=>
397o.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,n==="float"?(this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0);break;default:Et(s),g(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=_e(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,n=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(n),a=new DataView(s);for(let u=0;u<i*this.decoderConfig.numberOfChannels;u++){const d=u*this.inputSampleSize,f=u*this.outputSampleSize,m=this.readInputValue(t,d);this.writeOutputValue(a,f,m)}const o=i/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);const c=this.currentTimestamp;this.currentTimestamp+=o;const l=new Ke({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}}class Ch extends Mc{constructor(e){if(!(e instanceof Cn))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=await this._track.getCodec(),n=await this._track.getDecoderConfig();return g(i&&n),Xe.includes(n.codec)?new Ph(e,t,n):new vh(e,t,i,n)}_createPacketSink(){return new Zs(this._track)}async getSample(e,t={}){Yt(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Ih{constructor(e){if(!(e instanceof Cn))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Ch(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){Yt(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return Yi(this._audioSampleSink.samples(e,t,i),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(e,t){return Yi(this._audioSampleSink.samplesAtTimestamps(e,t),i=>i&&this._audioSampleToWrappedArrayBuffer(i))}}/*! 398 * Copyright (c) 2026-present, Vanilagy and contributors 399 * 400 * This Source Code Form is subject to the terms of the Mozilla Public 401 * License, v. 2.0. If a copy of the MPL was not distributed with this 402 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 403 */class Bi{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Pn}isAudioTrack(){return this instanceof Cn}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return ze(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return ze(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return ze(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return ze(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return ze(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return(e==null?void 0:e.timestamp)??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}
403),i=((t==null?void 0:t.timestamp)??0)+((t==null?void 0:t.duration)??0);return Zi(i,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new Zs(this);let n=1/0,s=-1/0,a=0,o=0;for await(const c of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=s)break;n=Math.min(n,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-n)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(s-n)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Bi))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(yr({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(yr({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(yr({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(yr({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(yr({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=Gn(e));const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=Gn(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=Gn(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const ze=(r,e,t)=>{if(r instanceof Promise)throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},Gn=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{const t=n=>{if(typeof n!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return n},i=r(e);return i instanceof Promise?i.then(t):t(i)}:void 0};class Pn extends Bi{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return ze(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var e,t;return await((t=(e=this._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return ze(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return ze(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return ze(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return ze(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return ze(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=en({num:await this.get
403SquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=en({num:ze(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ze(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ze(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ze(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")}))}async getDisplayWidth(){var i,n;const e=await((n=(i=this._backing).getMetadataDisplayWidth)==null?void 0:n.call(i));return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){var n,s;const e=(s=(n=this._backing).getMetadataDisplayWidth)==null?void 0:s.call(n);if(e!==void 0){const a=ze(e,"displayWidth","getDisplayWidth");if(a!==null)return a}const i=ze(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ze(i,"displayWidth","getDisplayWidth")}async getDisplayHeight(){var i,n;const e=await((n=(i=this._backing).getMetadataDisplayHeight)==null?void 0:n.call(i));return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){var n,s;const e=(s=(n=this._backing).getMetadataDisplayHeight)==null?void 0:s.call(n);if(e!==void 0){const a=ze(e,"displayHeight","getDisplayHeight");if(a!==null)return a}const i=ze(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ze(i,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}
403async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var i,n;const e=await((n=(i=this._backing).getMetadataCodecParameterString)==null?void 0:n.call(i));if(e!=null)return e;const t=await this._backing.getDecoderConfig();return(t==null?void 0:t.codec)??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return g(t!==null),zc.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return ue._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Ae))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(t===null)return null;const i=await this.getDecoderConfig();return g(i),Tn(t,i,e.data)}}class Cn extends Bi{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return ze(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var e,t;return await((t=(e=this._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return ze(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return ze(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var i,n;const e=await((n=(i=this._backing).getMetadataCodecParameterString)==null?void 0:n.call(i));if(e!=null)return e;const t=await this._backing.getDecoderConfig();return(t==null?void 0:t.codec)??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return g(t!==null),Fc.some(i=>i.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return ue._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Ae))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const Ja=r=>-(r??-1/0),ui=r=>-r,di=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{const t=n=>{if(typeof n!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return n},i=r.filter(e);return i instanceof Promise?i.then(t):t(i)}:void 0,sortBy:r.sortBy?e=>{const t=n=>{if(typeof n!="number"&&(!Array.isArray(n)||!n.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return n},i=r.sortBy(e);return i instanceof Promise?i.then(t):t(i)}:void 0}},yr=(r,e)=>({filter:r!=null&&r.filter||e!=null&&e.filter?t=>{var s;const i=((s=r==null?void 0:r.filter)==null?void 0:s.call(r,t))??!0,n=a=>{var o;return a===!1?!1:((o=e==null?void 0:e.filter)==null?void 0:o.call(e,t))??!0};return i instanceof Promise?i.then(n):n(i)}:void 0,sortBy:r!=null&&r.sortBy||e!=null&&e.sortBy?t=>{var a,o;const i=((a=r==null?void 0:r.sortBy)==null?void 0:a.call(r,t))??[],n=((o=e==null?void 0:e.sortBy)==null?void 0:o.call(e,t))??[],s=(c,l)=>[...Array.isArray(c)?c:[c],...Array.isArray(l)?l:[l]];return i instanceof Promise||n instanceof Promise?Promise.all([i,n]).then(([c,l])=>s(c,l)):s(i,n)}:void 0}),Xn=async(r,e)=>{let t=r;if(e!=null&&e.filter){const a=r.map(c=>e.filter(c));if(a.some(c=>c instanceof Promise)){const c=await Promise.all(a);t=r.filter((l,u)=>c[u])}else t=r.filter((c,l)=>a[l])}if(!(e!=null&&e.sortBy))return t;const i=t.map(a=>e.sortBy(a)),s=i.some(a=>a instanceof Promise)?await Promise.all(i):i;return t.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){const f=c[d]??0,m=l[d]??0;if(f!==m)return f-m}return 0}).map(a=>a.track)};/*! 404 * Copyright (c) 2026-present, Vanilagy and contributors 405 * 406 * This Source Code Form is subject to the terms of the Mozilla Public 407 * License, v. 2.0. If a copy of the MPL was not distributed with this 408 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 409 */Os();const Eh=1,Ah=2;class zr extends Ai{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof zt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof It||e.source instanceof Qs))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof It&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof zr))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&th(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof It?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){g(this._rootSource instanceof ni);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=Eh){const i=this._sourceCache.find(a=>a.cacheGroup===t&&Na(a.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const n=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Na(a.request,e));if(n)return n.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(mi(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){const d=Ds(this._sourceCache,m=>m.cacheGroup===t&&m.sourceRef.source._refCount===1?m.age:1/0);g(d!==-1);const f=this._sourceCache[d];this._sourceCache.splice(d,1),f.sourceRef.free(),ds(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(a);const l=this._sourceCachePromises.findIndex(d=>d.request===e);return g(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{var e;this._reader=new $i(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});
409for(const t of this._formats)if(await t._canReadInput(this))return this._format=t,(e=this._onFormatDetermined)==null||e.call(this,t),t._createDemuxer(this);throw new eo})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),g(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof eo)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(n=>n!==null);if(t.length===0)return 0;const i=await Promise.all(t.map(n=>n.getFirstTimestamp()));return Math.min(...i)}async computeDuration(e,t){e??(e=await this.getTracks());const i=e.filter(s=>s!==null);if(i.length===0)return 0;const n=await Promise.all(i.map(s=>s.computeDuration(t)));return Math.max(...n)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const i=e.filter(a=>a!==null),s=(await Promise.all(i.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&(e=di(e));const i=(await this._getTrackBackings()).map(n=>this._wrapBackingAsTrack(n));return Xn(i,e)}async getVideoTracks(e){e&&(e=di(e));const i=(await this.getTracks()).filter(n=>n.isVideoTrack());return Xn(i,e)}async getAudioTracks(e){e&&(e=di(e));const i=(await this.getTracks()).filter(n=>n.isAudioTrack());return Xn(i,e)}async getPrimaryVideoTrack(e){e&&(e=di(e));const t=yr(e,{sortBy:async n=>[ui((await n.getDisposition()).default),ui(await n.hasPairableAudioTrack()),ui(!await n.hasOnlyKeyPackets()),Ja(await n.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=di(e));const t=await this.getPrimaryVideoTrack(),i=yr(e,{sortBy:async s=>[ui(!t||s.canBePairedWith(t)),ui((await s.getDisposition()).default),Ja(await s.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const n=e.getType()==="video"?new Pn(this,e):new Cn(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}
409class eo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class tt extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}/*! 410 * Copyright (c) 2026-present, Vanilagy and contributors 411 * 412 * This Source Code Form is subject to the terms of the Mozilla Public 413 * License, v. 2.0. If a copy of the MPL was not distributed with this 414 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 415 */class $i{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new tt;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const s=new Uint8Array(0);return new at(s,_e(s),0,e,e)}const i=e+t,n=this.source._read(e,i,hc,mc);return n instanceof Promise?n.then(s=>s?new at(s.bytes,s.view,s.offset,e,i):null):n?new at(n.bytes,n.view,n.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new tt;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,De(this.fileSizeNonStrict-e,t,i));{const n=this.requestSlice(e,i),s=a=>a||(g(this.fileSizeNonStrict!==null),this.requestSlice(e,De(this.fileSizeNonStrict-e,t,i)));return n instanceof Promise?n.then(s):s(n)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const t=[];let i=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(i,0,e);if(a instanceof Promise&&(a=await a),!a||a.length===0)break;const o=se(a,a.length);t.push(o),i+=a.length}const n=new Uint8Array(i);let s=0;for(const a of t)n.set(a,s),s+=a.length;return new at(n,_e(n),0,0,i)})()}}class at{constructor(e,t,i,n,s){this.bytes=e,this.view=t,this.offset=i,this.start=n,this.end=s,this.bufferPos=n-i}static tempFromBytes(e){return new at(e,_e(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new at(this.bytes,this.view,this.offset,e,e+t)}}const Ze=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},se=(r,e)=>{Ze(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},ie=r=>(Ze(r,1),r.view.getUint8(r.bufferPos++)),fi=(r,e)=>{Ze(r,2);const t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},Oe=r=>{Ze(r,2);const e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},Ut=r=>{Ze(r,3);const e=mn(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},Ps=r=>{Ze(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},dr=(r,e)=>{Ze(r,4);const t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},K=r=>{Ze(r,4);const e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},$r=r=>{Ze(r,4);const e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Tr=r=>{Ze(r,4);const e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},zh=r=>{Ze(r,4);const e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},to=(r,e)=>{let t,i;return e?(t=dr(r,!0),i=dr(r,!0)):(i=dr(r,!1),t=dr(r,!1)),i*4294967296+t},ut=r=>{const e=K(r),t=K(r);return e*4294967296+t},Fh=r=>{const e=Tr(r),t=K(r);return e*4294967296+t},Bh=r=>{const e=$r(r);return zh(r)*4294967296+e},Rh=r=>{Ze(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},Uc=r=>{Ze(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},Re=(r,e)=>{Ze(r,e);let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},Vc=(r,e,t)=>Ye.decode(se(r,e)).split(` 416`).map(s=>s.trim()).filter(s=>{var a;return s.length>0&&!((a=t==null?void 0:t.ignore)!=null&&a.call(t,s))});/*! 417 * Copyright (c) 2026-present, Vanilagy and contributors 418 * 419 * This Source Code Form is subject to the terms of the Mozilla Public 420 * License, v. 2.0. If a copy of the MPL was not distributed with this 421 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 422 */var _r;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(_r||(_r={}));var jr;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(jr||(jr={}));const ji=128,ht=10,Kr=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","S
422ound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Mh=(r,e)=>{var d;const t=r.filePos;e.raw??(e.raw={}),(d=e.raw).TAG??(d.TAG=se(r,ji-3)),r.filePos=t;const i=Dr(r,30);i&&(e.title??(e.title=i));const n=Dr(r,30);n&&(e.artist??(e.artist=n));const s=Dr(r,30);s&&(e.album??(e.album=s));const a=Dr(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??(e.date=new Date(String(o))));const c=se(r,30);let l;if(c[28]===0&&c[29]!==0){const f=c[29];f>0&&(e.trackNumber??(e.trackNumber=f)),r.skip(-30),l=Dr(r,28),r.skip(2)}else r.skip(-30),l=Dr(r,30);l&&(e.comment??(e.comment=l));const u=ie(r);u<Kr.length&&(e.genre??(e.genre=Kr[u]))},Dr=(r,e)=>{const t=se(r,e),i=Nr(t.indexOf(0),t.length),n=t.subarray(0,i);let s="";for(let a=0;a<n.length;a++)s+=String.fromCharCode(n[a]);return s.trimEnd()},tr=r=>{const e=r.filePos,t=Re(r,3),i=ie(r),n=ie(r),s=ie(r),a=K(r);if(t!=="ID3"||i===255||n===255||(a&2155905152)!==0)return r.filePos=e,null;let o=gs(a);return s&_r.Footer&&(o+=ht),{majorVersion:i,revision:n,flags:s,size:o}},In=(r,e,t)=>{var a,o,c,l,u;if(![2,3,4].includes(e.majorVersion)){ue._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const i=e.flags&_r.Footer?e.size-ht:e.size,n=se(r,i),s=new Oh(e,n);if(e.flags&_r.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&_r.ExtendedHeader){const d=s.readU32();e.majorVersion===3?s.pos+=d:s.pos+=d-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){const d=s.readId3V2Frame();if(!d)break;const f=s.pos,m=s.pos+d.size;let p=!1,h=!1,b=!1;if(e.majorVersion===3?(p=!!(d.flags&64),h=!!(d.flags&128)):e.majorVersion===4&&(p=!!(d.flags&4),h=!!(d.flags&8),b=!!(d.flags&2)||!!(e.flags&_r.Unsynchronisation)),p){ue._warn(`Skipping encrypted ID3v2 frame ${d.id}`),s.pos=m;continue}if(h){ue._warn(`Skipping compressed ID3v2 frame ${d.id}`),s.pos=m;continue}if(b&&s.ununsynchronizeRegion(s.pos,m),t.raw??(t.raw={}),d.id==="TXXX"){const y=(a=t.raw).TXXX??(a.TXXX={}),x=s.readId3V2TextEncoding(),T=s.readId3V2Text(x,m),P=s.readId3V2Text(x,m);y[T]??(y[T]=P)}else d.id[0]==="T"?(o=t.raw)[c=d.id]??(o[c]=s.readId3V2EncodingAndText(m)):(l=t.raw)[u=d.id]??(l[u]=s.readBytes(d.size));switch(s.pos=f,d.id){case"TIT2":case"TT2":t.title??(t.title=s.readId3V2EncodingAndText(m));break;case"TIT3":case"TT3":t.description??(t.description=s.readId3V2EncodingAndText(m));break;case"TPE1":case"TP1":t.artist??(t.artist=s.readId3V2EncodingAndText(m));break;case"TALB":case"TAL":t.album??(t.album=s.readId3V2EncodingAndText(m));break;case"TPE2":case"TP2":t.albumArtist??(t.albumArtist=s.readId3V2EncodingAndText(m));break;case"TRCK":case"TRK":{const x=s.readId3V2EncodingAndText(m).split("/"),T=Number.parseInt(x[0],10),P=x[1]&&Number.parseInt(x[1],10);Number.isInteger(T)&&T>0&&(t.trackNumber??(t.trackNumber=T)),P&&Number.isInteger(P)&&P>0&&(t.tracksTotal??(t.tracksTotal=P))}break;case"TPOS":case"TPA":{const x=s.readId3V2EncodingAndText(m).split("/"),T=Number.parseInt(x[0],10),P=x[1]&&Number.parseInt(x[1],10);Number.isInteger(T)&&T>0&&(t.discNumber??(t.discNumber=T)),P&&Number.isInteger(P)&&P>0&&(t.discsTotal??(t.discsTotal=P))}break;case"TCON":case"TCO":{const y=s.readId3V2EncodingAndText(m);let x=/^\((\d+)\)/.exec(y);if(x){const T=Number.parseInt(x[1]);if(Kr[T]!==void 0){t.genre??(t.genre=Kr[T]);break}}if(x=/^\d+$/.exec(y),x){const T=Number.parseInt(x[0]);if(Kr[T]!==void 0){t.genre??(t.genre=Kr[T]);break}}t.genre??(t.genre=y)}break;case"TDRC":case"TDAT":{const y=s.readId3V2EncodingAndText(m),x=new Date(y);Number.isNaN(x.getTime())||(t.date??(t.date=x))}break;case"TYER":case"TYE":{const y=s.readId3V2EncodingAndText(m),x=Number.parseInt(y,10);Number.isInteger(x)&&(t.date??(t.date=new Date(String(x))))}break;case"USLT":case"ULT":{const y=s.readU8();s.pos+=3,s.readId3V2Text(y,m),t.lyrics??(t.lyrics=s.readId3V2Text(y,m))}break;case"COMM":case"COM":{const y=s.readU8();s.pos+=3,s.readId3V2Text(y,m),t.comment??(t.comment=s.readId3V2Text(y,m))}break;case"APIC":case"PIC":{const y=s.readId3V2TextEncoding();let x;if(e.majorVersion===2){const S=s.readAscii(3);x=S==="PNG"?"image/png":S==="JPG"?"image/jpeg":"image/*"}else x=s.readId3V2Text(y,m);const T=s.readU8(),P=s.readId3V2Text(y,m).trimEnd(),_=m-s.pos;if(_>=0){const S=s.readBytes(_);t.images||(t.images=[]),t.images.push({data:S,mimeType:x,kind:T===3?"coverFront":T===4?"coverBack":"unknown",de
422scription:P})}}break;default:s.pos+=d.size;break}s.pos=m}};class Oh{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const i=this.bytes[t];e.push(i),i===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const i=[];for(let a=e;a<t;a++){const o=this.bytes[a];i.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}const n=this.bytes.subarray(0,e),s=this.bytes.subarray(t);this.bytes=new Uint8Array(n.length+i.length+s.length),this.bytes.set(n,0),this.bytes.set(i,n.length),this.bytes.set(s,n.length+i.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(this.view.getUint8(this.pos+i));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){const e=this.readAscii(3);if(e==="\0\0\0")return null;const t=this.readU24();return{id:e,size:t,flags:0}}else{const e=this.readAscii(4);if(e==="\0\0\0\0")return null;const t=this.readU32();let i=this.header.majorVersion===4?gs(t):t;const n=this.readU16(),s=this.pos,a=o=>{const c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;const l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!a(i)){const o=this.header.majorVersion===4?t:gs(t);a(o)&&(i=o)}return this.pos=s,{id:e,size:i,flags:n}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,n=this.readBytes(t-this.pos);switch(e){case jr.ISO_8859_1:{let s="";for(let a=0;a<n.length;a++){const o=n[a];if(o===0){this.pos=i+a+1;break}s+=String.fromCharCode(o)}return s}case jr.UTF_16_WITH_BOM:if(n[0]===255&&n[1]===254){const s=new TextDecoder("utf-16le"),a=Nr(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(2,a))}else if(n[0]===254&&n[1]===255){const s=new TextDecoder("utf-16be"),a=Nr(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(2,a))}else{const s=Nr(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),Ye.decode(n.subarray(0,s))}case jr.UTF_16_BE_NO_BOM:{const s=new TextDecoder("utf-16be"),a=Nr(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(0,a))}case jr.UTF_8:{const s=Nr(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),Ye.decode(n.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}/*! 423 * Copyright (c) 2026-present, Vanilagy and contributors 424 * 425 * This Source Code Form is subject to the terms of the Mozilla Public 426 * License, v. 2.0. If a copy of the MPL was not distributed with this 427 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 428 */class Dh{constructor(e){this.mutex=new ii,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let n=this.trackTimestampInfo.get(e);if(n){if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),n.maxTimestampBeforeLastKeyPacket!==null&&t<n.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);n.maxTimestamp=Math.max(n.maxTimestamp,t)}else{if(!i)throw new Error("First packet must be a key packet.");
428n={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,n)}}}/*! 429 * Copyright (c) 2026-present, Vanilagy and contributors 430 * 431 * This Source Code Form is subject to the terms of the Mozilla Public 432 * License, v. 2.0. If a copy of the MPL was not distributed with this 433 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 434 */const ro=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Nh=r=>{const e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),i=Math.floor(r%(60*1e3)/1e3),n=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};/*! 435 * Copyright (c) 2026-present, Vanilagy and contributors 436 * 437 * This Source Code Form is subject to the terms of the Mozilla Public 438 * License, v. 2.0. If a copy of the MPL was not distributed with this 439 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 440 */class Ni{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const s of e.children)s&&this.writeBox(s);const i=this.writer.getPos(),n=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);g(t!==void 0);const i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const i of e.children)i&&(t+=this.measureBox(i));return t}}}const fe=new Uint8Array(8),mt=new DataView(fe.buffer),Me=r=>[(r%256+256)%256],le=r=>(mt.setUint16(0,r,!1),[fe[0],fe[1]]),ea=r=>(mt.setInt16(0,r,!1),[fe[0],fe[1]]),Lc=r=>(mt.setUint32(0,r,!1),[fe[1],fe[2],fe[3]]),q=r=>(mt.setUint32(0,r,!1),[fe[0],fe[1],fe[2],fe[3]]),Gt=r=>(mt.setInt32(0,r,!1),[fe[0],fe[1],fe[2],fe[3]]),At=r=>(mt.setUint32(0,Math.floor(r/2**32),!1),mt.setUint32(4,r,!1),[fe[0],fe[1],fe[2],fe[3],fe[4],fe[5],fe[6],fe[7]]),Uh=r=>(mt.setInt32(0,Math.floor(r/2**32),!1),mt.setUint32(4,r,!1),[fe[0],fe[1],fe[2],fe[3],fe[4],fe[5],fe[6],fe[7]]),Wc=r=>(mt.setInt16(0,2**8*r,!1),[fe[0],fe[1]]),kt=r=>(mt.setInt32(0,2**16*r,!1),[fe[0],fe[1],fe[2],fe[3]]),Qn=r=>(mt.setInt32(0,2**30*r,!1),[fe[0],fe[1],fe[2],fe[3]]),Yn=(r,e)=>{const t=[];let i=r;do{let n=i&127;i>>=7,t.length>0&&(n|=128),t.push(n)}while(i>0||e);return t.reverse()},Pe=(r,e=!1)=>{const t=Array(r.length).fill(null).map((i,n)=>r.charCodeAt(n));return e&&t.push(0),t},Hc=r=>{const e=r*(Math.PI/180),t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},qc=Hc(0),$c=r=>[kt(r[0]),kt(r[1]),Qn(r[2]),kt(r[3]),kt(r[4]),Qn(r[5]),kt(r[6]),kt(r[7]),Qn(r[8])],oe=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),xe=(r,e,t,i,n)=>oe(r,[Me(e),Lc(t),i??[]],n),Vh=r=>r.isQuickTime?oe("ftyp",[Pe("qt "),q(512),Pe("qt ")]):r.fragmented?r.cmaf?oe("ftyp",[Pe("iso5"),q(512),Pe("iso5"),Pe("iso6"),Pe("mp41"),Pe("cmfc"),Pe("dash")]):oe("ftyp",[Pe("iso5"),q(512),Pe("iso5"),Pe("iso6"),Pe("mp41")]):oe("ftyp",[Pe("isom"),q(512),Pe("isom"),r.holdsAvc?Pe("avc1"):[],Pe("mp41")]),io=()=>oe("styp",[Pe("iso5"),q(0),Pe("iso5"),Pe("iso6"),Pe("mp41"),Pe("cmfc"),Pe("dash")]),no=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),xe("sidx",1,0,[q(1),q(yt),At(Fe(r.minWrittenTimestamp,yt)),At(0),le(0),le(1),q(e&2147483647),q(Fe(t,yt)),q(0)])},Ui=r=>({type:"mdat",largeSize:r}),Lh=r=>({type:"free",size:r}),hi=r=>oe("moov",void 0,[Wh(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>Hh(e,r.creationTime)),r.isFragmented?Im(r.trackDatas):null,Lm(r)]),Wh=(r,e)=>{const t=Math.max(0,...e.map(a=>Fe(En(a),yt)+Fe(a.startTimestampOffset??0,yt))),i=Math.max(0,...e.map(a=>a.track.id))+1,n=!fr(r)||!fr(t),s=n?At:q;return xe("mvhd",+n,0,[s(r),s(r),q(yt),s(t),kt(1),Wc(1),Array(10).fill(0),$c(qc),Array(24).fill(0),q(i)])},En=r=>{if(r.samples.length===0)return 0;let e=1/0,t=-1/0;for(let i=0;i<r.samples.length;i++){const n=r.samples[i];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>t&&(t=n.timestamp+n.duration)}return e===1/0?0:t-e},Hh=(r,e)=>{const t=Ym(r),i=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return oe("trak",void 0,[qh(r,e),i?$h(r,r.startTimestampOffset):null,jh(r,e),t.name!==void 0?oe("udta",void 0,[oe("name",[...Ct.encode(t.name)])]):null])},qh=(r,e)=>{var o;const t=Fe(En(r),yt)+Fe(r.startTimestampOffset??0,yt),i=!fr(e)||!fr(t),n=i?At:q;let s;if(r.type==="video"){const c=r.track.metadata.rotation;s=Hc(c??0)}else s=qc;let a=2;return((o=r.track.metadata.disposition)==null?void 0:o.default)!==!1&&(a|=1),xe("tkhd",+i,a,[n(e),n(e),q(r.track.id),q(0),n(t),Array(8).fill(0),le(0),le(r.track.id),Wc(r.type==="audio"?1:0),le(0),$c(s),kt(r.type==="video"?r.info.width:0),kt(r.type==="video"?r.info.height:0)])},$h=(r,e)=>{const t=Fe(e,yt),i=Fe(En(r),yt),n=!fr(t)||!fr(i),s=n?At:q,a=n?Uh:Gt;return oe("edts",void 0,[xe("elst",n?1:0,0,[q(2),s(t),a(-1),kt(1),s(i),a(0),kt(1)])])},jh=(r,e)=>oe("mdia",void 0,[Kh(r,e),ta(!0,Gh[r.type],Xh[r.type]),Qh(r)]),Kh=(r,e)=>{const t=Fe(En(r),r.timescale),i=!fr(e)||!fr(t),n=i?At:q;return xe("mdhd",+i,0,[n(e),n(e),q(r.timescale),n(t),le(Xc(r.track.metadata.languageCode??He)),le(0)])},Gh={video:"vide",audio:"soun",subtitle:"text"},Xh={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ta=(r,e,t,i="\0\0\0\0")=>xe("hdlr",0,0,[r?Pe("mhlr"):q(0),Pe(e),Pe(i),q(0),q(0),Pe(t,!0)]),Qh=r=>oe("minf",void 0,[em[r.type](),tm(),nm(r)]),Yh=()=>xe("vmhd",0,1,[le(0),le(0),le(0),le(0)]),Zh=()=>xe("smhd",0,0,[le(0),le(0)]),Jh=()=>xe("nmhd",0,0),em={video:Yh,audio:Zh,subtitle:Jh},tm=()=>oe("dinf",void 0,[rm()]),rm=()=>xe("dref",0,0,[q(1)],[im()]),im=()=>xe("url ",0,1),nm=r=>{const e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>
440t.sampleCompositionTimeOffset!==0);return oe("stbl",void 0,[sm(r),xm(r),e?Pm(r):null,e?Cm(r):null,_m(r),Sm(r),vm(r),Tm(r)])},sm=r=>{let e;if(r.type==="video")e=am($m(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){const t=Gc(r.track.source._codec,r.muxer.isQuickTime);g(t),e=fm(t,r)}else r.type==="subtitle"&&(e=ym(Km[r.track.source._codec],r));return g(e),xe("stsd",0,0,[q(1)],[e])},am=(r,e)=>{var t;return oe(r,[Array(6).fill(0),le(1),le(0),le(0),Array(12).fill(0),le(e.info.width),le(e.info.height),q(4718592),q(4718592),q(0),le(1),Array(32).fill(0),le(24),ea(65535)],[((t=Jn[e.track.source._codec])==null?void 0:t.call(Jn,e))??null,om(e),Bu(e.info.decoderConfig.colorSpace)?cm(e):null])},om=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:oe("pasp",[q(r.info.pixelAspectRatio.num),q(r.info.pixelAspectRatio.den)]),cm=r=>oe("colr",[Pe(r.muxer.isQuickTime?"nclc":"nclx"),le(ei[r.info.decoderConfig.colorSpace.primaries]),le(ti[r.info.decoderConfig.colorSpace.transfer]),le(ri[r.info.decoderConfig.colorSpace.matrix]),r.muxer.isQuickTime?[]:Me((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),lm=r=>r.info.decoderConfig&&oe("avcC",[...Ge(r.info.decoderConfig.description)]),um=r=>r.info.decoderConfig&&oe("hvcC",[...Ge(r.info.decoderConfig.description)]),so=r=>{var f,m,p,h;if(!r.info.decoderConfig)return null;const e=r.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),n=Number(t[2]),s=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(((f=e.colorSpace)==null?void 0:f.fullRange)??0),c=(s<<4)+(a<<1)+o,l=t[5]?Number(t[5]):(m=e.colorSpace)!=null&&m.primaries?ei[e.colorSpace.primaries]:2,u=t[6]?Number(t[6]):(p=e.colorSpace)!=null&&p.transfer?ti[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):(h=e.colorSpace)!=null&&h.matrix?ri[e.colorSpace.matrix]:2;return xe("vpcC",1,0,[Me(i),Me(n),Me(c),Me(l),Me(u),Me(d),le(0)])},dm=r=>oe("av1C",Zu(r.info.decoderConfig.codec)),fm=(r,e)=>{var a;let t=0,i,n=16;const s=Xe.includes(e.track.source._codec);if(s){const o=e.track.source._codec,{sampleSize:c}=er(o);n=8*c,n>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)i=[Array(6).fill(0),le(1),le(t),le(0),q(0),le(e.info.numberOfChannels),le(n),le(0),le(0),le(e.info.sampleRate<2**16?e.info.sampleRate:0),le(0)];else{const o=s?0:-2;i=[Array(6).fill(0),le(1),le(t),le(0),q(0),le(e.info.numberOfChannels),le(Math.min(n,16)),ea(o),le(0),le(e.info.sampleRate<2**16?e.info.sampleRate:0),le(0),s?[q(1),q(n/8),q(e.info.numberOfChannels*n/8)]:[q(0),q(0),q(0)],q(2)]}return oe(r,i,[((a=jm(e.track.source._codec,e.muxer.isQuickTime))==null?void 0:a(e))??null])},Zn=r=>{let e;switch(r.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let t=[...Me(e),...Me(21),...Lc(0),...q(0),...q(0)];if(r.info.decoderConfig.description){const i=Ge(r.info.decoderConfig.description);t=[...t,...Me(5),...Yn(i.byteLength),...i]}return t=[...le(1),...Me(0),...Me(4),...Yn(t.length),...t,...Me(6),...Me(1),...Me(2)],t=[...Me(3),...Yn(t.length),...t],xe("esds",0,0,t)},nr=r=>oe("wave",void 0,[hm(r),mm(r),oe("\0\0\0\0")]),hm=r=>oe("frma",[Pe(Gc(r.track.source._codec,r.muxer.isQuickTime))]),mm=r=>{const{littleEndian:e}=er(r.track.source._codec);return oe("enda",[le(+e)])},pm=r=>{var c;let e=r.info.numberOfChannels,t=3840,i=r.info.sampleRate,n=0,s=0,a=new Uint8Array(0);const o=(c=r.info.decoderConfig)==null?void 0:c.description;if(o){g(o.byteLength>=18);const l=Ge(o),u=Lo(l);e=u.outputChannelCount,t=u.preSkip,i=u.inputSampleRate,n=u.outputGain,s=u.channelMappingFamily,u.channelMappingTable&&(a=u.channelMappingTable)}return oe("dOps",[Me(0),Me(e),le(t),q(i),ea(n),Me(s),...a])},gm=r=>{var i;const e=(i=r.info.decoderConfig)==null?void 0:i.description;g(e);const t=Ge(e);return xe("dfLa",0,0,[...t.subarray(4)])},_t=r=>{const{littleEndian:e,sampleSize:t}=er(r.track.source._codec),i=+e;return xe("pcmC",0,0,[Me(i),Me(8*t)])},bm=r=>{const e=Wo(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const t=new Uint8Array(3),i=new Se(t);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.b
vendor: 7,888 bytes, line 440
440smod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),oe("dac3",[...t])},km=r=>{const e=qo(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(const a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;const i=Math.ceil(t/8),n=new Uint8Array(i),s=new Se(n);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(const a of e.substreams)s.writeBits(2,a.fscod),s.writeBits(5,a.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,a.bsmod),s.writeBits(3,a.acmod),s.writeBits(1,a.lfeon),s.writeBits(3,0),s.writeBits(4,a.numDepSub),a.numDepSub>0?s.writeBits(9,a.chanLoc):s.writeBits(1,0);return oe("dec3",[...n])},ym=(r,e)=>oe(r,[Array(6).fill(0),le(1)],[Gm[e.track.source._codec](e)]),wm=r=>oe("vttC",[...Ct.encode(r.info.config.description)]),xm=r=>xe("stts",0,0,[q(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[q(e.sampleCount),q(e.sampleDelta)])]),Tm=r=>{if(r.samples.every(t=>t.type==="key"))return null;const e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return xe("stss",0,0,[q(e.length),e.map(([t])=>q(t+1))])},_m=r=>xe("stsc",0,0,[q(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[q(e.firstChunk),q(e.samplesPerChunk),q(1)])]),Sm=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){const{sampleSize:e}=er(r.track.source._codec);return xe("stsz",0,0,[q(e*r.info.numberOfChannels),q(r.samples.reduce((t,i)=>t+Fe(i.duration,r.timescale),0))])}return xe("stsz",0,0,[q(0),q(r.samples.length),r.samples.map(e=>q(e.size))])},vm=r=>r.finalizedChunks.length>0&&Be(r.finalizedChunks).offset>=2**32?xe("co64",0,0,[q(r.finalizedChunks.length),r.finalizedChunks.map(e=>At(e.offset))]):xe("stco",0,0,[q(r.finalizedChunks.length),r.finalizedChunks.map(e=>q(e.offset))]),Pm=r=>xe("ctts",1,0,[q(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[q(e.sampleCount),Gt(e.sampleCompositionTimeOffset)])]),Cm=r=>{let e=1/0,t=-1/0,i=1/0,n=-1/0;g(r.compositionTimeOffsetTable.length>0),g(r.samples.length>0);for(let a=0;a<r.compositionTimeOffsetTable.length;a++){const o=r.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<r.samples.length;a++){const o=r.samples[a];i=Math.min(i,Fe(o.timestamp,r.timescale)),n=Math.max(n,Fe(o.timestamp+o.duration,r.timescale))}const s=Math.max(-e,0);return n>=2**31?null:xe("cslg",0,0,[Gt(s),Gt(e),Gt(t),Gt(i),Gt(n)])},Im=r=>oe("mvex",void 0,r.map(Em)),Em=r=>xe("trex",0,0,[q(r.track.id),q(1),q(0),q(0),q(0)]),ao=(r,e)=>oe("moof",void 0,[Am(r),...e.map(zm)]),Am=r=>xe("mfhd",0,0,[q(r)]),jc=r=>{let e=0,t=0;const i=0,n=0,s=r.type==="delta";return t|=+s,s?e|=1:e|=2,e<<24|t<<16|i<<8|n},zm=r=>oe("traf",void 0,[Fm(r),Bm(r),Rm(r)]),Fm=r=>{g(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=r.currentChunk.samples[1]??r.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:jc(t)};return xe("tfhd",0,e,[q(r.track.id),q(i.duration),q(i.size),q(i.flags)])},Bm=r=>(g(r.currentChunk),xe("tfdt",1,0,[At(Fe(r.currentChunk.startTimestamp,r.timescale))])),Rm=r=>{g(r.currentChunk);const e=r.currentChunk.samples.map(h=>h.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(h=>h.size),i=r.currentChunk.samples.map(jc),n=r.currentChunk.samples.map(h=>Fe(h.timestamp-h.decodeTimestamp,r.timescale)),s=new Set(e),a=new Set(t),o=new Set(i),c=new Set(n),l=o.size===2&&i[0]!==i[1],u=s.size>1,d=a.size>1,f=!l&&o.size>1,m=c.size>1||[...c].some(h=>h!==0);let p=0;return p|=1,p|=4*+l,p|=256*+u,p|=512*+d,p|=1024*+f,p|=2048*+m,xe("trun",1,p,[q(r.currentChunk.samples.length),q(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?q(i[0]):[],r.currentChunk.samples.map((h,b)=>[u?q(e[b]):[],d?q(t[b]):[],f?q(i[b]):[],m?Gt(n[b]):[]])])},Mm=r=>oe("mfra",void 0,[...r.map(Om),Dm()]),Om=(r,e)=>xe("tfra",1,0,[q(r.track.id),q(63),q(r.finalizedChunks.length),r.finalizedChunks.map(i=>[At(Fe(i.samples[0].timestamp,r.timescale)),At(i.moofOffset),q(e+1),q(1),q(1)])]),Dm=()=>xe("mfro",0,0,[q(0)]),Nm=()=>oe("vtte"),Um=(r,e,t,i,n)=>oe("vttc",void 0,[n!==null?oe("vsid",[Gt(n)]):null,t!==null?oe("iden",[...Ct.encode(t)]):null,e!==null?oe("ctim",[...Ct.encode(Nh(e))]):null,i!==null?oe("sttg",[...Ct.encode(i)]):null,oe("payl",[...Ct.encode(r)])]),Vm=r=>oe("vtta",[...Ct.encode(r)]),Lm=r=>{const e=[],t=r.format._options.metadataFormat??"auto",i=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){const n=Hm(i);n&&e.push(n)}else if(t==="mdta"){const n=qm(i);n&&e.push(n)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&Wm(e,r.output._metadataTags);return e.length===0?null:oe("udta",void 0,e)},Wm=(r,e)=>{for(const{key:t,value:i}of So(e))switch(t){case"title":r.push(St("©nam",i));break;case"description":r.push(St("©des",i));break;case"artist":r.push(St("©ART",i));break;case"album":r.push(St("©alb",i));break;case"albumArtist":r.push(St("albr",i));break;case"genre":r.push(St("©gen",i));break;case"date":r.push(St("©day",i.toISOString().slice(0,10)));break;case"comment":r.push(St("©cmt",i));break;case"lyrics":r.push(St("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Et(t)}if(e.raw)for(const t in e.raw){const i=e.raw[t];i==null||t.length!==4||r.some(n=>n.type===t)||(typeof i=="string"?r.push(St(t,i)):i instanceof Uint8Array&&r.push(oe(t,Array.from(i))))}},St=(r,e)=>{const t=Ct.encode(e);return oe(r,[le(t.length),le(Xc("und")),Array.from(t)])},oo={"image/jpeg":13,"image/png":14,"image/bmp":27},Kc=(r,e)=>{const t=[];for(const{key:i,value:n}of So(r))switch(i){case"title":t.push({key:e?"title":"©nam",value:gt(n)});break;case"description":t.push({key:e?"description":"©des",value:gt(n)});break;case"artist":t.push({key:e?"artist":"©ART",value:gt(n)});break;case"album":t.push({key:e?"album":"©alb",value:gt(n)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:gt(n)});break;case"comment":t.push({key:e?"comment":"©cmt",value:gt(n)});break;case"genre":t.push({key:e?"genre":"©gen",value:gt(n)});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:gt(n)});break;case"date":t.push({key:e?"date":"©day",value:gt(n.toISOString().slice(0,10))});break;case"images":for(const s of n)s.kind==="coverFront"&&t.push({key:"covr",value:oe("data",[q(oo[s.mimeType]??0),q(0),Array.from(s.data)])});break;case"trackNumber":if(e){const s=r.tracksTotal!==void 0?`${n}/${r.tracksTotal}`:n.toString();t.push({key:"track",value:gt(s)})}else t.push({key:"trkn",value:oe("data",[q(0),q(0),le(0),le(n),le(r.tracksTotal??0),le(0)])});break;case"discNumber":e||t.push({key:"disc",value:oe("data",[q(0),q(0),le(0),le(n),le(r.discsTotal??0),le(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Et(i)}if(r.raw)for(const i in r.raw){const n=r.raw[i];n==null||!e&&i.length!==4||t.some(s=>s.key===i)||(typeof n=="string"?t.push({key:i,value:gt(n)}):n instanceof Uint8Array?t.push({key:i,value:oe("data",[q(0),q(0),Array.from(n)])}):n instanceof Xr&&t.push({key:i,value:oe("data",[q(oo[n.mimeType]??0),q(0),Array.from(n.data)])}))}return t},Hm=r=>{const e=Kc(r,!1);return e.length===0?null:xe("meta",0,0,void 0,[ta(!1,"mdir","","appl"),oe("ilst",void 0,e.map(t=>oe(t.key,void 0,[t.value])))])},qm=r=>{const e=Kc(r,!0);return e.length===0?null:oe("meta",void 0,[ta(!1,"mdta",""),xe("keys",0,0,[q(e.length)],e.map(t=>oe("mdta",[...Ct.encode(t.key)]))),oe("ilst",void 0,e.map((t,i)=>{const n=String.fromCharCode(...q(i+1));return oe(n,void 0,[t.value])}))])},gt=r=>oe("data",[q(1),q(0),...Ct.encode(r)]),$m=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";
440case"prores":return e}},Jn={avc:lm,hevc:um,vp8:so,vp9:so,av1:dm,prores:null},Gc=(r,e)=>{switch(r){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(r){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(r){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},jm=(r,e)=>{switch(r){case"aac":return Zn;case"mp3":return Zn;case"opus":return pm;case"vorbis":return Zn;case"flac":return gm;case"ac3":return bm;case"eac3":return km}if(e)switch(r){case"pcm-s24":return nr;case"pcm-s24be":return nr;case"pcm-s32":return nr;case"pcm-s32be":return nr;case"pcm-f32":return nr;case"pcm-f32be":return nr;case"pcm-f64":return nr;case"pcm-f64be":return nr}else switch(r){case"pcm-s16":return _t;case"pcm-s16be":return _t;case"pcm-s24":return _t;case"pcm-s24be":return _t;case"pcm-s32":return _t;case"pcm-s32be":return _t;case"pcm-f32":return _t;case"pcm-f32be":return _t;case"pcm-f64":return _t;case"pcm-f64be":return _t}return null},Km={webvtt:"wvtt"},Gm={webvtt:wm},Xc=r=>{g(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};/*! 441 * Copyright (c) 2026-present, Vanilagy and contributors 442 * 443 * This Source Code Form is subject to the terms of the Mozilla Public 444 * License, v. 2.0. If a copy of the MPL was not distributed with this 445 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 446 */class Cs{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){g(!this.started),this.target._start(),this.started=!0}write(e){g(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return g(this.started&&!this.finalized),this.target._flush()}async finalize(){g(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const i=t+e.byteLength-this.trackedStart;let n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){const s=new Uint8Array(n);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}/*! 447 * Copyright (c) 2026-present, Vanilagy and contributors 448 * 449 * This Source Code Form is subject to the terms of the Mozilla Public 450 * License, v. 2.0. If a copy of the MPL was not distributed with this 451 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 452 */class Wt extends Ai{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){var i;(i=this.onwrite)==null||i.call(this,e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new Xm(this,e)}}const es=2**16,ts=2**32;class Ki extends Wt{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");
452if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(es,{maxByteLength:ts})}catch{this._buffer=new ArrayBuffer(es),this._supportsResize=!1}else this._buffer=new ArrayBuffer(es);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>ts)throw new Error(`ArrayBuffer exceeded maximum size of ${ts} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const i=new ArrayBuffer(t),n=new Uint8Array(i);n.set(this._bytes,0),this._buffer=i,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}}class Xm extends Wt{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class rs{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}}/*! 453 * Copyright (c) 2026-present, Vanilagy and contributors 454 * 455 * This Source Code Form is subject to the terms of the Mozilla Public 456 * License, v. 2.0. If a copy of the MPL was not distributed with this 457 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 458 */const yt=57600,Qm=2082844800,Ym=r=>{const e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},Fe=(r,e,t=!0)=>{const i=r*e;return t?Math.round(i):i};class Zm extends Dh{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Ki,this.auxWriter=new Cs(this.auxTarget,!1),this.auxBoxWriter=new Ni(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ue(),this.creationTime=Math.floor(Date.now()/1e3)+Qm,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof el,this.isCmaf=t instanceof lo,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof lo?1/0:1)}async start(){var i;const e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":n instanceof Ki),this.boxWriter=new Ni(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Ki?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const n=await this.output._getInitTarget(),s=new Cs(n,!0);s.start(),this.initWriter=s,this.initBoxWriter=new Ni(s)}const t=this.output._tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{const n=this.initBoxWriter??this.boxWriter;if(g(n),this.format._options.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(Vh({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){const{data:s,start:a}=n.writer.stopTrackingWrites();this.format._options.onFtyp(s,a)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const n of this.output._tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(g(this.writer),g(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ui(!0),this.boxWriter.writeBox(this.mdat));await((i=this.writer)==null?void 0:i.flush()),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Ko({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const n=this.trackDatas.find(f=>f.track===e);if(n)return n;od(i),g(i),g(i.decoderConfig);const s={...i.decoderConfig};
458g(s.codedWidth!==void 0),g(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){const f=qs(t.data);if(!f)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=gd(f),a=!0}else if(e.source._codec==="hevc"&&!s.description){const f=js(t.data);if(!f)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=vd(f),a=!0}const o=qu(1/(e.metadata.frameRate??yt),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}
458:en({num:c*s.codedHeight,den:l*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:u,decoderConfig:s,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((f,m)=>f.track.id-m.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,i){const n=this.trackDatas.find(c=>c.track===e);if(n)return n;ld(i),g(i),g(i.decoderConfig);const s={...i.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!s.description){const c=Ar(at.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const l=Er[c.samplingFrequencyIndex],u=zi[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=Co({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),a=!0}const o={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&Xe.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const i=this.trackDatas.find(s=>s.track===e);if(i)return i;ud(t),g(t),g(t.config);const n={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,t,i){const n=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,t,i);let a=t.data;if(s.info.requiresAnnexBTransformation){const c=[...Fi(a)].map(l=>a.subarray(l.offset,l.offset+l.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=Hs(c,4)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");const o=this.createSampleForTrack(s,a,t.timestamp,t.duration,t.type);await this.registerSample(s,o)}finally{n()}}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,t,i);let a=t.data;if(s.info.requiresAdtsStripping){const u=Ar(at.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");const d=u.crcCheck===null?an:Ir;a=a.subarray(d)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(s.info.requiresPcmTransformation){const d=er(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(c=a.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){const f=o-s.info.expectedNextPcmPacketTimestamp;if(f<.01)o=s.info.expectedNextPcmPacketTimestamp;else{const m=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);o=s.info.expectedNextPcmPacketTimestamp+m}}s.info.expectedNextPcmPacketTimestamp=o+c}const l=this.createSampleForTrack(s,a,o,c,t.type);await this.registerSample(s,l)}finally{n()}}async padWithSilence(e,t,i){const n=Fe(i,e.timescale);if(i=n/e.timescale,n>0){const{sampleSize:s,silentValue:a}=er(e.info.decoderConfig.codec),o=n*e.info.numberOfChannels,c=new Uint8Array(s*o).fill(a),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,i,"key");await this.registerSample(e,l)}return i}async addSubtitleCue(e,t,i){const n=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(e,i);this.validateTimestamp(s.track,t.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(t),await this.processWebVTTCues(s,t.timestamp))}finally{n()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const l of e.cueQueue)g(l.timestamp<=t),g(e.lastCueEndTimestamp<=l.timestamp+l.duration),i.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),i.add(l.timestamp+l.duration);const n=[...i].sort((l,u)=>l-u),s=n[0],a=n[1]??s;if(t<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const l=Nm();this.auxBoxWriter.writeBox(l);const u=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){const u=e.cueQueue[l];if(u.timestamp>=a)break;ro.lastIndex=0;const d=ro.test(u.text),f=u.timestamp+u.duration;let m=e.cueToSourceId.get(u);if(m===void 0&&a<f&&(m=e.nextSourceId++,e.cueToSourceId.set(u,m)),u.notes){const h=Vm(u.notes);this.auxBoxWriter.writeBox(h)}const p=Um(u.text,d?s:null,u.identifier??null,u.settings??null,m??null);this.auxBoxWriter.writeBox(p),f===a&&e.cueQueue.splice(l--,1)}const o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,a-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,i,n,s){return{timestamp:i,decodeTimestamp:i,duration:n,data:t,size:t.byteLength,type:s,timescaleUnitsToNextSample:Fe(n,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??(e.startTimestampOffset=e.timestampProcessingQueue[0].timestamp));let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){const a=e.timestampProcessingQueue[s],o=Fe(a.duration,e.timescale);n+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleC
vendor: 4,470 bytes, line 458
458ount:n,sampleDelta:1});else{const s=Be(e.timeToSampleTable);s.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);this.isFragmented||(e.startTimestampOffset??(e.startTimestampOffset=i[0]));for(let n=0;n<e.timestampProcessingQueue.length;n++){const s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n];const a=Fe(s.timestamp-s.decodeTimestamp,e.timescale),o=Fe(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){g(e.lastSample);const c=Fe(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(g(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=Be(e.timeToSampleTable);if(g(u),u.sampleCount===1){u.sampleDelta=l;const f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),u=f)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=Be(e.compositionTimeOffsetTable);g(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=Fe(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,g(e.lastSample),g(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){g(t.type==="key");const n=Fe(t.timestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const n=e.track.metadata.maximumPacketCount;if(g(n!==void 0),e.samples.length>n)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${n}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const n=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.closed});n>=this.minimumFragmentDuration&&s&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),g(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(g(!this.isFragmented),g(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((i,n)=>i+Fe(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Be(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)g(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(g(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(const s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(t=s,i=s.sampleQueue[0].timestamp)}if(!t)break;const n=t.sampleQueue.shift();await this.addSampleToTrack(t,n)}}async finalizeFragment(e=!this.isCmaf){g(this.isFragmented);const t=this.nextFragmentNumber++;
458if(t===1){const m=this.initBoxWriter??this.boxWriter;g(m),this.format._options.onMoov&&m.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const p=hi(this);if(m.writeBox(p),this.format._options.onMoov){const{data:h,start:b}=m.writer.stopTrackingWrites();this.format._options.onMoov(h,b)}if(this.isCmaf){g(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Ni(this.writer);const h=this.boxWriter.measureBox(io()),b=this.boxWriter.measureBox(no(this,0));this.segmentHeaderSize=h+b,this.writer.seek(this.segmentHeaderSize)}}g(this.writer),g(this.boxWriter);const i=this.trackDatas.filter(m=>m.currentChunk),n=ao(t,i),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(n);let o=a+$t,c=1/0;for(const m of i){m.currentChunk.offset=o,m.currentChunk.moofOffset=s;for(const p of m.currentChunk.samples)o+=p.size;c=Math.min(c,m.currentChunk.startTimestamp)}const l=o-a,u=l>=2**32;if(u)for(const m of i)m.currentChunk.offset+=wr-$t;this.format._options.onMoof&&this.writer.startTrackingWrites();const d=ao(t,i);if(this.boxWriter.writeBox(d),this.format._options.onMoof){const{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(m,p,c)}g(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const f=Ui(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(a+(u?wr:$t));for(const m of i)for(const p of m.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){const{data:m,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(m,p)}for(const m of i)m.finalizedChunks.push(m.currentChunk),this.finalizedChunks.push(m.currentChunk),m.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(g(this.writer),g(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();const i=hi(this),s=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;g(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ui(!0),this.boxWriter.writeBox(this.mdat);for(const a of this.trackDatas){for(const o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){g(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;g(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.closed=!0,i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(const e of["video","audio","subtitle"]){const t=this.trackDatas.filter(n=>n.type===e);if(t.length===0)continue;if(!t.some(n=>{var s;return((s=n.track.metadata.disposition)==null?void 0:s.default)!==!1})){const n=t[0];n.track.metadata.disposition={...n.track.metadata.disposition,default:!0}}}}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(const t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const t of this.trackDatas){await this.finalizeCurrentChunk(t),g(t.startTimestampOffset!==null);for(let i=0;i<t.samples.length;i++){const n=t.samples[i];n.timestamp-=t.startTimestampOffset,n.decodeTimestamp-=t.startTimestampOffset}}if(g(this.writer),g(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Ui(!1);let t;for(let n=0;n<2;n++){const s=hi(this),a=this.boxWriter.measureBox(s);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(const c of this.finalizedChunks){c.offset=o;for(const{data:l}of c.samples)g(l),o+=l.byteLength,t+=l.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=hi(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const n of this.finalizedChunks)for(const s of n.samples)g(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){const{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,s)}}else if(this.isFragmented)if(this.isCmaf){const t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(io()),this.boxWriter.writeBox(no(this,t))}else{const t=this.writer.getPos(),i=Mm(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{g(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);g(t!==void 0);const i=this.writer.getPos()-t;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}const n=hi(this);if(this.fastStart==="reserve"){g(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);const s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Lh(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}}/*! 459 * Copyright (c) 2026-present, Vanilagy and contributors 460 * 461 * This Source Code Form is subject to the terms of the Mozilla Public 462 * License, v. 2.0. If a copy of the MPL was not distributed with this 463 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 464 */class Jm{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){g(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(i,n)=>i[n*e]:e===1&&t===4?this.channelMixer=(i,n,s)=>i[n*e]*+(s<2):e===1&&t===6?this.channelMixer=(i,n,s)=>i[n*e]*+(s===2):e===2&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return .5*(i[s]+i[s+1])}:e===2&&t===4?this.channelMixer=(i,n,s)=>i[n*e+s]*+(s<2):e===2&&t===6?this.channelMixer=(i,n,s)=>i[n*e+s]*+(s<2):e===4&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return .25*(i[s]+i[s+1]+i[s+2]+i[s+3])}:e===4&&t===2?this.channelMixer=(i,n,s)=>{const a=n*e;return .5*(i[a+s]+i[a+s+2])}:e===4&&t===6?this.channelMixer=(i,n,s)=>{const a=n*e;return s<2?i[a+s]:s===2||s===3?0:i[a+s-2]}:e===6&&t===1?this.channelMixer=(i,n)=>{const s=n*e;return Math.SQRT1_2*(i[s]+i[s+1])+i[s+2]+.5*(i[s+4]+i[s+5])}:e===6&&t===2?this.channelMixer=(i,n,s)=>{const a=n*e;return i[a+s]+Math.SQRT1_2*(i[a+2]+i[a+s+4])}:e===6&&t===4?this.channelMixer=(i,n,s)=>{const a=n*e;return s<2?i[a+s]+Math.SQRT1_2*i[a+2]:i[a+s+2]}:this.channelMixer=(i,n,s)=>s<e?i[n*e+s]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const i=new Float32Array(t);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),g(this.startTime!==null);const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const i=e.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(n,{planeIndex:0,format:"f32"});const s=e.timestamp-this.startTime,a=s+e.duration,o=Math.floor((s-1/this.sourceSampleRate)*this.targetSampleRate)+1,c=Math.ceil(a*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const u=l-this.bufferStartFrame;g(u<this.bufferSizeInFrames);const m=(l/this.targetSampleRate-s)*this.sourceSampleRate,p=Math.floor(m),h=Math.ceil(m),b=m-p;for(let y=0;y<this.targetNumberOfChannels;y++){let x=0,T=0;p>=0&&p<e.numberOfFrames&&(x=this.channelMixer(n,p,y)),h>=0&&h<e.numberOfFrames&&(T=this.channelMixer(n,h,y));const P=x+b*(T-x),_=u*this.targetNumberOfChannels+y;this.outputBuffer[_]+=P}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;g(this.startTime!==null);const e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const i=new Ke({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}}/*! 465 * Copyright (c) 2026-present, Vanilagy and contributors 466 * 467 * This Source Code Form is subject to the terms of the Mozilla Public 468 * License, v. 2.0. If a copy of the MPL was not distributed with this 469 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 470 */class ra{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}
470_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??(this._closingPromise=(async()=>{await this._flushAndClose(e),this._closed=!0})())}}class Qc extends ra{constructor(e){if(super(),this._connectedTrack=null,!wt.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${wt.join(", ")}.`);this._codec=e}}const co=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class ep{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.co
470dedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new pn,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t,i){var s,a,o,c,l,u,d,f,m,p,h,b;const n=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const y=this.encodingConfig,x=y.sizeChangeBehavior??"deny";let T=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(T=!0,x==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(((s=y.transform)==null?void 0:s.width)!==void 0||((a=y.transform)==null?void 0:a.height)!==void 0||((o=y.transform)==null?void 0:o.rotate)!==void 0||((c=y.transform)==null?void 0:c.crop)!==void 0||((l=y.transform)==null?void 0:l.force)===!0||T&&x!=="passThrough"){let I=(u=y.transform)==null?void 0:u.width,C=(d=y.transform)==null?void 0:d.height,v=((f=y.transform)==null?void 0:f.fit)??"fill";T&&x!=="passThrough"&&(g(this.outputWidth),g(this.outputHeight),g(x!=="deny"),I=this.outputWidth,C=this.outputHeight,v=x);const A=await e.transform({width:I,height:C,roundDimensionsTo:2,crop:(m=y.transform)==null?void 0:m.crop,rotate:(p=y.transform)==null?void 0:p.rotate,fit:v,alpha:y.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=A.displayWidth,this.outputHeight=A.displayHeight),t&&e.close(),e=A,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const S=(h=y.transform)==null?void 0:h.frameRate;if(S!==void 0){const I=e.timestamp+e.duration,C=la(e.timestamp,S);if(this.frameRateLastSample!==null)if(C<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=I;return}else await this.padFrameRate(C,i);e===n&&(e=e.clone(),t=!0),e.setTimestamp(C),e.setDuration(1/S),(b=this.frameRateLastSample)==null||b.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=C,this.frameRateLastEndTimestamp=I}await this.processAndEncode(e,i)}finally{t&&e.close()}}async processAndEncode(e,t){var s,a,o;const i=this.encodingConfig;let n;if((s=i.transform)!=null&&s.process){let c=i.transform.process(e);if(c instanceof Promise&&(c=await c),c===null)return;Array.isArray(c)||(c=[c]),n=c.map(l=>l instanceof je?l:typeof VideoFrame<"u"&&l instanceof VideoFrame?new je(l):new je(l,{timestamp:e.timestamp,duration:e.duration}))}else n=[e];try{for(const c of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(c),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized),this.closed)break;const l=this.encodingConfig.keyFrameInterval??2,u=Math.floor(c.timestamp/l),d={...c.encodeOptions,...t},f={...d,keyFrame:d.keyFrame!==void 0?d.keyFrame:l===0||u!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=u,(o=(a=this.encodingConfig).onEncodedSample)==null||o.call(a,c),this.customEncoder){this.customEncoderQueueSize++;const m=c.clone(),p=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(m,f)).catch(h=>this.setError(h)).finally(()=>{this.customEncoderQueueSize--,m.close()});this.customEncoderQueueSize>=4&&await p}else{g(this.encoder);const m=c.toVideoFrame(),p=ye(this.preciseTimings,m.timestamp,b=>b.microsecondTimestamp),h=p!==-1?this.preciseTimings[p]:null;if(h&&h.microsecondTimestamp===m.timestamp?(h.timestamp!==c.timestamp&&(h.timestampIsValid=!1),h.duration!==c.duration&&(h.durationIsValid=!1)):(this.preciseTimings.splice(p+1,0,{microsecondTimestamp:m.timestamp,timestamp:c.timestamp,duration:c.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(m,f),m.close();else if(!!m.format&&!m.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(m,f),m.close();else{this.splitter||(this.splitter=new tp);const{colorFrame:y,alphaFrame:x}=await this.splitter.split(m);this.alphaFrameQueue.push(x),this.encoder.encode(y,f),y.close()}this.encoder.encodeQueueSize>=4&&await new Promise(b=>this.encoder.addEventListener("dequeue",b,{once:!0}))}await this.lastMuxerPromise}}finally{for(const c of n)c!==e&&c.close()}}async padFrameRate(e,t){const i=this.encodingConfig.transform.frameRate;g(this.frameRateLastSample);const n=Math.round((e-this.frameRateLastTimestamp)*i);for(let s=1;s<n;s++){const a=this.frameRateLastSample.clone();a.setTimestamp(this.frameRateLastTimestamp+s/i),a.setDuration(1/i),await this.processAndEncode(a,t),a.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var n,s,a;
470const t=Pc({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:(n=this.source._connectedTrack)==null?void 0:n.metadata.frameRate});(a=(s=this.encodingConfig).onEncoderConfig)==null||a.call(s,t);const i=Bc.find(o=>o.supports(this.encodingConfig.codec,t));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(o,c)=>{var l,u;if(!(o instanceof Ae))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");co(this.source._connectedTrack,o),(u=(l=this.encodingConfig).onEncodedPacket)==null||u.call(l,o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(d=>{this.setError(d)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(t.alpha="discard",this.encodingConfig.alpha==="keep"&&(t.latencyMode="quality"),(t.width%2===1||t.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const l=[],u=[];let d=0,f=0;const m=(h,b,y)=>{var I,C;const x={};if(b){const v=new Uint8Array(b.byteLength);b.copyTo(v),x.alpha=v}let T=Ae.fromEncodedChunk(h,x);const P=ye(this.preciseTimings,h.timestamp,v=>v.microsecondTimestamp),_=P!==-1?this.preciseTimings[P]:null;let S=null;this.emittedEncoderPackets===0&&T.type==="delta"&&(y!=null&&y.decoderConfig)&&(S=Tn(this.encodingConfig.codec,y.decoderConfig,T.data)),(_&&_.microsecondTimestamp===h.timestamp||S!==null)&&(T=T.clone({timestamp:_!=null&&_.timestampIsValid?_.timestamp:void 0,duration:_!=null&&_.durationIsValid?_.duration:void 0,type:S??void 0})),co(this.source._connectedTrack,T),(C=(I=this.encodingConfig).onEncodedPacket)==null||C.call(I,T,y),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,T,y).catch(v=>{this.setError(v)}),this.emittedEncoderPackets++},p=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(h,b)=>{if(!this.alphaEncoder){m(h,null,b);return}const y=this.alphaFrameQueue.shift();g(y!==void 0),y?(this.alphaEncoder.encode(y,{keyFrame:h.type==="key"}),f++,y.close(),l.push({chunk:h,meta:b})):f===0?m(h,null,b):(u.push(d+f),l.push({chunk:h,meta:b}))},error:h=>{h.stack=p,this.setError(h)}}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){const h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(b,y)=>{f--;const x=l.shift();for(g(x!==void 0),m(x.chunk,b,x.meta),d++;u.length>0&&u[0]===d;){u.shift();const T=l.shift();g(T!==void 0),m(T.chunk,null,T.meta)}},error:b=>{b.stack=h,this.setError(b)}}),this.alphaEncoder.configure(t)}}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){var t,i,n;if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){const s=this.encodingConfig.transform.frameRate,a=la(this.frameRateLastEndTimestamp,s);await this.padFrameRate(a)}this.closed=!0,(t=this.frameRateLastSample)==null||t.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await((i=this.alphaEncoder)==null?void 0:i.flush()),await bn(25)),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(s=>s==null?void 0:s.close()),(n=this.splitter)==null||n.close()),e||this.checkForEncoderError()}getQueueSize(){var e;return this.customEncoder?this.customEncoderQueueSize:((e=this.encoder)==null?void 0:e.encodeQueueSize)??0}checkForEncoderError(){if(this.errorSet)throw this.error}}let is=null;class tp{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!is){const n=new Blob([`(${rp.toString()})()`],{type:"application/javascript"});is=URL.createObjectURL(n)}this.worker=new Worker(is),this.worker.addEventListener("message",n=>{const s=n.data,a=this.pendingRequests.get(s.id);a&&(this.pendingRequests.delete(s.id),"error"in s?a.reject(new Error(s.error)):a.resolve({colorFrame:s.colorFrame,alphaFrame:s.alphaFrame}))}),this.worker.addEventListener("error",n=>{const s=new Error(n.message||"Color/alpha splitter worker error.");for(const a of this.pendingRequests.values())a.reject(s);this.pendingRequests.clear()})}const t=this.nextRequestId++,i=Ue();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){var t;(t=this.worker)==null||t.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()}}const rp=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",s=>{const{id:a,sourceFrame:o}=s.data;e=e.then(async()=>{try{const{colorFrame:c,alphaFrame:l}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});const t=async s=>{const a=s.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=s.allocationSize();if((!r||r.byteLength!==o)&&(r=new Uint8Array(o)),await s.copyTo(r),a==="RGBA"||a==="BGRA")return i(r,a,s);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return n(r,a,s);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},i=(s,a,o)=>{var x,T;const c=((x=o.visibleRect)==null?void 0:x.width)??o.codedWidth,l=((T
470=o.visibleRect)==null?void 0:T.height)??o.codedHeight,u=c*l,d=Math.ceil(c/2),f=Math.ceil(l/2),m=u+d*f*2,p=new Uint8Array(m);for(let P=0,_=3;P<u;P++,_+=4)p[P]=s[_];p.fill(128,u);const h=new VideoFrame(s,{format:a==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),b={format:"I420",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[p.buffer]},y=new VideoFrame(p,b);return{colorFrame:h,alphaFrame:y}},n=(s,a,o)=>{var ve,Ie;const c=((ve=o.visibleRect)==null?void 0:ve.width)??o.codedWidth,l=((Ie=o.visibleRect)==null?void 0:Ie.height)??o.codedHeight,u=a.includes("P10"),d=a.includes("P12"),f=u||d?2:1;let m,p;a.startsWith("I420")?(m=Math.ceil(c/2),p=Math.ceil(l/2)):a.startsWith("I422")?(m=Math.ceil(c/2),p=l):(m=c,p=l);const h=c*l,b=m*p,y=h*f,x=b*f,T=h*f,P=y+x*2,_=a.replace("A",""),S=Math.ceil(c/2),I=Math.ceil(l/2),C=S*I,v=C*f,A=T+2*v,H=new Uint8Array(A),M=P;H.set(s.subarray(M,M+T),0);const D=T,$=u?512:d?2048:128;f===1?H.fill($,D):new Uint16Array(H.buffer,D,2*C).fill($);const B=u?"I420P10":d?"I420P12":"I420",O=new VideoFrame(s.subarray(0,P),{format:_,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),X={format:B,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[H.buffer]},ae=new VideoFrame(H,X);return{colorFrame:O,alphaFrame:ae}}};class ip extends Qc{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");mh(t),super(t.codec),this._encoder=new ep(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const n=new je(this._canvas,{timestamp:e,duration:t});return this._encoder.add(n,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Yc extends ra{constructor(e){if(super(),this._connectedTrack=null,!Jt.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Jt.join(", ")}.`);this._codec=e}}class np{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new pn,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){var i,n;try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;const s=this.encodingConfig;((i=s.transform)==null?void 0:i.numberOfChannels)!==void 0||((n=s.transform)==null?void 0:n.sampleRate)!==void 0?(this.resampler||(this.resampler=new Jm({targetNumberOfChannels:s.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:s.transform.sampleRate??e.sampleRate,onSample:async o=>{await this.processAndEncode(o,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){var n,s;const i=this.encodingConfig;if(((n=i.transform)==null?void 0:n.sampleFormat)!==void 0&&dh(e.format)!==i.transform.sampleFormat){const a=hh(e,i.transform.sampleFormat);t&&e.close(),e=a,t=!0}if((s=i.transform)!=null&&s.process){let a=i.transform.process(e);if(a instanceof Promise&&(a=await a),a===null)return;
470Array.isArray(a)||(a=[a]);for(const o of a){if(!(o instanceof Ke))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(o,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){var i,n;try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized),this.closed)return;{const s=Math.round(e.timestamp*e.sampleRate),a=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=a;else{const o=s-this.lastEndSampleIndex;if(o>=64){const c=new Ke({data:new Float32Array(o*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:o,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(c,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if((n=(i=this.encodingConfig).onEncodedSample)==null||n.call(i,e),this.customEncoder){this.customEncoderQueueSize++;const s=e.clone(),a=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(s)).catch(o=>this.setError(o)).finally(()=>{this.customEncoderQueueSize--,s.close()});this.customEncoderQueueSize>=4&&await a,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{g(this.encoder);const s=e.toAudioData();this.encoder.encode(s),s.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(a=>this.encoder.addEventListener("dequeue",a,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){var f,m;g(this.outputSampleSize),g(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:n,sampleRate:s,timestamp:a}=e,o=2048,c=[];for(let p=0;p<n;p+=o){const h=Math.min(o,e.numberOfFrames-p),b=h*i*this.outputSampleSize,y=new ArrayBuffer(b),x=new DataView(y);c.push({frameCount:h,view:x})}const l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let p=0;p<i;p++){e.copyTo(u,{planeIndex:p,format:"f32-planar"});for(let h=0;h<c.length;h++){const{frameCount:b,view:y}=c[h];for(let x=0;x<b;x++)this.writeOutputValue(y,(x*i+p)*this.outputSampleSize,u[h*o+x])}}t&&e.close();const d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let p=0;p<c.length;p++){const{frameCount:h,view:b}=c[p],y=b.buffer,x=p*o,T=new Ae(new Uint8Array(y),"key",a+x/s,h/s);(m=(f=this.encodingConfig).onEncodedPacket)==null||m.call(f,T,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,T,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var a,o;const{numberOfChannels:t,sampleRate:i}=e,n=Ic({numberOfChannels:t,sampleRate:i,...this.encodingConfig});(o=(a=this.encodingConfig).onEncoderConfig)==null||o.call(a,n);const s=Rc.find(c=>c.supports(this.encodingConfig.codec,n));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(c,l)=>{var u,d;if(!(c instanceof Ae))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(l!==void 0&&(!l||typeof l!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");(d=(u=this.encodingConfig).onEncodedPacket)==null||d.call(u,c,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,c,l).catch(f=>{this.setError(f)})},this.customEncoder.onError=c=>{this.setError(c)},await this.customEncoder.init();else if(Xe.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);const l=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(u,d)=>{var m,p;if(this.encodingConfig.codec==="aac"&&(d!=null&&d.decoderConfig)){let h=!1;if(!d.decoderConfig.description||d.decoderConfig.description.byteLength<2?h=!0:h=Ns(Ge(d.decoderConfig.description)).objectType===0,h){const b=Number(Be(n.codec.split(".")));d.decoderConfig.description=Co({objectType:b,numberOfChannels:d.decoderConfig.numberOfChannels,sampleRate:d.decoderConfig.sampleRate})}}let f=Ae.fromEncodedChunk(u);
470f=f.clone({timestamp:Zi(f.timestamp,n.sampleRate),duration:u.duration!=null?Zi(f.duration,n.sampleRate):void 0}),(p=(m=this.encodingConfig).onEncodedPacket)==null||p.call(m,f,d),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,f,d).catch(h=>{this.setError(h)})},error:u=>{u.stack=l,this.setError(u)}}),this.encoder.configure(n)}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:n}=er(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,De((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,De(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{const c=De(Math.floor(o*32767),-32768,32767);s.setUint8(a,kh(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{const c=De(Math.floor(o*32767),-32768,32767);s.setUint8(a,wh(c))}:g(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,De((o+1)*32767.5,0,65535),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,De(Math.round(o*32767),-32768,32767),n):g(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>Rs(s,a,De((o+1)*83886075e-1,0,16777215),n):t==="signed"?this.writeOutputValue=(s,a,o)=>Uu(s,a,De(Math.round(o*8388607),-8388608,8388607),n):g(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,De((o+1)*21474836475e-1,0,4294967295),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,De(Math.round(o*2147483647),-2147483648,2147483647),n):t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat32(a,o,n):g(!1);break;case 8:t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat64(a,o,n):g(!1);break;default:Et(i),g(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){var e;return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:((e=this.encoder)==null?void 0:e.encodeQueueSize)??0}checkForEncoderError(){if(this.errorSet)throw this.error}}class sp extends Yc{constructor(e){ph(e),super(e.codec),this._accumulatedTime=0,this._encoder=new np(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=Ke._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const i of t)await this._encoder.add(i,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class ap extends ra{constructor(e){if(super(),this._connectedTrack=null,!Si.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Si.join(", ")}.`);this._codec=e}}/*! 471 * Copyright (c) 2026-present, Vanilagy and contributors 472 * 473 * This Source Code Form is subject to the terms of the Mozilla Public 474 * License, v. 2.0. If a copy of the MPL was not distributed with this 475 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 476 */class Zc{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>wt.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Jt.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Si.includes(e))}_codecUnsupportedHint(e){return""}}class ia extends Zc{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");
476if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Zm(e,this)}}class Jc extends ia{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...wt,...Us,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Si]}_codecUnsupportedHint(e){return new el().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class lo extends ia{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...wt,...Us,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Si]}}class el extends ia{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...wt,...Jt]}_codecUnsupportedHint(e){return new Jc().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}/*! 477 * Copyright (c) 2026-present, Vanilagy and contributors 478 * 479 * This Source Code Form is subject to the terms of the Mozilla Public 480 * License, v. 2.0. If a copy of the MPL was not distributed with this 481 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 482 */const op=["video","audio","subtitle"];class Ri{constructor(e,t,i,n,s){this.id=e,this.output=t,this.type=i,this.source=n,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof Ri))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=da(this.metadata.group),i=da(e.metadata.group);for(const n of t)if(this.type!==e.type&&i.some(o=>n===o)||i.some(o=>n._pairedGroups.has(o)))return!0;return!1}}class cp extends Ri{constructor(e,t,i,n){super(e,t,"video",i,n)}}class lp extends Ri{constructor(e,t,i,n){super(e,t,"audio",i,n)}}class up extends Ri{constructor(e,t,i,n){super(e,t,"subtitle",i,n)}}class Ci{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof Ci))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const ns=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!Ms(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&Xu(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof Ci)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof Ci))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class dp extends Ai{get target(){const e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);const t=this._getRootTarget();if(t instanceof Promise)throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new Ci,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new ii,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Zc))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Wt||e.target instanceof rs))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Wt&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Wt)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Wt&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){g(this._target instanceof rs);const t=this._target.getTarget(e),i=n=>{if(!(n instanceof Wt))throw new TypeError("getTarget must return a Target.");return n};return t instanceof Promise?t.then(i):i(t)}async _getTarget(e){g(this._target instanceof rs);const t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}
482async _getInitTarget(){if(g(this._initTarget!==null),this._initTarget instanceof Wt)return this._initTarget;const e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Wt)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),i=n=>(this.state==="canceled"?n._close():this._rememberTarget(n),this._emit("target",{target:n,request:e,isRoot:!0}),this._rootTarget=n,n);return t instanceof Promise?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??(this._rootWriterPromise=(async()=>{const t=await this._getRootTarget(),i=new Cs(t,typeof e=="boolean"?e:e(t));return i.start(),i})())}addVideoTrack(e,t={}){if(!(e instanceof Qc))throw new TypeError("source must be a VideoSource.");if(ns(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);const i={...t};return i.group??(i.group=this.defaultTrackGroup),this._addTrack(new cp(this._tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof Yc))throw new TypeError("source must be an AudioSource.");ns(t);const i={...t};return i.group??(i.group=this.defaultTrackGroup),this._addTrack(new lp(this._tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof ap))throw new TypeError("source must be a SubtitleSource.");ns(t);const i={...t};return i.group??(i.group=this.defaultTrackGroup),this._addTrack(new up(this._tracks.length+1,this,e,i))}setMetadataTags(e){if(Gu(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const t=this.format.getSupportedTrackCounts(),i=this._tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),n=t[e.type].max;if(i===n)throw new Error(n===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${n} ${e.type} track${n===1?"":"s"}.`);const s=t.total.max;if(this._tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){const a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}
482async start(){const e=this.format.getSupportedTrackCounts();for(const i of op){const n=this._tracks.reduce((a,o)=>a+(o.type===i?1:0),0),s=e[i].min;if(n<s)throw new Error(s===e[i].max?`${this.format._name} requires exactly ${s} ${i} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${i} track${s===1?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(ue._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const i=await this._mutex.acquire();try{await this._muxer.start();const n=this._tracks.map(s=>s.source._start());await Promise.all(n)}finally{i()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return ue._warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&ue._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(ue._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){const i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}}function fp(r){const e="url"in r?new Sn(r.url):new Ys(r.file);return new zr({formats:cn,source:e})}async function hp(r,e=48){var o;const t=await r.getPrimaryVideoTrack();if(!t)return null;const i=new Nc(t,{height:e}),n=Math.max(0,await t.getFirstTimestamp().catch(()=>0)),s=i.canvasesAtTimestamps([n]),{value:a}=await s.next();return await((o=s.return)==null?void 0:o.call(s)),(a==null?void 0:a.canvas)??null}async function mp(r,{height:e=48,everySeconds:t=1}={}){const i=await r.getPrimaryVideoTrack();if(!i)return[];const n=await r.computeDuration(),s=await r.getFirstTimestamp().catch(()=>0),a=new Nc(i,{height:e}),o=[];for(let l=s;l<s+n;l+=t)o.push(l);const c=[];for await(const l of a.canvasesAtTimestamps(o))l&&c.push(l);return c}const tl=.5,pp=64,gp=120;function bp(){const r=zn(new Map),e=new Map,t=new Map;function i(m){var p;return(p=r.get(m))==null?void 0:p.poster}function n(m){var p;return((p=r.get(m))==null?void 0:p.loading)??!1}function s(m){var p;return((p=r.get(m))==null?void 0:p.strip)??[]}async function a(m){if(m instanceof HTMLCanvasElement)return m.toDataURL("image/jpeg",.7);const p=await m.convertToBlob({type:"image/jpeg",quality:.7});return URL.createObjectURL(p)}function o(m,p){let h=e.get(m);return(!h||h.disposed)&&(h=fp(p),e.set(m,h)),h}async function c(m,p){return o(m,p)}function l(m,p){const h=r.get(m);if(h!=null&&h.poster||h!=null&&h.loading||t.has(`${m}:poster`))return;const b=h??zn({loading:!1});b.loading=!0,r.set(m,b);const y=(async()=>{try{const x=await c(m,p),T=await hp(x,48);if(!T||!r.has(m))return;b.poster=await a(T)??void 0}catch{}finally{b.loading=!1,t.delete(`${m}:poster`)}})();t.set(`${m}:poster`,y)}function u(m,p){const h=r.get(m);if(h!=null&&h.strip||h!=null&&h.stripLoading||t.has(`${m}:strip`))return;const b=h??zn({loading:!1});b.stripLoading=!0,r.set(m,b);const y=(async()=>{try{const x=await c(m,p),T=await mp(x,{height:pp,everySeconds:tl});if(!r.has(m))return;const P=[];for(const _ of T.slice(0,gp)){const S=await a(_.canvas);S&&P.push({t:_.timestamp,url:S})}b.strip=P}catch{}finally{b.stripLoading=!1,t.delete(`${m}:strip`)}})();t.set(`${m}:strip`,y)}function d(m){var p;(p=m==null?void 0:m.poster)!=null&&p.startsWith("blob:")&&URL.revokeObjectURL(m.poster);for(const h of(m==null?void 0:m.strip)??[])h.url.startsWith("blob:")&&URL.revokeObjectURL(h.url)}function f(m){d(r.get(m)),r.delete(m);const p=e.get(m);p&&!p.disposed&&p.dispose(),e.delete(m)}return Br(()=>{for(const m of[...e.keys()])f(m);for(const m of[...r.keys()])f(m)}),{posterOf:i,loadingOf:n,stripOf:s,ensure:l,ensureStrip:u,inputFor:o,forget:f}}const kp={class:"flex h-52 flex-shrink-0 flex-col border-t border-zinc-200 dark:border-zinc-800"},yp={class:"relative flex h-9 flex-shrink-0 items-center gap-1 border-b border-zinc-200 px-2 dark:border-zinc-800"},wp=["disabled","aria-label"],xp=["disabled","aria-label"],Tp=["aria-pressed","aria-label"],_p=["aria-label"],Sp=["value","aria-label"],vp=["aria-label"],Pp=["aria-label","aria-expanded"],Cp={key:0,class:"absolute bottom-full right-0 z-30 mb-1 w-64 roun
482ded-lg border border-zinc-200 bg-white p-1 shadow-md dark:border-zinc-800 dark:bg-zinc-950"},Ip={class:"flex h-7 items-center justify-between px-2"},Ep={class:"text-xs font-medium text-zinc-900 dark:text-zinc-100"},Ap=["aria-label"],zp={class:"text-xs text-zinc-600 dark:text-zinc-300"},Fp={class:"flex-shrink-0 rounded border border-zinc-200 bg-zinc-50 px-1 text-[10px] font-medium tabular-nums text-zinc-500 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-400"},Bp=["src"],Rp=["aria-label","onFocus","onPointerdown","onClick"],Mp={class:"pointer-events-none absolute left-1 top-1 z-20 max-w-[70%] truncate rounded bg-white/90 px-1 text-[11px] font-medium leading-4 text-zinc-800 dark:bg-zinc-900/90 dark:text-zinc-200"},Op={class:"pointer-events-none absolute bottom-1 right-1 z-20 rounded bg-white/90 px-1 text-[11px] font-medium leading-4 tabular-nums text-zinc-800 dark:bg-zinc-900/90 dark:text-zinc-200"},Dp=["onPointerdown"],Np=["onPointerdown"],Up={key:1,class:"flex min-h-0 flex-1 items-center justify-center px-6"},Vp={class:"text-xs text-zinc-400 dark:text-zinc-500"},uo=10,fo=200,Lp=6,Wp=Fr({__name:"StudioTimeline",props:{studio:{},playback:{},thumbs:{},editingDisabled:{type:Boolean}},setup(r,{expose:e}){const t=r,{t:i}=Rr(),{studio:n,playback:s,thumbs:a}=t,o=pe(()=>n.project.value.fps),c=pe(()=>n.project.value.clips),l=pe(()=>Zt(n.project.value)),u=pe(()=>xo(n.project.value)),d=pe(()=>c.value.length>0),f=ke(null),m=ke(null),p=al(f),h=ke(!0),b=ke(40),y=ke(!1),x=pe(()=>Math.max(s.total.value*b.value+80,p.width.value));function T(z,R){const V=Math.min(fo,Math.max(uo,z));if(V===b.value)return;const j=f.value;if(j&&R!==void 0){const we=(R-j.getBoundingClientRect().left+j.scrollLeft)/b.value;b.value=V,os(()=>{j.scrollLeft=we*b.value-(R-j.getBoundingClientRect().left)});return}b.value=V}function P(){T(b.value*1.25)}function _(){T(b.value/1.25)}function S(z){T(Number(z.target.value))}function I(z){if(!z.ctrlKey&&!z.metaKey)return;z.preventDefault();const R=z.deltaY<0?1.15:1/1.15;T(b.value*R,z.clientX)}Gr(d,async z=>{var V;if(!z||y.value)return;await os();const R=((V=f.value)==null?void 0:V.clientWidth)??0;R>0&&s.total.value>0&&(b.value=Math.min(fo,Math.max(uo,(R-80)/s.total.value)),y.value=!0)},{immediate:!0}),Gr(()=>s.currentTime.value,z=>{const R=f.value;if(!R||!s.playing.value)return;const V=z*b.value,j=Math.min(60,R.clientWidth*.2);(V<R.scrollLeft+j||V>R.scrollLeft+R.clientWidth-j)&&R.scrollTo({left:Math.max(0,V-R.clientWidth*.3)})});const C=[.1,.25,.5,1,2,5,10,15,30,60,120,300,600],v=pe(()=>{const z=b.value,R=C.find(ee=>ee*z>=72)??C[C.length-1],V=R/4,j=Math.max(1,R),ne=[],we=s.total.value+R;for(let ee=0;ee<=we;ee+=V){const he=Math.abs(ee/R-Math.round(ee/R))<1e-6,lt=Math.abs(ee/j-Math.round(ee/j))<1e-6;ne.push({x:ee*z,major:he,label:lt?A(ee):void 0})}return ne});function A(z){const R=Math.floor(z/60),V=Math.floor(z%60),j=ne=>String(ne).padStart(2,"0");return`${j(R)}:${j(V)}`}const H=pe(()=>s.currentTime.value*b.value);let M=!1;function D(z){const R=m.value;if(!R)return 0;const V=z-R.getBoundingClientRect().left;return Math.min(Math.max(V/b.value,0),s.total.value)}function $(z){if(z.button!==0)return;M=!0,z.currentTarget.setPointerCapture(z.pointerId);const R=z.currentTarget,V=ne=>{M&&s.seek(D(ne.clientX))},j=()=>{M=!1,R.removeEventListener("pointermove",V),R.removeEventListener("pointerup",j),R.removeEventListener("pointercancel",j)};R.addEventListener("pointermove",V),R.addEventListener("pointerup",j),R.addEventListener("pointercancel",j),s.seek(D(z.clientX))}function B(z){z.button===0&&s.seek(D(z.clientX))}const O=ke(null);function X(z){var R;t.editingDisabled||(R=z.dataTransfer)!=null&&R.types.includes(ls)&&(z.preventDefault(),z.dataTransfer.dropEffect="copy",O.value=Fn(n.project.value,D(z.clientX)))}function ae(z){z.currentTarget.contains(z.relatedTarget)||(O.value=null)}function ve(z){var j;if(t.editingDisabled){O.value=null;return}const R=(j=z.dataTransfer)==null?void 0:j.getData(ls);if(O.value=null,!R)return;z.preventDefault();const V=Fn(n.project.value,D(z.clientX));n.insertSource(R,V)}function Ie(z){var R;return((R=n.project.value.sources.find(V=>
482V.id===z.sourceId))==null?void 0:R.label)??""}function ct(z){return a.stripOf(z.sourceId).filter(R=>R.t>=z.in-.001&&R.t<z.out-.001)}Gr(()=>c.value.map(z=>z.sourceId).join(","),()=>{for(const z of c.value){const R=n.project.value.sources.find(j=>j.id===z.sourceId);if((R==null?void 0:R.status)!=="ready")continue;const V=n.sourceFiles.get(R.id);a.ensureStrip(R.id,V?{file:V}:{url:R.url})}},{immediate:!0});let de=null,qe=!1;function xt(z,R,V){z.button!==0||t.editingDisabled||(de={kind:"move",clipId:R.id,startClientX:z.clientX,origClip:{...R},origStart:l.value[V],origTime:s.currentTime.value,targets:[...u.value,s.currentTime.value],moved:!1,fromIndex:V},z.currentTarget.setPointerCapture(z.pointerId))}function Ft(z){!de||de.kind!=="move"||!de.moved&&Math.abs(z.clientX-de.startClientX)<4||(de.moved=!0,O.value=Fn(n.project.value,D(z.clientX)))}function Bt(z){if(!de||de.kind!=="move")return;const{clipId:R,fromIndex:V,moved:j}=de;if(de=null,j){const ne=O.value??V;O.value=null,qe=!0,setTimeout(()=>{qe=!1},0),n.moveClip(R,ne>V?ne-1:ne)}}function Rt(){(de==null?void 0:de.kind)==="move"&&(de=null,O.value=null)}function Mt(z,R){qe||(n.select(R.id),s.seek(D(z.clientX)))}function pt(z,R,V,j){z.button!==0||t.editingDisabled||(z.preventDefault(),de={kind:"trim",clipId:R.id,edge:j,startClientX:z.clientX,origClip:{...R},origStart:l.value[V],origTime:s.currentTime.value,targets:[...u.value,s.currentTime.value],moved:!1,fromIndex:V},n.beginDraft(),z.currentTarget.setPointerCapture(z.pointerId))}function te(z){if(!de||de.kind!=="trim"||!de.edge)return;de.moved=!0;const R=(z.clientX-de.startClientX)/b.value;let j=(de.edge==="in"?de.origStart:de.origStart+(de.origClip.out-de.origClip.in))+R;h.value&&(j=Cu(j,de.targets,Lp/b.value));const ne=de.origClip.in+(j-de.origStart);n.updateDraft(To(n.project.value,de.clipId,de.edge,ne));const we=n.project.value.clips.findIndex(ee=>ee.id===de.clipId);if(we>=0){const ee=n.project.value.clips[we],he=Zt(n.project.value);s.seek(de.edge==="in"?he[we]:he[we]+ft(ee))}}function J(z){if(!de||de.kind!=="trim")return;const R=de.origTime;de=null,z?n.commitDraft():(n.cancelDraft(),s.seek(R))}const Te=()=>J(!0),ge=()=>J(!1),ce=pe(()=>{const z=Sr(n.project.value,s.currentTime.value);if(!z)return!1;const R=c.value[z.clipIndex],V=l.value[z.clipIndex],j=Zr(o.value),ne=s.currentTime.value;return ne-V>=j-1e-9&&V+ft(R)-ne>=j-1e-9});function k(){ce.value&&n.splitAt(s.currentTime.value)}function N(){const z=n.selectedClipId.value;z&&n.removeClip(z)}const E=ke(!1),F=pe(()=>typeof navigator<"u"&&/mac/i.test(navigator.platform)),G=pe(()=>[{label:i("sc_play"),keys:"Space"},{label:i("sc_frame"),keys:"â / â"},{label:i("sc_second"),keys:"Shift+â / â"},{label:i("sc_split"),keys:"S"},{label:i("sc_delete"),keys:"Del"},{label:i("sc_undo"),keys:F.value?"âZ":"Ctrl+Z"},{label:i("sc_redo"),keys:F.value?"ââ§Z":"Ctrl+Shift+Z"},{label:i("sc_in_out"),keys:"I / O"},{label:i("sc_zoom"),keys:"+ / â"},{label:i("sc_move"),keys:"Alt+â / â"}]);function U(z){if(z.key==="Escape"){if(de){z.preventDefault(),z.stopPropagation(),de.kind==="trim"?J(!1):(de=null,O.value=null);return}E.value&&(E.value=!1)}}return dn(()=>window.addEventListener("keydown",U,!0)),Br(()=>window.removeEventListener("keydown",U,!0)),e({zoomIn:P,zoomOut:_,setZoom:T}),(z,R)=>(Z(),re("div",kp,[L("div",yp,[L("button",{type:"button",disabled:!w(ce)||r.editingDisabled,"aria-label":w(i)("split"),class:"inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs font-medium text-zinc-500 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:k},[be(w(Rl),{class:"h-3.5 w-3.5"}),$e(" "+Y(w(i)("split")),1)],8,wp),L("button",{type:"button",disabled:!w(n).selectedClipId.value||r.editingDisabled,"aria-label":w(i)("delete"),class:"inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs font-medium text-zinc-500 transition-colors duration-150 hover:bg-red-50 hover:text-red-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:text-zinc-400 dark:hover:bg-red-500/10 dark:hover:text-red-400",onClick:N},[be(w(Dl),{class:"h-3.5 w-3.5"}),$e(" "+Y(w(i)("delete")),1)],8,xp),L("button",{type:"button","aria-pressed":w(h),"aria-label":w(i)("snap"),class:qt(["inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none",w(h)?"bg-zinc-100 text-zinc-900 dark:bg-white/[0.08] dark:text-zinc-100":"text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100"]),onClick:R[0]||(R[0]=V=>h.value=!w(h))},[be(w(Cl),{class:"h-3.5 w-3.5"}),$e(" "+Y(w(i)("snap")),1)],10,Tp),R[3]||(R[3]=L("div",{class:"flex-1"},null,-1)),L("button",{type:"button","aria-label":w(i)("zoom_out"),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-500 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:_},[be(w(Ll),{class:"h-3.5 w-3.5"})],8,_p),L("input",{type:"range",min:"10",max:"200",step:"1",value:w(b),"aria-label":w(i)("zoom"),class:"h-4 w-24 accent-zinc-900 dark:accent-zinc-100",onInput:S},null,40,Sp),L("button",{type:"button","aria-label":w(i)("zoom_in"),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-500 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:P},[be(w(Vl),{class:"h-3.5 w-3.5"})],8,vp),L("button",{type:"button","aria-label":w(i)("shortcuts"),"aria-expanded":w(E),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-500 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:R[1]||(R[1]=V=>E.value=!w(E))},[be(w(Sl),{class:"h-3.5 w-3.5"})],8,Pp),w(E)?(Z(),re("div",Cp,[L("div",Ip,[L("span",Ep,Y(w(i)("shortcuts")),1),L("button",{type:"button","aria-label":w(i)("back"),
482class:"inline-flex h-5 w-5 items-center justify-center rounded-md text-zinc-400 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:R[2]||(R[2]=V=>E.value=!1)},[be(w(fn),{class:"h-3 w-3"})],8,Ap)]),(Z(!0),re(Qe,null,Xt(w(G),V=>(Z(),re("div",{key:V.label,class:"flex items-center justify-between gap-3 rounded-md px-2 py-1"},[L("span",zp,Y(V.label),1),L("kbd",Fp,Y(V.keys),1)]))),128))])):Ce("",!0)]),w(d)?(Z(),re("div",{key:0,ref_key:"scrollEl",ref:f,class:"relative min-h-0 flex-1 select-none overflow-x-auto overflow-y-hidden",onWheel:I},[L("div",{ref_key:"innerEl",ref:m,class:"relative h-full",style:Dt({width:`${w(x)}px`})},[L("div",{ref:"rulerEl",class:"relative h-6 cursor-ew-resize border-b border-zinc-200 dark:border-zinc-800",onPointerdown:$},[(Z(!0),re(Qe,null,Xt(w(v),V=>(Z(),re(Qe,{key:V.x},[L("div",{class:qt(["absolute bottom-0 w-px bg-zinc-300 dark:bg-zinc-700",V.major?"h-2.5":"h-1"]),style:Dt({left:`${V.x}px`})},null,6),V.label?(Z(),re("span",{key:0,class:"absolute left-0 top-0.5 pl-1 text-[11px] leading-3 tabular-nums text-zinc-500 dark:text-zinc-400",style:Dt({left:`${V.x}px`})},Y(V.label),5)):Ce("",!0)],64))),128)),L("div",{class:"absolute bottom-0 z-10 -ml-1.5 h-3 w-3 cursor-ew-resize rounded-sm bg-zinc-900 dark:bg-white",style:Dt({left:`${w(H)}px`}),onPointerdown:nt($,["stop"])},null,36)],544),L("div",{class:"relative h-16",onPointerdown:B,onDragover:X,onDragleave:ae,onDrop:ve},[(Z(!0),re(Qe,null,Xt(w(c),(V,j)=>(Z(),re("div",{key:V.id,class:"absolute top-0 h-16 py-0.5",style:Dt({left:`${w(l)[j]*w(b)}px`,width:`${Math.max(w(ft)(V)*w(b)-2,8)}px`})},[L("div",{class:qt(["group/clip relative h-full overflow-hidden rounded-md border border-zinc-200 bg-zinc-50 dark:border-zinc-800 dark:bg-zinc-900",w(n).selectedClipId.value===V.id?"ring-2 ring-zinc-900 dark:ring-white":""])},[(Z(!0),re(Qe,null,Xt(ct(V),ne=>(Z(),re("img",{key:ne.t,src:ne.url,alt:"",draggable:"false",class:"pointer-events-none absolute top-0 h-full object-cover",style:Dt({left:`${(ne.t-V.in)*w(b)}px`,width:`${w(tl)*w(b)}px`})},null,12,Bp))),128)),L("button",{type:"button",class:"absolute inset-0 z-10 w-full focus-visible:outline-none","aria-label":w(i)("clip_aria",{n:j+1,start:w(st)(w(l)[j],w(o)),end:w(st)(w(l)[j]+w(ft)(V),w(o))}),onFocus:ne=>w(n).select(V.id),onPointerdown:ne=>xt(ne,V,j),onPointermove:Ft,onPointerup:Bt,onPointercancel:Rt,onClick:ne=>Mt(ne,V)},null,40,Rp),L("span",Mp,Y(Ie(V)),1),L("span",Op,Y(w(st)(w(ft)(V),w(o))),1),L("div",{role:"presentation",class:qt(["absolute inset-y-0 left-0 z-30 w-1.5 cursor-ew-resize touch-none opacity-0 transition-opacity duration-150 group-hover/clip:opacity-100 group-focus-within/clip:opacity-100",w(n).selectedClipId.value===V.id?"opacity-100":""]),onPointerdown:nt(ne=>pt(ne,V,j,"in"),["stop"]),onPointermove:te,onPointerup:Te,onPointercancel:ge},[...R[4]||(R[4]=[L("div",{class:"mx-auto mt-[22px] h-5 w-1 rounded-full bg-white/90 ring-1 ring-black/10 dark:bg-zinc-300/90"},null,-1)])],42,Dp),L("div",{role:"presentation",class:qt(["absolute inset-y-0 right-0 z-30 w-1.5 cursor-ew-resize touch-none opacity-0 transition-opacity duration-150 group-hover/clip:opacity-100 group-focus-within/clip:opacity-100",w(n).selectedClipId.value===V.id?"opacity-100":""]),onPointerdown:nt(ne=>pt(ne,V,j,"out"),["stop"]),onPointermove:te,onPointerup:Te,onPointercancel:ge},[...R[5]||(R[5]=[L("div",{class:"mx-auto mt-[22px] h-5 w-1 rounded-full bg-white/90 ring-1 ring-black/10 dark:bg-zinc-300/90"},null,-1)])],42,Np)],2)],4))),128)),w(O)!==null?(Z(),re("div",{key:0,class:"pointer-events-none absolute inset-y-0 z-20 w-0.5 bg-zinc-900 dark:bg-white",style:Dt({left:`${(w(u)[w(O)]??0)*w(b)-1}px`})},null,4)):Ce("",!0)],32),L("div",{class:"pointer-events-none absolute inset-y-0 w-px bg-zinc-900 dark:bg-white",style:Dt({left:`${w(H)}px`})},null,4)],4)],544)):(Z(),re("div",Up,[L("p",Vp,Y(w(i)("timeline_empty")),1)]))]))}}),Hp={class:"flex items-center justify-between gap-3 py-1.5"},qp={class:"flex flex-col items-end gap-0.5"},$p=["value","aria-invalid","onKeydown"],jp={key:0,class:"text-[11px] leading-3 text-red-600 dark:text-red-400"},ho=Fr({__name:"StudioTimecodeField",props:{label:{},modelValue:{},fps:{}},emits:["commit"],setup(r,{emit:e}){const t=r,i=e,{t:n}=Rr(),s=`tc-${Math.random().toString(36).slice(2,8)}`,a=ke(!1),o=ke(""),c=ke(!1);function l(){a.value=!0,c.value=!1,o.value=st(t.modelValue,t.fps)}function u(p){o.value=p.target.value,c.value=!1}function d(p){var b;const h=aa(o.value,t.fps);if(h===null){c.value=!0;return}a.value=!1,c.value=!1,i("commit",h),(b=p==null?void 0:p.target)==null||b.blur()}function f(){a.value=!1,c.value=!1,o.value=st(t.modelValue,t.fps)}function m(){if(!a.value)return;if(c.value){f();return}const p=aa(o.value,t.fps);a.value=!1,p!==null&&i("commit",p)}return(p,h)=>(Z(),re("div",Hp,[L("label",{for:s,class:"text-xs text-zinc-500 dark:text-zinc-400"},Y(r.label),1),L("div",qp,[L("input",{id:s,value:w(a)?w(o):w(st)(r.modelValue,r.fps),type:"text",inputmode:"numeric",spellcheck:"false","aria-invalid":w(c),class:qt(["h-7 w-24 rounded-md border bg-white px-2 text-right text-xs tabular-nums text-zinc-900 transition-colors focus:outline-none dark:bg-zinc-900 dark:text-zinc-100",w(c)?"border-red-300 focus:border-red-400 focus:ring-2 focus:ring-red-500/10 dark:border-red-500/40":"border-zinc-200 hover:border-zinc-300 focus:border-zinc-400 focus:ring-2 focus:ring-zinc-900/5 dark:border-zinc-800 dark:hover:border-zinc-700 dark:focus:border-zinc-600 dark:focus:ring-white/10"]),onFocus:l,onInput:u,onKeydown:[h[0]||(h[0]=cs(nt(b=>d(b),["prevent"]),["enter"])),cs(nt(f,["prevent"]),["esc"])],onBlur:m}
482,null,42,$p),w(c)?(Z(),re("p",jp,Y(w(n)("invalid_timecode")),1)):Ce("",!0)])]))}}),Kp=["aria-label"],Gp={class:"flex h-11 items-center justify-between border-b border-zinc-200 px-4 dark:border-zinc-800"},Xp={class:"flex items-center gap-2"},Qp={class:"text-[13px] font-semibold text-zinc-950 dark:text-zinc-100"},Yp=["disabled","aria-label"],Zp={class:"p-4"},Jp={key:0,class:"flex items-center gap-2 py-2 text-xs text-zinc-500 dark:text-zinc-400"},eg={key:0,class:"flex items-center justify-between gap-3 py-1.5"},tg={class:"text-xs text-zinc-500 dark:text-zinc-400"},rg={class:"flex flex-col items-end gap-1"},ig={role:"group",class:"inline-flex h-7 rounded-md bg-zinc-100 p-0.5 dark:bg-white/[0.06]"},ng=["aria-pressed","disabled","onClick"],sg={class:"text-[11px] tabular-nums text-zinc-500 dark:text-zinc-400"},ag={key:1,class:"flex items-center justify-between gap-3 py-1.5"},og={class:"text-xs text-zinc-500 dark:text-zinc-400"},cg={class:"text-xs tabular-nums text-zinc-700 dark:text-zinc-300"},lg={key:2,class:"flex flex-col gap-1.5 pt-1"},ug={key:0,class:"flex items-start gap-2 rounded-md border border-zinc-200 bg-zinc-50 px-3 py-2 text-xs leading-4 text-zinc-600 dark:border-zinc-800 dark:bg-white/[0.03] dark:text-zinc-300"},dg={key:1,class:"flex items-start gap-2 rounded-md border border-zinc-200 bg-zinc-50 px-3 py-2 text-xs leading-4 text-zinc-600 dark:border-zinc-800 dark:bg-white/[0.03] dark:text-zinc-300"},fg={key:2,class:"flex items-start gap-2 rounded-md border border-zinc-200 bg-zinc-50 px-3 py-2 text-xs leading-4 text-zinc-600 dark:border-zinc-800 dark:bg-white/[0.03] dark:text-zinc-300"},hg={key:3,class:"mt-1 flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs leading-4 text-red-700 dark:border-red-500/20 dark:bg-red-500/10 dark:text-red-300"},mg={key:4,class:"mt-1 flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs leading-4 text-red-700 dark:border-red-500/20 dark:bg-red-500/10 dark:text-red-300"},pg={key:5,class:"flex flex-col gap-2 pt-2"},gg=["aria-valuenow"],bg={class:"text-xs tabular-nums text-zinc-600 dark:text-zinc-300"},kg={class:"text-[11px] leading-4 text-zinc-400 dark:text-zinc-500"},yg={key:6,class:"flex flex-col gap-1.5 py-1"},wg={class:"flex items-center gap-2 text-[13px] font-medium text-zinc-900 dark:text-zinc-100"},xg={class:"flex items-center justify-between gap-3 py-1.5"},Tg={class:"text-xs text-zinc-500 dark:text-zinc-400"},_g={class:"text-xs tabular-nums text-zinc-700 dark:text-zinc-300"},Sg={class:"flex items-center justify-between gap-3 py-0.5"},vg={class:"text-xs text-zinc-500 dark:text-zinc-400"},Pg={class:"text-xs tabular-nums text-zinc-700 dark:text-zinc-300"},Cg={key:7,class:"mt-1 flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs leading-4 text-red-700 dark:border-red-500/20 dark:bg-red-500/10 dark:text-red-300"},Ig={class:"flex items-center justify-end gap-1.5 border-t border-zinc-200 px-4 py-3 dark:border-zinc-800"},Eg=["disabled","aria-busy"],Ag=Fr({__name:"StudioExportDialog",props:{expo:{},studio:{}},emits:["close"],setup(r,{emit:e}){const t=r,i=e,{t:n}=Rr(),{expo:s}=t,a=pe(()=>t.studio.project.value.fps),o=pe(()=>Ii(t.studio.project.value)),c=pe(()=>[{value:"source",label:n("export_res_source")},{value:1080,label:"1080p"},{value:720,label:"720p"}]),l=pe(()=>{var p;const m=((p=s.result.value)==null?void 0:p.blob.size)??0;return m>=1024*1024?`${(m/1024/1024).toFixed(1)} MB`:m>=1024?`${(m/1024).toFixed(0)} KB`:`${m} B`}),u=ke(null);function d(){s.exporting.value||i("close")}function f(){s.exporting.value||i("close")}return dn(()=>{var m;return(m=u.value)==null?void 0:m.focus()}),(m,p)=>(Z(),bt(ol,{to:"body"},[L("div",{class:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4",onPointerdown:nt(d,["self"])},[L("div",{ref_key:"dialogEl",ref:u,role:"dialog","aria-modal":"true","aria-label":w(n)("export_title"),tabindex:"-1",class:"w-full max-w-sm rounded-xl border border-zinc-200 bg-white shadow-2xl dark:border-zinc-800 dark:bg-zinc-950",onKeydown:cs(f,["esc"])},[L("div",Gp,[L("div",Xp,[be(w(vl),{class:"h-3.5 w-3.5 text-zinc-500 dark:text-zinc-400"}
482),L("h2",Qp,Y(w(n)("export_title")),1)]),L("button",{type:"button",disabled:w(s).exporting.value,"aria-label":w(n)("export_close"),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-400 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:p[0]||(p[0]=h=>i("close"))},[be(w(fn),{class:"h-4 w-4"})],8,Yp)]),L("div",Zp,[w(s).state.value==="checking"?(Z(),re("div",Jp,[be(w(yo),{class:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none"}),$e(" "+Y(w(n)("export_checking")),1)])):w(s).state.value==="ready"||w(s).state.value==="blocked"||w(s).state.value==="error"||w(s).state.value==="done"||w(s).state.value==="exporting"?(Z(),re(Qe,{key:1},[w(s).state.value!=="done"?(Z(),re("div",eg,[L("span",tg,Y(w(n)("export_resolution")),1),L("div",rg,[L("div",ig,[(Z(!0),re(Qe,null,Xt(w(c),h=>(Z(),re("button",{key:h.value,type:"button","aria-pressed":w(s).resolution.value===h.value,disabled:w(s).exporting.value,class:qt(["rounded px-2.5 text-xs font-medium transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none",w(s).resolution.value===h.value?"bg-white text-zinc-900 shadow-sm dark:bg-zinc-800 dark:text-zinc-100":"text-zinc-500 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"]),onClick:b=>w(s).resolution.value=h.value},Y(h.label),11,ng))),128))]),L("span",sg,Y(w(s).outputSize.value.width)+" à "+Y(w(s).outputSize.value.height),1)])])):Ce("",!0),w(s).state.value!=="done"?(Z(),re("div",ag,[L("span",og,Y(w(n)("export_duration")),1),L("span",cg,Y(w(st)(w(o),w(a))),1)])):Ce("",!0),w(s).state.value!=="done"?(Z(),re("div",lg,[w(s).mixedAspect.value?(Z(),re("p",ug,[be(w(Hi),{class:"mt-px h-3.5 w-3.5 flex-shrink-0 text-zinc-400"}),$e(Y(w(n)("export_mixed_aspect")),1)])):Ce("",!0),w(s).noClipAudio.value?(Z(),re("p",dg,[be(w(Hi),{class:"mt-px h-3.5 w-3.5 flex-shrink-0 text-zinc-400"}),$e(Y(w(n)("export_no_audio")),1)])):w(s).state.value!=="checking"&&!w(s).capabilities.value.audio&&w(s).state.value!=="blocked"?(Z(),re("p",fg,[be(w(Hi),{class:"mt-px h-3.5 w-3.5 flex-shrink-0 text-zinc-400"}),$e(Y(w(n)("export_no_audio_encoder")),1)])):Ce("",!0)])):Ce("",!0),w(s).state.value==="blocked"&&w(s).blockReason.value==="too_long"?(Z(),re("p",hg,[be(w(Wi),{class:"mt-px h-3.5 w-3.5 flex-shrink-0"}),$e(Y(w(n)("export_too_long")),1)])):w(s).state.value==="blocked"?(Z(),re("p",mg,[be(w(Wi),{class:"mt-px h-3.5 w-3.5 flex-shrink-0"}),$e(Y(w(n)("export_unsupported")),1)])):Ce("",!0),w(s).state.value==="exporting"?(Z(),re("div",pg,[L("div",{class:"h-1 w-full overflow-hidden rounded-full bg-zinc-200 dark:bg-zinc-800",role:"progressbar","aria-valuenow":Math.round(w(s).progress.value*100),"aria-valuemin":"0","aria-valuemax":"100"},[L("div",{class:"h-full w-full origin-left rounded-full bg-zinc-900 transition-transform duration-100 dark:bg-white",style:Dt({transform:`scaleX(${w(s).progress.value})`})},null,4)],8,gg),L("p",bg,Y(w(n)("export_progress",{pct:Math.round(w(s).progress.value*100)})),1),L("p",kg,Y(w(n)("export_keep_open")),1)])):Ce("",!0),w(s).state.value==="done"&&w(s).result.value?(Z(),re("div",yg,[L("p",wg,[be(w(_l),{class:"h-4 w-4 text-zinc-900 dark:text-zinc-100"}),$e(Y(w(n)("export_done")),1)]),L("div",xg,[L("span",Tg,Y(w(n)("export_file_size")),1),L("span",_g,Y(w(l)),1)]),L("div",Sg,[L("span",vg,Y(w(n)("export_duration")),1),L("span",Pg,Y(w(st)(w(s).result.value.duration,w(a)))+" · "+Y(w(s).result.value.width)+" à "+Y(w(s).result.value.height),1)])])):Ce("",!0),w(s).state.value==="error"?(Z(),re("p",Cg,[be(w(Wi),{class:"mt-px h-3.5 w-3.5 flex-shrink-0"}),$e(Y(w(n)("export_failed")),1)])):Ce("",!0)],64)):Ce("",!0)]),L("div",Ig,[w(s).state.value==="exporting"?(Z(),re("button",{key:0,type:"button",class:"inline-flex h-7 items-center justify-center rounded-md border border-zinc-200 bg-white px-3 text-xs font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800",onClick:p[1]||(p[1]=(...h)=>w(s).cancel&&w(s).cancel(...h))}
482,Y(w(n)("export_cancel")),1)):w(s).state.value==="done"?(Z(),re(Qe,{key:1},[L("button",{type:"button",class:"inline-flex h-7 items-center justify-center rounded-md border border-zinc-200 bg-white px-3 text-xs font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800",onClick:p[2]||(p[2]=h=>i("close"))},Y(w(n)("export_continue")),1),L("button",{type:"button",class:"inline-flex h-7 items-center justify-center rounded-md bg-zinc-900 px-3 text-xs font-medium text-white transition-colors duration-150 hover:bg-zinc-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:bg-white dark:text-zinc-900 dark:hover:bg-zinc-200",onClick:p[3]||(p[3]=(...h)=>w(s).download&&w(s).download(...h))},Y(w(n)("export_download")),1)],64)):(Z(),re(Qe,{key:2},[w(s).state.value==="error"?(Z(),re("button",{key:0,type:"button",class:"inline-flex h-7 items-center justify-center rounded-md border border-zinc-200 bg-white px-3 text-xs font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800",onClick:p[4]||(p[4]=h=>i("close"))},Y(w(n)("export_close")),1)):Ce("",!0),L("button",{type:"button",disabled:w(s).state.value!=="ready","aria-busy":w(s).state.value==="exporting",class:"inline-flex h-7 items-center justify-center rounded-md bg-zinc-900 px-3 text-xs font-medium text-white transition-colors duration-150 hover:bg-zinc-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:bg-white dark:text-zinc-900 dark:hover:bg-zinc-200",onClick:p[5]||(p[5]=(...h)=>w(s).start&&w(s).start(...h))},Y(w(s).state.value==="error"?w(n)("export_retry"):w(n)("export_start")),9,Eg)],64))])],40,Kp)],32)]))}}),Vi=30,zg=120,un=48e3,na=2,Fg=1e-6,Li=r=>Math.max(2,Math.round(r)-Math.round(r)%2);function rl(r,e){const t=r.clips[0],i=t?r.sources.find(s=>s.id===t.sourceId):void 0;if(!(i!=null&&i.width)||!(i!=null&&i.height))return{width:0,height:0};if(e==="source")return{width:Li(i.width),height:Li(i.height)};const n=e/Math.min(i.width,i.height);return{width:Li(i.width*n),height:Li(i.height*n)}}async function il(r,e){const[t,i]=await Promise.all([gh("avc",{width:r,height:e,bitrate:Ac}).catch(()=>!1),bh("aac",{numberOfChannels:na,sampleRate:un,bitrate:Ec}).catch(()=>!1)]);return{video:t,audio:i}}function mo(){return new DOMException("Export aborted","AbortError")}async function Bg(r,e,t){const i=Zt(r),n=new OfflineAudioContext(na,Math.ceil(t*un),un);let s=0;for(let a=0;a<r.clips.length;a++){const o=r.clips[a],c=r.sources.find(d=>d.id===o.sourceId);if(!(c!=null&&c.hasAudio))continue;const l=await e(o.sourceId).getPrimaryAudioTrack();if(!l)continue;const u=new Ih(l);for await(const d of u.buffers(o.in,o.out)){const f=n.createBufferSource();f.buffer=d.buffer,f.connect(n.destination);const m=i[a]+Math.max(0,d.timestamp-o.in),p=Math.max(0,o.in-d.timestamp),h=d.buffer.duration-p;h<=0||(f.start(Math.min(m,t),p,Math.min(h,t-m)),s++)}}return s?n.startRendering():null}async function Rg(r,e,t){var b,y,x,T,P;const{width:i,height:n}=rl(r,t.resolution),s=Ii(r);if(!i||!n||s<=0)throw new Error("Nothing to export");const a=await il(i,n);if(!a.video)throw new Error("No usable H.264 video encoder");const o=Math.max(1,Math.round(s*Vi)),c=new OffscreenCanvas(i,n),l=c.getContext("2d"),u=new ip(c,{codec:"avc",bitrate:Ac}),d=r.clips.some(_=>{var S;return(S=r.sources.find(I=>I.id===_.sourceId))==null?void 0:S.hasAudio});let f=null,m=null;d&&a.audio&&(f=await Bg(r,e,s),f&&(m=new sp({codec:"aac",bitrate:Ec,numberOfChannels:na,sampleRate:un})));const p=new dp({format:new Jc({fastStart:"in-memory"}),target:new Ki});p.addVideoTrack(u),m&&p.addAudioTrack(m),await p.start();try{const _=Zt(r);let S=0;for(let I=0;I<r.clips.length&&S<o;I++){const C=r.clips[I],v=await e(C.sourceId).getPrimaryVideoTrack();if(!v)continue;const A=_[I],H=A+ft(C),M=Math.min(Math.round(H*Vi),o),D=new Dc(v),$=D.samples(C.in,C.out);let B=await D.getSample(C.in),O=await $.next();try{for(;S<M;S++){if((b=t.signal)!=null&&b.aborted)throw mo();const X=S/Vi,ae=C.in+(X-A);for(;!O.done&&O.value&&O.value.timestamp<=ae+Fg;)B==null||B.close(),B=O.value,O=await $.next();l.fillStyle="#000",l.fillRect(0,0,i,n),B==null||B.drawWithFit(l,{fit:"contain"}),await u.add(X,1/Vi),(y=t.onProgress)==null||y.call(t,{frame:S+1,totalFrames:o})}}finally{B==null||B.close(),O.done||(x=O.value)==null||x.close(),await((T=$.return)==null?void 0:T.call($))}}if((P=t.signal)!=null&&P.aborted)throw mo();m&&f&&await m.add(f),await p.finalize()}catch(_){throw await p.cancel().catch(()=>{}),_}
482const h=p.target.buffer;if(!h)throw new Error("Export produced no output");return{blob:new Blob([h],{type:"video/mp4"}),width:i,height:n,duration:s,hasAudio:!!m}}function Mg(){const r=new Date,e=t=>String(t).padStart(2,"0");return`studio-${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}-${e(r.getHours())}${e(r.getMinutes())}.mp4`}function Og(r,e){const t=ke("idle"),i=ke(null),n=ke({video:!1,audio:!1}),s=ke(0),a=ke("source"),o=ke(null),c=ke(null),l=pe(()=>t.value==="exporting"),u=pe(()=>rl(r.project.value,a.value)),d=pe(()=>{const S=new Set;for(const I of r.project.value.clips){const C=r.project.value.sources.find(v=>v.id===I.sourceId);C!=null&&C.width&&(C!=null&&C.height)&&S.add(Math.round(C.width/C.height*1e3))}return S.size>1}),f=pe(()=>!r.project.value.clips.some(S=>{var I;return(I=r.project.value.sources.find(C=>C.id===S.sourceId))==null?void 0:I.hasAudio}));let m=null;function p(S){const I=r.sourceFiles.get(S),C=r.project.value.sources.find(v=>v.id===S);if(!C)throw new Error(`Unknown source ${S}`);return e.inputFor(S,I?{file:I}:{url:C.url})}function h(){c.value&&URL.revokeObjectURL(c.value),c.value=null,o.value=null}async function b(){h(),i.value=null,t.value="checking";const S=Ii(r.project.value);if(!r.project.value.clips.length){i.value="empty",t.value="blocked";return}if(S>zg){i.value="too_long",t.value="blocked";return}const I=u.value;if(n.value=await il(I.width,I.height),!n.value.video){i.value="unsupported",t.value="blocked";return}t.value="ready"}const y=S=>{S.preventDefault(),S.returnValue=""};async function x(){if(t.value!=="exporting"){m=new AbortController,h(),s.value=0,t.value="exporting",window.addEventListener("beforeunload",y);try{const S=await Rg(r.project.value,p,{resolution:a.value,signal:m.signal,onProgress:I=>{s.value=I.frame/I.totalFrames}});o.value=S,c.value=URL.createObjectURL(S.blob),t.value="done"}catch(S){t.value=S instanceof DOMException&&S.name==="AbortError"?"ready":"error"}finally{window.removeEventListener("beforeunload",y),m=null}}}function T(){m==null||m.abort()}function P(){if(!c.value)return;const S=document.createElement("a");S.href=c.value,S.download=Mg(),S.click()}function _(){t.value!=="exporting"&&(h(),t.value="idle",i.value=null)}return Br(()=>{T(),h(),window.removeEventListener("beforeunload",y)}),{state:t,blockReason:i,capabilities:n,progress:s,resolution:a,result:o,resultUrl:c,exporting:l,outputSize:u,mixedAspect:d,noClipAudio:f,prepare:b,start:x,cancel:T,download:P,close:_}}function Dg(r){return{url:ml(r),editable:hl(r)||r.startsWith("/")}}function Ng(){return pl()}function Ug(r=30){return gl(r)}function Vg(){return`${kl()}__video_studio_project_v1`}function Lg(r){bl(r)}function Wg(r){const e=r.videoWidth,t=r.videoHeight;if(!e||!t)return Promise.reject(new Error("no video frame"));const i=document.createElement("canvas");i.width=e,i.height=t;const n=i.getContext("2d");return n?(n.drawImage(r,0,0,e,t),new Promise((s,a)=>{i.toBlob(o=>o?s(o):a(new Error("encode failed")),"image/png")})):Promise.reject(new Error("no 2d context"))}async function Hg(r){var o;const e=`frame_${Date.now()}.png`,t=new File([r],e,{type:"image/png"}),i=new FormData;i.append("file",t),i.append("fileName",e);const s=await(await fetch("/api/common/image-upload",{method:"POST",body:i})).json(),a=(o=s.data)==null?void 0:o.downloadUrl;if(!s.success||!a)throw new Error(s.msg||"upload failed");return a}const qg={key:1,class:"video-studio flex h-full min-h-0 flex-1 flex-col overflow-hidden bg-white dark:bg-zinc-950"},$g={class:"flex h-11 flex-shrink-0 items-center gap-2 border-b border-zinc-200 px-3 dark:border-zinc-800"},jg=["aria-label"],Kg={class:"text-[13px] font-semibold text-zinc-950 dark:text-zinc-100"},Gg={class:"text-xs tabular-nums text-zinc-500 dark:text-zinc-400"},Xg=["disabled"],Qg=["disabled","aria-label"],Yg=["disabled","aria-label"],Zg=["disabled"],Jg={class:"grid min-h-0 flex-1 grid-cols-[15rem_minmax(0,1fr)_18rem]"},e0={class:"flex min-h-0 min-w-0 flex-col border-r border-zinc-200 dark:border-zinc-800"},t0={class:"flex h-9 flex-shrink-0 items-center border-b border-zinc-200 px-3 dark:border-zinc-800"},r0={class:"text-xs font-medium text-zinc-500 dark:text-zinc-400"},i0={class:"min-h-0 flex-1 overflow-y-auto px-2 py-2"},n0={key:0,role:"status",class:"mb-2 flex items-start gap-2 rounded-md border border-zinc-200 bg-zinc-50 px-3 py-2 text-xs leading-4 text-zinc-600 dark:border-zinc-800 dark:bg-white/[0.03] dark:text-zinc-300"},s0={class:"min-w-0 flex-1"},a0=["aria-label"],o0={key:0},c0={class:"px-2 pb-1 pt-1 text-xs font-medium text-zinc-500 dark:text-zinc-400"},l0={class:"px-2 pb-1 pt-2 text-xs font-medium text-zinc-500 dark:text-zinc-400"},u0={key:0,class:"px-2 py-1 text-[11px] leading-4 text-zinc-400 dark:text-zinc-500"},d0={key:1},f0={class:"px-2 pb-1 pt-2 text-xs font-medium text-zinc-500 dark:text-zinc-400"},h0={key:2,class:"flex flex-col items-center px-4 py-6 text-center"},m0={class:"mt-2 text-[13px] font-medium text-zinc-900 dark:text-zinc-100"},p0={class:"mt-1 text-xs leading-4 text-zinc-500 dark:text-zinc-400"},g0={class:"flex-shrink-0 p-3"},b0={class:"text-xs font-medium text-zinc-700 dark:text-zinc-300"},k0={class:"flex min-h-0 min-w-0 flex-col"},y0={class:"flex min-h-0 flex-1 items-center justify-center p-3"},w0={class:"flex h-full w-full items-center justify-center overflow-hidden rounded-lg bg-zinc-950 p-3"},x0={key:1,class:"flex flex-col items-center px-6 text-center"},T0={class:"mt-2 text-xs text-zinc-500"},_0={class:"flex h-9 flex-shrink-0 items-center gap-1 px-3 pb-1"},S0=["disabled","aria-label"],v0=["disabled","aria-label"],P0=["disabled","aria-label"],C0={class:"ml-2 text-xs tabular-nums text-zinc-500 dark:text-zinc-400"},I0={class:"flex min-h-0 min-w-0 flex-col border-l border-zinc-200 dark:border-zinc-800"},E0={class:"flex h-9 flex-shrink-0 items-center border-b border-zinc-200 px-3 dark:border-zinc-800"},A0={class:"text-xs font-medium text-zinc-500 dark:text-zinc-400"},z0={key:0,class:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 py-3"},F0={class:"text-[12.5px] font-medium text-zinc-900 dark:text-zinc-100"},B0={key:0},R0={class:"text-xs font-medium text-zinc-500 dark:text-zinc-400"},M0={class:"mt-1 line-clamp-3 text-xs leading-4 text-zinc-700 dark:text-zinc-300"},O0={key:1},D0={class:"text-xs font-medium text-zinc-500 dark:text-zinc-400"},N0={class:"mt-1 text-xs text-zinc-700 dark:text-zinc-300"},U0={class:"flex items-center justify-between gap-3 py-1.5"},V0={class:"text-xs font-medium text-zinc-500 dark:text-zinc-400"},L0={class:"text-xs tabular-nums text-zinc-700 dark:text-zinc-300"},W0={class:"mt-auto flex flex-col gap-1.5 pt-3"},H0=["disabled"],q0=["disabled"],$0={key:1,class:"flex min-h-0 flex-1 items-center justify-center px-4 text-center"},j0={class:"text-xs leading-4 text-zinc-500 dark:text-zinc-400"},K0={key:2,class:"flex flex-shrink-0 flex-col gap-1.5 border-t border-zinc-200 px-3 py-2.5 dark:border-zinc-800"}
482,G0=["disabled","aria-busy"],X0={key:0,class:"text-[11px] leading-4 text-zinc-400 dark:text-zinc-500"},Q0={key:1,role:"alert",class:"flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs leading-4 text-red-700 dark:border-red-500/20 dark:bg-red-500/10 dark:text-red-300"},Y0={role:"status","aria-live":"polite",class:"sr-only"},Z0=Fr({__name:"VideoStudio",props:{studio:{},playback:{},thumbs:{},returnPath:{},localClipsRemoved:{type:Boolean}},setup(r){const e=r,{t}=Rr(),{studio:i,playback:n,thumbs:s}=e,a=cl("(max-width: 1023px)",{ssrWidth:1024}),o=pe(()=>i.project.value.fps),c=pe(()=>st(n.total.value,o.value)),l=pe(()=>i.project.value.clips.length>0),u=pe(()=>i.project.value.sources.length>0),d=te=>pe(()=>te.value.map(J=>i.project.value.sources.find(Te=>Te.id===J)).filter(J=>!!J)),f=pe(()=>i.groups.value.handoff),m=pe(()=>i.groups.value.recent.slice(0,12)),p=pe(()=>i.groups.value.local),h=d(f),b=d(m),y=d(p),x=ke(null),T=Og(i,s),P=ke(!1),_=ke(null),S=ke(""),I=ke(!1);Gr(()=>T.state.value,te=>{te==="done"?S.value=t("export_done"):te==="error"&&(S.value=t("export_failed"))});function C(){P.value=!0,T.prepare()}function v(){T.close(),P.value=!1,os(()=>{var te;return(te=_.value)==null?void 0:te.focus()})}function A(){T.exporting.value||i.newProject()}const H=pe(()=>!!Iu(i.project.value,n.currentTime.value)),M=ke(!1),D=ke(!1);async function $(){if(!e.returnPath||M.value||T.exporting.value||!H.value)return;const te=n.activeVideoEl();if(!te){D.value=!0;return}n.pause(),M.value=!0,D.value=!1;try{const J=await Wg(te),Te=await Hg(J);Lg(Te),await ll(e.returnPath)}catch{D.value=!0,M.value=!1}}const B=pe(()=>Zt(i.project.value)),O=pe(()=>i.project.value.clips.find(te=>te.id===i.selectedClipId.value)??null),X=pe(()=>O.value?i.project.value.sources.find(te=>te.id===O.value.sourceId)??null:null),ae=pe(()=>{const te=O.value;if(!te)return!1;const J=i.project.value.clips.indexOf(te),Te=Sr(i.project.value,n.currentTime.value);if(!Te||Te.clipIndex!==J)return!1;const ge=Zr(o.value),ce=n.currentTime.value,k=B.value[J];return ce-k>=ge-1e-9&&k+ft(te)-ce>=ge-1e-9}),ve=pe(()=>{const te=Sr(i.project.value,n.currentTime.value);if(!te)return!1;const J=i.project.value.clips[te.clipIndex],Te=B.value[te.clipIndex],ge=Zr(o.value),ce=n.currentTime.value;return ce-Te>=ge-1e-9&&Te+ft(J)-ce>=ge-1e-9});function Ie(te){T.exporting.value||i.insertSource(te)}function ct(te){T.exporting.value||(s.forget(te),i.removeSource(te))}const de=ke(null),qe=ke(!1);function xt(te){for(const J of te){const Te=i.addSource({file:J,label:J.name,origin:"local-file",group:"local"});s.ensure(Te.id,{file:J})}}function Ft(te){const J=te.target;xt(J.files??[]),J.value=""}function Bt(te){var Te;qe.value=!1;const J=[...((Te=te.dataTransfer)==null?void 0:Te.files)??[]].filter(ge=>ge.type.startsWith("video/"));xt(J)}function Rt(){const te=ul(),J=dl();window.history.length>1?te.back():te.push(J("/dashboard"))}function Mt(te){const J=te;if(!J)return!1;const Te=J.tagName;return Te==="INPUT"||Te==="TEXTAREA"||Te==="SELECT"||J.isContentEditable}function pt(te){var ce,k;if(te.isComposing||Mt(te.target))return;const J=T.exporting.value,Te=te.metaKey||te.ctrlKey,ge=te.key;if(Te&&ge.toLowerCase()==="z"){if(J)return;te.preventDefault(),te.shiftKey?i.redo():i.undo();return}if(Te&&ge.toLowerCase()==="y"){if(J)return;te.preventDefault(),i.redo();return}if(!Te)if(te.code==="Space")te.preventDefault(),n.toggle();else if(ge==="ArrowLeft"||ge==="ArrowRight"){if(J&&te.altKey)return;te.preventDefault();const N=ge==="ArrowLeft"?-1:1;if(te.altKey){const E=i.project.value.clips.findIndex(F=>F.id===i.selectedClipId.value);E>=0&&i.moveClip(i.selectedClipId.value,E+N)}else te.shiftKey?n.seek(n.currentTime.value+N):n.step(N)}else if(ge==="Delete"||ge==="Backspace"){const N=i.selectedClipId.value;if(!N||J)return;te.preventDefault(),i.removeClip(N)}else if(ge.toLowerCase()==="s"){if(!ae.value&&!ve.value||J)return;te.preventDefault(),i.splitAt(n.currentTime.value)}else if(ge.toLowerCase()==="i"||ge.toLowerCase()==="o"){if(J)return;const N=O.value;if(!N)return;const E=i.project.value.clips.indexOf(N),F=Sr(i.project.value,n.currentTime.value);if(!F||F.clipIndex!==E)return;te.preventDefault(),i.trimClip(N.id,ge.toLowerCase()==="i"?"in":"out",F.sourceTime)}else ge==="+"||ge==="="?(te.preventDefault(),(ce=x.value)==null||ce.zoomIn()):(ge==="-"||ge==="_")&&(te.preventDefault(),(k=x.value)==null||k.zoomOut())}return dn(()=>window.addEventListener("keydown",pt)),Br(()=>window.removeEventListener("keydown",pt)),(te,J)=>{const Te=fu,ge=Pu;return w(a)?(Z(),bt(Te,{key:0})):(Z(),re("div",qg,[L("header",$g,[L("button",{type:"button","aria-label":w(t)("back"),
482class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-400 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:Rt},[be(w(xl),{class:"h-4 w-4"})],8,jg),L("h1",Kg,Y(w(t)("studio_title")),1),L("span",Gg,Y(w(c)),1),J[14]||(J[14]=L("div",{class:"flex-1"},null,-1)),L("button",{type:"button",disabled:w(T).exporting.value||!w(u)&&!w(l),class:"inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs font-medium text-zinc-500 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:A},[be(w(Pl),{class:"h-3.5 w-3.5"}),$e(" "+Y(w(t)("new_project")),1)],8,Xg),L("button",{type:"button",disabled:!w(i).canUndo.value,"aria-label":w(t)("undo"),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-400 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:J[0]||(J[0]=(...ce)=>w(i).undo&&w(i).undo(...ce))},[be(w(Nl),{class:"h-4 w-4"})],8,Qg),L("button",{type:"button",disabled:!w(i).canRedo.value,"aria-label":w(t)("redo"),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-400 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:J[1]||(J[1]=(...ce)=>w(i).redo&&w(i).redo(...ce))},[be(w(Bl),{class:"h-4 w-4"})],8,Yg),L("button",{ref_key:"exportBtnEl",ref:_,type:"button",disabled:!w(l)||w(T).exporting.value,class:"inline-flex h-8 items-center gap-1.5 rounded-md bg-zinc-900 px-3 text-xs font-medium text-white transition-colors duration-150 hover:bg-zinc-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:bg-white dark:text-zinc-900 dark:hover:bg-zinc-200 dark:focus-visible:ring-offset-zinc-950",onClick:C},Y(w(t)("export")),9,Zg)]),L("div",Jg,[L("aside",e0,[L("div",t0,[L("h2",r0,Y(w(t)("media_title")),1)]),L("div",i0,[r.localClipsRemoved&&!w(I)?(Z(),re("div",n0,[be(w(Hi),{class:"mt-px h-3.5 w-3.5 flex-shrink-0 text-zinc-400"}),L("span",s0,Y(w(t)("autosave_local_removed")),1),L("button",{type:"button","aria-label":w(t)("dismiss"),class:"-mr-1 inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded text-zinc-400 transition-colors duration-150 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:hover:text-zinc-100",onClick:J[2]||(J[2]=ce=>I.value=!0)},[be(w(fn),{class:"h-3.5 w-3.5"})],8,a0)])):Ce("",!0),w(u)?(Z(),re(Qe,{key:1},[w(h).length?(Z(),re("section",o0,[L("h3",c0,Y(w(t)("media_section_handoff")),1),(Z(!0),re(Qe,null,Xt(w(h),ce=>(Z(),bt(ge,{key:ce.id,source:ce,poster:w(s).posterOf(ce.id),loading:w(s).loadingOf(ce.id),onAdd:Ie,onRemove:ct},null,8,["source","poster","loading"]))),128))])):Ce("",!0),L("section",null,[L("h3",l0,Y(w(t)("media_section_recent")),1),(Z(!0),re(Qe,null,Xt(w(b),ce=>(Z(),bt(ge,{key:ce.id,source:ce,poster:w(s).posterOf(ce.id),loading:w(s).loadingOf(ce.id),onAdd:Ie,onRemove:ct},null,8,["source","poster","loading"]))),128)),w(b).length?Ce("",!0):(Z(),re("p",u0,Y(w(t)("recent_empty")),1))]),w(y).length?(Z(),re("section",d0,[L("h3",f0,Y(w(t)("media_section_local")),1),(Z(!0),re(Qe,null,Xt(w(y),ce=>(Z(),bt(ge,{key:ce.id,source:ce,poster:w(s).posterOf(ce.id),loading:w(s).loadingOf(ce.id),removable:"",onAdd:Ie,onRemove:ct},null,8,["source","poster","loading"]))),128))])):Ce("",!0)],64)):(Z(),re("div",h0,[be(w(ko),{class:"h-5 w-5 text-zinc-400"}),L("p",m0,Y(w(t)("media_empty_title")),1),L("p",p0,Y(w(t)("media_empty_desc")),1
482)]))]),L("div",g0,[L("input",{ref_key:"fileInputEl",ref:de,type:"file",accept:"video/*",multiple:"",class:"hidden",onChange:Ft},null,544),L("button",{type:"button",class:qt(["flex w-full flex-col items-center gap-1.5 rounded-lg border border-dashed py-5 text-center transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none",w(qe)?"border-zinc-500 bg-zinc-100 dark:border-zinc-400 dark:bg-white/[0.08]":"border-zinc-300 hover:border-zinc-500 hover:bg-zinc-50 dark:border-zinc-700 dark:hover:border-zinc-500 dark:hover:bg-white/[0.06]"]),onClick:J[3]||(J[3]=ce=>{var k;return(k=w(de))==null?void 0:k.click()}),onDragenter:J[4]||(J[4]=nt(ce=>qe.value=!0,["prevent"])),onDragover:J[5]||(J[5]=nt(ce=>qe.value=!0,["prevent"])),onDragleave:J[6]||(J[6]=nt(ce=>qe.value=!1,["prevent"])),onDrop:nt(Bt,["prevent"])},[be(w(Ul),{class:"h-5 w-5 text-zinc-400"}),L("span",b0,Y(w(t)("media_add_local")),1)],34)])]),L("section",k0,[L("div",y0,[L("div",w0,[w(l)?(Z(),re(Qe,{key:0},Xt([0,1],ce=>L("video",{key:ce,ref_for:!0,ref:w(n).setVideoEl(ce),class:qt(["h-full w-full object-contain",w(n).activeSlot.value===ce?"":"hidden"]),playsinline:"",preload:"auto"},null,2)),64)):(Z(),re("div",x0,[be(w(Il),{class:"h-5 w-5 text-zinc-500"}),L("p",T0,Y(w(t)("viewer_empty")),1)]))])]),L("div",_0,[L("button",{type:"button",disabled:!w(l),"aria-label":w(n).playing.value?w(t)("pause"):w(t)("play"),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-600 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:text-zinc-300 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:J[7]||(J[7]=(...ce)=>w(n).toggle&&w(n).toggle(...ce))},[w(n).playing.value?(Z(),bt(w(Al),{key:0,class:"h-4 w-4"})):(Z(),bt(w(zl),{key:1,class:"h-4 w-4"}))],8,S0),L("button",{type:"button",disabled:!w(l),"aria-label":w(t)("prev_frame"),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-600 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:text-zinc-300 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:J[8]||(J[8]=ce=>w(n).step(-1))},[be(w(Ml),{class:"h-4 w-4"})],8,v0),L("button",{type:"button",disabled:!w(l),"aria-label":w(t)("next_frame"),class:"inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-600 transition-colors duration-150 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:text-zinc-300 dark:hover:bg-white/[0.06] dark:hover:text-zinc-100",onClick:J[9]||(J[9]=ce=>w(n).step(1))},[be(w(Ol),{class:"h-4 w-4"})],8,P0),L("span",C0,Y(w(st)(w(n).currentTime.value,w(o)))+" / "+Y(w(st)(w(n).total.value,w(o))),1)])]),L("aside",I0,[L("div",E0,[L("h2",A0,Y(w(t)("inspector_title")),1)]),w(O)&&w(X)?(Z(),re("div",z0,[L("div",null,[L("p",F0,Y(w(X).label),1)]),w(X).prompt?(Z(),re("div",B0,[L("p",R0,Y(w(t)("inspector_prompt")),1),L("p",M0,Y(w(X).prompt),1)])):Ce("",!0),w(X).model?(Z(),re("div",O0,[L("p",D0,Y(w(t)("inspector_model")),1),L("p",N0,Y(w(X).model),1)])):Ce("",!0),be(ho,{label:w(t)("inspector_in"),"model-value":w(O).in,fps:w(o),onCommit:J[10]||(J[10]=ce=>{w(T).exporting.value||w(i).trimClip(w(O).id,"in",ce)})},null,8,["label","model-value","fps"]),be(ho,{label:w(t)("inspector_out"),"model-value":w(O).out,fps:w(o),onCommit:J[11]||(J[11]=ce=>{w(T).exporting.value||w(i).trimClip(w(O).id,"out",ce)})},null,8,["label","model-value","fps"]),L("div",U0,[L("p",V0,Y(w(t)("inspector_duration")),1),L("p",L0,Y(w(st)(w(O).out-w(O).in,w(o))),1)]),L("div",W0,[L("button",{type:"button",disabled:!w(ae)||w(T).exporting.value,class:"inline-flex h-7 items-center justify-center rounded-md border border-zinc-200 bg-white px-3 text-xs font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800",onClick:J[12]||(J[12]=ce=>w(i).splitAt(w(n).currentTime.value))},Y(w(t)("split_at_playhead")),9,H0),L("button",{type:"button",disabled:w(T).exporting.value,class:"inline-flex h-7 items-center justify-center rounded-md px-3 text-xs font-medium text-zinc-500 transition-colors duration-150 hover:bg-red-50 hover:text-red-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 motion-reduce:transition-none dark:text-zinc-400 dark:hover:bg-red-500/10 dark:hover:text-red-400",onClick:J[13]||(J[13]=ce=>w(i).removeClip(w(O).id))},Y(w(t)("delete")),9,q0)])])):(Z(),re("div",$0,[L("p",j0,Y(w(t)("inspector_empty")),1)])),r.returnPath?(Z(),re("div",K0,[L("button",{type:"button",disabled:w(T).exporting.value||!w(H)||w(M),"aria-busy":w(M),class:"inline-flex h-7 items-center justify-center gap-1.5 rounded-md border border-zinc-200 bg-white px-3 text-xs font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 motion-reduce:transition-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800",onClick:$},[w(M)?(Z(),bt(w(yo),{key:0,class:"h-3.5 w-3.5 animate-spin motion-reduce:animate-none"})):(Z(),bt(w(Tl),{key:1,class:"h-3.5 w-3.5"})),$e(" "+Y(w(t)("use_frame")),1)],8,G0),w(M)?(Z(),re("p",X0,Y(w(t)("use_frame_uploading")),1)):Ce("",!0),w(D)?(Z(),re("p",Q0,[be(w(Wi),{class:"mt-px h-3.5 w-3.5 flex-shrink-0"}),$e(Y(w(t)("use_frame_failed")),1)])):Ce("",!0)])):Ce("",!0)])]),be(Wp,{ref_key:"timelineEl",ref:x,studio:w(i),playback:w(n),thumbs:w(s),"editing-disabled":w(T).exporting.value},null,8,["studio","playback","thumbs","editing-disabled"]),w(P)?(Z(),bt(Ag,{key:0,expo:w(T),studio:w(i),onClose:v},null,8,["expo","studio"])):Ce("",!0),L("div",Y0,Y(w(S)),1)]))}}}),J0=8*1024*1024;function eb(r){const e=r.originalUrl??r.url;return!e||e.startsWith("blob:")?null:e}function tb(r){const e=new Set,t=new Map,i=[];for(const o of r.sources){if(o.origin!=="generation")continue;const c=eb(o);!c||e.has(c)||(e.add(c),t.set(o.id,c),i.push({url:c,label:o.label,prompt:o.prompt,model:o.model,taskId:o.taskId}))}const n=r.clips.filter(o=>
482t.has(o.sourceId)).map(o=>({src:t.get(o.sourceId),in:o.in,out:o.out})),s=new Set(r.sources.filter(o=>o.origin==="local-file").map(o=>o.id)),a=r.clips.some(o=>s.has(o.sourceId));return{version:1,fps:r.fps,sources:i,clips:n,hadLocalClips:a}}function po(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0}function rb(r){if(!r||typeof r!="object")return null;const e=r;if(e.version!==1||e.fps!==30||!Array.isArray(e.sources)||!Array.isArray(e.clips))return null;for(const i of e.sources){if(!i||typeof i!="object")return null;const n=i;if(typeof n.url!="string"||!n.url||n.url.startsWith("blob:")||typeof n.label!="string")return null;for(const s of[n.prompt,n.model,n.taskId])if(s!==void 0&&typeof s!="string")return null}const t=new Set(e.sources.map(i=>i.url));for(const i of e.clips){if(!i||typeof i!="object")return null;const n=i;if(typeof n.src!="string"||!t.has(n.src)||!po(n.in)||!po(n.out)||n.out<=n.in)return null}return{version:1,fps:30,sources:e.sources,clips:e.clips,hadLocalClips:e.hadLocalClips===!0}}function ib(r){if(!r)return null;try{return rb(JSON.parse(r))}catch{return null}}const nb=500;function go(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function sb(r){function e(){return Vg()}function t(){const a=go();if(!a)return null;let o=null;try{o=a.getItem(e())}catch{return null}return ib(o)}function i(){const a=go();if(a)try{const o=JSON.stringify(tb(r.project.value));o.length<=J0&&a.setItem(e(),o)}catch{}}let n=0;const s=Gr(r.project,()=>{n&&window.clearTimeout(n),n=window.setTimeout(()=>{n=0,i()},nb)},{deep:!0});return Br(()=>{s(),n&&window.clearTimeout(n),i()}),{read:t,write:i}}const ss=.001;function ab(r){const e=[sa(null),sa(null)],t=()=>{s.value&&C()},i=B=>O=>{const X=e[B].value;X&&X.removeEventListener("ended",t);const ae=O??null;e[B].value=ae,ae&&ae.addEventListener("ended",t)},n=ke(0),s=ke(!1),a=ke(0),o=ke(0),c=pe(()=>Ii(r.value)),l=pe(()=>Zt(r.value)),u=pe(()=>r.value.fps),d=()=>r.value.clips,f=B=>r.value.sources.find(O=>O.id===B.sourceId);let m=0,p=0,h=0,b=!1;function y(){m&&cancelAnimationFrame(m);const B=e[a.value].value;p&&(B!=null&&B.cancelVideoFrameCallback)&&B.cancelVideoFrameCallback(p),h&&clearInterval(h),m=0,p=0,h=0}function x(){h||(h=window.setInterval(()=>{const B=d()[o.value],O=e[a.value].value;!B||!O||!s.value||(O.ended||O.currentTime>=B.out-ss)&&C()},120))}function T(){if(!s.value)return;const B=e[a.value].value;B&&(typeof B.requestVideoFrameCallback=="function"?p=B.requestVideoFrameCallback(()=>P()):m=requestAnimationFrame(()=>P()))}function P(){m=0,p=0;const B=d()[o.value],O=e[a.value].value;if(!(!B||!O)){if(n.value=l.value[o.value]+(O.currentTime-B.in),O.ended||O.currentTime>=B.out-ss){C();return}T()}}function _(B){const O=d()[B+1],X=e[1-a.value].value;if(!O||!X)return;const ae=f(O);if(ae){X.dataset.studioSrc!==ae.url&&(X.dataset.studioSrc=ae.url,X.src=ae.url,X.load());try{X.currentTime=O.in}catch{}}}async function S(B){B.muted=!1;try{await B.play()}catch{B.muted=!0;try{await B.play()}catch{s.value=!1}}}async function I(B,O,X){const ae=d()[B],ve=e[a.value].value;if(!ae||!ve){s.value=!1;return}const Ie=f(ae);if(!Ie){s.value=!1;return}o.value=B,ve.dataset.studioSrc!==Ie.url&&(ve.dataset.studioSrc=Ie.url,ve.src=Ie.url,ve.load());try{ve.currentTime=Math.min(Math.max(O,ae.in),ae.out)}catch{}n.value=l.value[B]+(Math.min(Math.max(O,ae.in),ae.out)-ae.in),_(B),X&&(s.value=!0,x(),await S(ve),T())}async function C(){if(!b){b=!0;try{const B=o.value+1;if(B>=d().length){s.value=!1,y(),n.value=c.value;return}a.value=1-a.value,await I(B,d()[B].in,!0)}finally{b=!1}}}async function v(){if(!d().length)return;if(n.value>=c.value-ss){a.value=0,await I(0,d()[0].in,!0);return}const B=Sr(r.value,n.value);B&&await I(B.clipIndex,B.sourceTime,!0)}function A(){var B;s.value=!1,y(),(B=e[a.value].value)==null||B.pause()}function H(){s.value?A():v()}async function M(B){if(!d().length){n.value=0;return}const O=xi(B,u.value),X=Math.min(Math.max(O,0),c.value),ae=Sr(r.value,X);ae&&await I(ae.clipIndex,ae.sourceTime,s.value)}async function D(B){A(),await M(n.value+B*Zr(u.value))}return Gr(()=>d().length,()=>{if(!d().length){A(),n.value=0,o.value=0;return}s.value||M(n.value)}),Br(()=>{A()}),{setVideoEl:i,currentTime:n,playing:s,activeSlot:a,clipIndex:o,total:c,activeVideoEl:()=>e[a.value].value,play:v,pause:A,toggle:H,seek:M,step:D}}function ob(r,e=100){let t=[],i=[],n=r;return{get present(){return n},get canUndo(){return t.length>0},get canRedo(){return i.length>0},push(s){s!==n&&(t.push(n),t.length>e&&t.shift(),n=s,i=[])},undo(){t.length&&(i.unshift(n),n=t.pop())},redo(){i.length&&(t.push(n),n=i.shift())}}}
482class it extends Error{constructor(e,t){super(t??e),this.name="StudioProbeError",this.code=e}}const Is=200*1024*1024;async function Es(r){try{const e=await r.getPrimaryVideoTrack();if(!e)throw new it("no_video_track");if(!await e.canDecode().catch(()=>!1))throw new it("not_decodable");const[i,n,s,a]=await Promise.all([r.computeDuration(),e.getDisplayWidth(),e.getDisplayHeight(),r.getAudioTracks()]);if(!Number.isFinite(i)||i<=0)throw new it("not_decodable");let o;try{const c=await e.computePacketStats(100);c.averagePacketRate>0&&(o=c.averagePacketRate)}catch{}return{duration:i,width:n,height:s,fps:o,hasAudio:a.length>0}}catch(e){throw e instanceof it?e:new it("not_decodable",e instanceof Error?e.message:String(e))}finally{r.dispose()}}async function cb(r){try{return await Es(new zr({formats:cn,source:new Sn(r)}))}catch(t){if(t instanceof it&&t.code!=="not_decodable")throw t}let e;try{const t=await fetch(r);if(!t.ok)throw new Error(`HTTP ${t.status}`);if(Number(t.headers.get("content-length")||0)>Is)throw new it("too_large");e=await t.blob()}catch(t){throw t instanceof it?t:new it("network",t instanceof Error?t.message:String(t))}if(e.size>Is)throw new it("too_large");return Es(new zr({formats:cn,source:new Ys(e)}))}async function lb(r){if(r.size>Is)throw new it("too_large");return Es(new zr({formats:cn,source:new Ys(r)}))}const ub=()=>{var r,e;return((e=(r=globalThis.crypto)==null?void 0:r.randomUUID)==null?void 0:e.call(r))??`src-${Math.random().toString(36).slice(2,10)}`},db=()=>`clip-${Math.random().toString(36).slice(2,10)}`,bo=()=>({version:1,sources:[],clips:[],fps:30});function fb(){const r=ke(bo()),e=ob(r.value),t=ke(null),i=ke({handoff:[],recent:[],local:[]}),n=new Set,s=new Map,a=pe(()=>(r.value,e.canUndo)),o=pe(()=>(r.value,e.canRedo));function c(D){D!==r.value&&(e.push(D),r.value=e.present)}function l(){e.undo(),r.value=e.present}function u(){e.redo(),r.value=e.present}function d(D){r.value={...r.value,sources:D(r.value.sources)}}function f(D,$){d(B=>B.map(O=>O.id===D?{...O,...$}:O))}function m(D){let $="";const B={id:$=ub(),url:D.url??"",originalUrl:D.origin==="generation"?D.url:void 0,origin:D.origin,label:D.label,prompt:D.prompt,model:D.model,taskId:D.taskId,duration:0,width:0,height:0,hasAudio:!1,status:"probing"};if(D.file)B.url=URL.createObjectURL(D.file),n.add(B.url),s.set(B.id,D.file);else if(D.origin==="generation"){const O=Dg(D.url??"");B.url=O.url,O.editable||(B.status="unsupported",B.error="origin")}return d(O=>[...O,B]),i.value[D.group].push(B.id),B.status==="probing"?((D.file?lb(D.file):cb(B.url)).then(X=>f(B.id,{status:"ready",...X})).catch(X=>f(B.id,{status:X instanceof it&&X.code==="network"?"error":"unsupported",error:X instanceof it?X.code:"network"})),{...B,id:$}):B}async function p(D){for(let $=0;$<1200;$++){const B=r.value.sources.find(O=>O.id===D);if(!B)return null;if(B.status!=="probing")return B;await new Promise(O=>setTimeout(O,50))}return null}function h(D){const $=r.value.sources.find(X=>X.id===D);if(!$)return;$.url.startsWith("blob:")&&(URL.revokeObjectURL($.url),n.delete($.url)),s.delete(D);for(const X of Object.values(i.value)){const ae=X.indexOf(D);ae>=0&&X.splice(ae,1)}const B=new Set(r.value.clips.filter(X=>X.sourceId===D).map(X=>X.id)),O={...r.value,sources:r.value.sources.filter(X=>X.id!==D),clips:r.value.clips.filter(X=>!B.has(X.id))};c(O),t.value&&B.has(t.value)&&(t.value=null)}function b(D,$){c(Eu(r.value,D,$))}function y(D){const $=[...r.value.clips];for(const B of D){const O=r.value.sources.find(ve=>ve.id===B.sourceId);if(!O||O.status!=="ready")continue;const X=Math.max(xi(B.in,r.value.fps),0),ae=Math.min(xi(B.out,r.value.fps),As(O.duration,r.value.fps));ae<=X||$.push({id:db(),sourceId:B.sourceId,in:X,out:ae})}$.length!==r.value.clips.length&&c({...r.value,clips:$})}function x(){!r.value.sources.length&&!r.value.clips.length||(c(bo()),t.value=null)}function T(D){c(Fu(r.value,D)),t.value===D&&(t.value=null)}function P(D,$,B){c(To(r.value,D,$,B))}function _(D){c(Au(r.value,D))}function S(D,$){c(zu(r.value,D,$))}let I=null;function C(){I||(I=r.value)}function v(D){I&&(r.value=D)}function A(){const D=I;I=null,D&&r.value!==D&&(e.push(r.value),r.value=e.present)}
482function H(){I&&(r.value=I,I=null)}function M(D){t.value=D}return Br(()=>{for(const D of n)URL.revokeObjectURL(D);n.clear()}),{project:r,selectedClipId:t,groups:i,sourceFiles:s,canUndo:a,canRedo:o,undo:l,redo:u,addSource:m,whenReady:p,removeSource:h,insertSource:b,restoreClips:y,newProject:x,removeClip:T,trimClip:P,splitAt:_,moveClip:S,select:M,beginDraft:C,updateDraft:v,commitDraft:A,cancelDraft:H}}const gb=Fr({__name:"index",setup(r){const{t:e}=Rr();fl({title:()=>e("page_title"),meta:[{name:"robots",content:"noindex, nofollow"}]});const t=fb(),i=ab(t.project),n=bp(),s=sb(t),a=ke(void 0),o=ke(!1);return dn(()=>{var m;const c=s.read(),l=Ng();a.value=l==null?void 0:l.returnPath,o.value=(c==null?void 0:c.hadLocalClips)??!1;const u=new Map,d=(p,h)=>{const b=t.addSource({url:p.url,label:p.label,prompt:p.prompt,model:p.model,taskId:p.taskId,origin:"generation",group:h});return b.status==="probing"&&n.ensure(b.id,{url:b.url}),u.set(p.url,b.id),b.id};for(const p of(c==null?void 0:c.sources)??[])d(p,"recent");const f=[];for(const p of(c==null?void 0:c.clips)??[]){const h=u.get(p.src);h&&f.push({sourceId:h,in:p.in,out:p.out})}for(const p of(l==null?void 0:l.sources)??[]){u.has(p.url)||d(p,"handoff");const h=u.get(p.url);h&&f.push({sourceId:h})}if(!c&&!(l!=null&&l.sources.length))for(const p of Ug(12))d({url:p.url,label:((m=p.prompt)==null?void 0:m.trim())||p.model||"Video",prompt:p.prompt,model:p.model},"recent");(async()=>{const p=[];for(const h of f){const b=await t.whenReady(h.sourceId);(b==null?void 0:b.status)==="ready"&&p.push({sourceId:h.sourceId,in:h.in??0,out:h.out??b.duration})}t.restoreClips(p)})()}),(c,l)=>(Z(),bt(Z0,{studio:w(t),playback:w(i),thumbs:w(n),"return-path":w(a),"local-clips-removed":w(o)},null,8,["studio","playback","thumbs","return-path","local-clips-removed"]))}});export{gb as default};
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.