diff --git a/backend/autostart_pause.go b/backend/autostart_pause.go new file mode 100644 index 0000000..b57ae06 --- /dev/null +++ b/backend/autostart_pause.go @@ -0,0 +1,222 @@ +// backend\autostart_pause.go + +package main + +import ( + "encoding/json" + "io" + "net/http" + "strings" + "sync" + "sync/atomic" + "time" +) + +var autostartPaused int32 // 0=false, 1=true + +// --- SSE subscribers für Autostart-State --- +var autostartSubsMu sync.Mutex +var autostartSubs = map[chan bool]struct{}{} + +func broadcastAutostartPaused(paused bool) { + autostartSubsMu.Lock() + defer autostartSubsMu.Unlock() + + for ch := range autostartSubs { + // non-blocking: wenn Client langsam ist, droppen wir Updates (neuester Zustand kommt eh wieder) + select { + case ch <- paused: + default: + } + } +} + +func isAutostartPaused() bool { + return atomic.LoadInt32(&autostartPaused) == 1 +} + +func setAutostartPaused(v bool) { + old := isAutostartPaused() + + if v { + atomic.StoreInt32(&autostartPaused, 1) + } else { + atomic.StoreInt32(&autostartPaused, 0) + } + + // nur wenn sich der Zustand wirklich geändert hat -> pushen + if old != v { + broadcastAutostartPaused(v) + } +} + +type autostartPauseReq struct { + Paused *bool `json:"paused"` +} + +func autostartPauseHandler(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{ + "paused": isAutostartPaused(), + }) + return + + case http.MethodPost: + // erlaubt: JSON body { "paused": true/false } + // oder Query ?paused=1/0/true/false + var val *bool + + ct := strings.ToLower(r.Header.Get("Content-Type")) + if strings.Contains(ct, "application/json") { + var req autostartPauseReq + _ = json.NewDecoder(r.Body).Decode(&req) + val = req.Paused + } + + if val == nil { + q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("paused"))) + if q != "" { + b := q == "1" || q == "true" || q == "yes" || q == "on" + val = &b + } + } + + if val == nil { + http.Error(w, "missing 'paused' (json body or query)", http.StatusBadRequest) + return + } + + setAutostartPaused(*val) + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{ + "paused": isAutostartPaused(), + }) + return + + default: + http.Error(w, "Nur GET/POST erlaubt", http.StatusMethodNotAllowed) + return + } +} + +func writeAutostartState(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{ + "paused": isAutostartPaused(), + }) +} + +// GET /api/autostart/state +func autostartStateHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Nur GET erlaubt", http.StatusMethodNotAllowed) + return + } + writeAutostartState(w) +} + +// GET/POST /api/autostart/pause (POST ohne Body pausiert) +func autostartPauseQuickHandler(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + writeAutostartState(w) + return + case http.MethodPost: + setAutostartPaused(true) + writeAutostartState(w) + return + default: + http.Error(w, "Nur GET/POST erlaubt", http.StatusMethodNotAllowed) + return + } +} + +// POST /api/autostart/resume (optional auch GET) +func autostartResumeHandler(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + writeAutostartState(w) + return + case http.MethodPost: + setAutostartPaused(false) + writeAutostartState(w) + return + default: + http.Error(w, "Nur GET/POST erlaubt", http.StatusMethodNotAllowed) + return + } +} + +// GET /api/autostart/state/stream (SSE) +func autostartStateStreamHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Nur GET erlaubt", http.StatusMethodNotAllowed) + return + } + + fl, ok := w.(http.Flusher) + if !ok { + http.Error(w, "Streaming nicht unterstützt", http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Connection", "keep-alive") + w.Header().Set("X-Accel-Buffering", "no") // wichtig falls Proxy/Nginx + + ch := make(chan bool, 1) + + // subscribe + autostartSubsMu.Lock() + autostartSubs[ch] = struct{}{} + autostartSubsMu.Unlock() + + // cleanup + defer func() { + autostartSubsMu.Lock() + delete(autostartSubs, ch) + autostartSubsMu.Unlock() + close(ch) + }() + + send := func(paused bool) { + payload := map[string]any{ + "paused": paused, + "ts": time.Now().UTC().Format(time.RFC3339Nano), + } + + b, _ := json.Marshal(payload) + _, _ = io.WriteString(w, "event: autostart\n") + _, _ = io.WriteString(w, "data: ") + _, _ = w.Write(b) + _, _ = io.WriteString(w, "\n\n") + fl.Flush() + } + + // initial state sofort senden + send(isAutostartPaused()) + + ctx := r.Context() + hb := time.NewTicker(15 * time.Second) + defer hb.Stop() + + for { + select { + case <-ctx.Done(): + return + case v := <-ch: + send(v) + case <-hb.C: + // heartbeat gegen Proxy timeouts + _, _ = io.WriteString(w, ": keep-alive\n\n") + fl.Flush() + } + } +} diff --git a/backend/chaturbate_autostart.go b/backend/chaturbate_autostart.go index 69a0b6b..bda50c9 100644 --- a/backend/chaturbate_autostart.go +++ b/backend/chaturbate_autostart.go @@ -96,6 +96,12 @@ func startChaturbateAutoStartWorker(store *ModelStore) { var lastStart time.Time for { + if isAutostartPaused() { + // optional: Queue behalten oder leeren – ich würde sie behalten. + time.Sleep(2 * time.Second) + continue + } + s := getSettings() // ✅ Autostart nur wenn Feature aktiviert ist // (optional zusätzlich AutoAddToDownloadList wie im Frontend logisch gekoppelt) diff --git a/backend/chaturbate_biocontext.go b/backend/chaturbate_biocontext.go new file mode 100644 index 0000000..7cf5ff1 --- /dev/null +++ b/backend/chaturbate_biocontext.go @@ -0,0 +1,243 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +const chaturbateBioContextURLFmt = "https://chaturbate.com/api/biocontext/%s/" + +// wie lange wir Biocontext ohne Refresh aus der DB zurückgeben +const bioCacheMaxAge = 10 * time.Minute + +type BioContextResp struct { + Enabled bool `json:"enabled"` + FetchedAt time.Time `json:"fetchedAt"` + LastError string `json:"lastError,omitempty"` + Model string `json:"model"` + Bio any `json:"bio,omitempty"` +} + +func sanitizeModelKey(s string) string { + s = strings.TrimSpace(strings.TrimPrefix(s, "@")) + // erlaubte chars: a-z A-Z 0-9 _ - . + s = strings.Map(func(r rune) rune { + switch { + case r >= 'a' && r <= 'z': + return r + case r >= 'A' && r <= 'Z': + return r + case r >= '0' && r <= '9': + return r + case r == '_' || r == '-' || r == '.': + return r + default: + return -1 + } + }, s) + return strings.TrimSpace(s) +} + +func chaturbateBioContextHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Nur GET erlaubt", http.StatusMethodNotAllowed) + return + } + + // ✅ Option A: Biocontext ist IMMER aktiv (unabhängig von UseChaturbateAPI) + enabled := true + + model := sanitizeModelKey(r.URL.Query().Get("model")) + if model == "" { + http.Error(w, "model fehlt", http.StatusBadRequest) + return + } + + refresh := strings.TrimSpace(r.URL.Query().Get("refresh")) + forceRefresh := refresh == "1" || strings.EqualFold(refresh, "true") + + // 1) Cache aus ModelStore lesen (persistiert über Neustarts) + var ( + cachedBio any + cachedAt time.Time + hasCache bool + ) + if cbModelStore != nil { + raw, ts, ok, err := cbModelStore.GetBioContext("chaturbate.com", model) + if err == nil && ok { + var tmp any + if e := json.Unmarshal([]byte(raw), &tmp); e == nil { + cachedBio = tmp + hasCache = true + if t, e2 := time.Parse(time.RFC3339Nano, strings.TrimSpace(ts)); e2 == nil { + cachedAt = t + } + } + } + } + + // 2) Wenn Cache frisch ist und kein Force-Refresh, geben wir ihn sofort zurück + if hasCache && !forceRefresh && !cachedAt.IsZero() && time.Since(cachedAt) < bioCacheMaxAge { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(BioContextResp{ + Enabled: enabled, + FetchedAt: cachedAt, + LastError: "", + Model: model, + Bio: cachedBio, + }) + return + } + + // 3) Upstream abrufen + ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) + defer cancel() + + u := fmt.Sprintf(chaturbateBioContextURLFmt, model) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err != nil { + http.Error(w, "request build failed: "+err.Error(), http.StatusInternalServerError) + return + } + + req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") + req.Header.Set("Accept", "application/json, text/plain, */*") + req.Header.Set("Referer", "https://chaturbate.com/"+model+"/") + + // ✅ optional: Cookies vom Frontend (für Cloudflare / session) + if ck := strings.TrimSpace(r.Header.Get("X-Chaturbate-Cookie")); ck != "" { + req.Header.Set("Cookie", ck) + } + + resp, err := cbHTTP.Do(req) // cbHTTP existiert schon in chaturbate_online.go + if err != nil { + // Fallback: Cache liefern (wenn vorhanden) + if hasCache { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(BioContextResp{ + Enabled: enabled, + FetchedAt: cachedAt, + LastError: err.Error(), + Model: model, + Bio: cachedBio, + }) + return + } + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(BioContextResp{ + Enabled: enabled, + FetchedAt: time.Now().UTC(), + LastError: err.Error(), + Model: model, + }) + return + } + defer resp.Body.Close() + + // max 1MB + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + + // Helper: Body-Snippet für Debug + snip := strings.TrimSpace(string(raw)) + if len(snip) > 400 { + snip = snip[:400] + "…" + } + + if resp.StatusCode != 200 { + errMsg := fmt.Sprintf("HTTP %d (ct=%s): %s", resp.StatusCode, resp.Header.Get("Content-Type"), snip) + + if hasCache { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(BioContextResp{ + Enabled: enabled, + FetchedAt: cachedAt, + LastError: errMsg, + Model: model, + Bio: cachedBio, + }) + return + } + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(BioContextResp{ + Enabled: enabled, + FetchedAt: time.Now().UTC(), + LastError: errMsg, + Model: model, + }) + return + } + + // 4) JSON parse + var bio any + if err := json.Unmarshal(raw, &bio); err != nil { + ct := strings.ToLower(resp.Header.Get("Content-Type")) + lowerBody := strings.ToLower(snip) + + // sehr häufig: HTML statt JSON (Cloudflare/Age-Gate/etc.) + htmlLike := strings.Contains(ct, "text/html") || + strings.HasPrefix(strings.TrimSpace(lowerBody), " max alle 10 Minuten + const tagsFillEvery = 10 * time.Minute + + // nur loggen, wenn sich etwas ändert (sonst spammt es) lastLoggedCount := -1 lastLoggedErr := "" + // Tags-Fill Throttle (lokal in der Funktion) + var tagsMu sync.Mutex + var tagsLast time.Time + // sofort ein initialer Tick first := time.NewTimer(0) defer first.Stop() + ticker := time.NewTicker(interval) defer ticker.Stop() @@ -115,18 +202,25 @@ func startChaturbateOnlinePoller() { continue } - ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + // ✅ immer merken: wir haben es versucht (hilft dem Handler beim Bootstrap-Cooldown) + cbMu.Lock() + cb.LastAttempt = time.Now() + cbMu.Unlock() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) rooms, err := fetchChaturbateOnlineRooms(ctx) cancel() cbMu.Lock() if err != nil { - // ❗️WICHTIG: bei Fehler NICHT fetchedAt aktualisieren, + // ❗️bei Fehler NICHT fetchedAt aktualisieren, // sonst wirkt der Cache "frisch", obwohl rooms alt sind. cb.LastErr = err.Error() - // ❗️Damit offline Models nicht hängen bleiben: rooms leeren + // ❗️damit offline Models nicht hängen bleiben: Cache leeren cb.Rooms = nil + cb.RoomsByUser = nil + cb.LiteByUser = nil cbMu.Unlock() @@ -137,12 +231,31 @@ func startChaturbateOnlinePoller() { continue } - // ✅ Erfolg: komplette Liste ersetzen + fetchedAt setzen + // ✅ Erfolg: komplette Liste ersetzen + indices + fetchedAt setzen cb.LastErr = "" cb.Rooms = rooms + cb.RoomsByUser = indexRoomsByUser(rooms) + cb.LiteByUser = indexLiteByUser(rooms) cb.FetchedAt = time.Now() + cbMu.Unlock() + // ✅ Tags übernehmen ist teuer -> nur selten + im Hintergrund + if cbModelStore != nil && len(rooms) > 0 { + shouldFill := false + + tagsMu.Lock() + if tagsLast.IsZero() || time.Since(tagsLast) >= tagsFillEvery { + tagsLast = time.Now() + shouldFill = true + } + tagsMu.Unlock() + + if shouldFill { + go cbModelStore.FillMissingTagsFromChaturbateOnline(rooms) + } + } + // success logging only on changes if lastLoggedErr != "" { fmt.Println("✅ [chaturbate] online rooms fetch recovered") @@ -155,105 +268,313 @@ func startChaturbateOnlinePoller() { } } +var onlineCacheMu sync.Mutex +var onlineCache = map[string]struct { + at time.Time + body []byte +}{} + +func cachedOnline(key string) ([]byte, bool) { + onlineCacheMu.Lock() + defer onlineCacheMu.Unlock() + e, ok := onlineCache[key] + if !ok { + return nil, false + } + if time.Since(e.at) > 2*time.Second { // TTL + delete(onlineCache, key) + return nil, false + } + return e.body, true +} + +func setCachedOnline(key string, body []byte) { + onlineCacheMu.Lock() + onlineCache[key] = struct { + at time.Time + body []byte + }{at: time.Now(), body: body} + onlineCacheMu.Unlock() +} + +type cbOnlineReq struct { + Q []string `json:"q"` // usernames + Show []string `json:"show"` // public/private/hidden/away + Refresh bool `json:"refresh"` +} + +func hashKey(parts ...string) string { + h := sha1.New() + for _, p := range parts { + _, _ = h.Write([]byte(p)) + _, _ = h.Write([]byte{0}) + } + return hex.EncodeToString(h.Sum(nil)) +} + func chaturbateOnlineHandler(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, "Nur GET erlaubt", http.StatusMethodNotAllowed) + if r.Method != http.MethodGet && r.Method != http.MethodPost { + http.Error(w, "Nur GET/POST erlaubt", http.StatusMethodNotAllowed) return } enabled := getSettings().UseChaturbateAPI + // --------------------------- + // Request params (GET/POST) + // --------------------------- + wantRefresh := false + var users []string + var shows []string + + if r.Method == http.MethodPost { + r.Body = http.MaxBytesReader(w, r.Body, 8<<20) + + raw, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "Body read failed", http.StatusBadRequest) + return + } + + var req cbOnlineReq + if len(raw) > 0 { + if err := json.Unmarshal(raw, &req); err != nil { + http.Error(w, "Invalid JSON body", http.StatusBadRequest) + return + } + } + + wantRefresh = req.Refresh + + // normalize users + seenU := map[string]bool{} + for _, u := range req.Q { + u = strings.ToLower(strings.TrimSpace(u)) + if u == "" || seenU[u] { + continue + } + seenU[u] = true + users = append(users, u) + } + sort.Strings(users) + + // normalize shows + seenS := map[string]bool{} + for _, s := range req.Show { + s = strings.ToLower(strings.TrimSpace(s)) + if s == "" || seenS[s] { + continue + } + seenS[s] = true + shows = append(shows, s) + } + sort.Strings(shows) + } else { + // GET (legacy) + qRefresh := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("refresh"))) + wantRefresh = qRefresh == "1" || qRefresh == "true" || qRefresh == "yes" + + qUsers := strings.TrimSpace(r.URL.Query().Get("q")) + if qUsers != "" { + seenU := map[string]bool{} + for _, s := range strings.Split(qUsers, ",") { + u := strings.ToLower(strings.TrimSpace(s)) + if u == "" || seenU[u] { + continue + } + seenU[u] = true + users = append(users, u) + } + sort.Strings(users) + } + + showFilter := strings.TrimSpace(r.URL.Query().Get("show")) + if showFilter != "" { + seenS := map[string]bool{} + for _, s := range strings.Split(showFilter, ",") { + s = strings.ToLower(strings.TrimSpace(s)) + if s == "" || seenS[s] { + continue + } + seenS[s] = true + shows = append(shows, s) + } + sort.Strings(shows) + } + } + + // --------------------------- + // Ultra-wichtig: niemals die komplette Affiliate-Liste ausliefern. + // Wenn keine Users angegeben sind -> leere Antwort (spart massiv CPU + JSON) + // --------------------------- + onlySpecificUsers := len(users) > 0 + + // show allow-set + allowedShow := map[string]bool{} + for _, s := range shows { + allowedShow[s] = true + } + + // --------------------------- + // Response Cache (2s) + // --------------------------- + cacheKey := "cb_online:" + hashKey( + fmt.Sprintf("enabled=%v", enabled), + "users="+strings.Join(users, ","), + "show="+strings.Join(shows, ","), + fmt.Sprintf("refresh=%v", wantRefresh), + "lite=1", + ) + if body, ok := cachedOnline(cacheKey); ok { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _, _ = w.Write(body) + return + } + + // --------------------------- + // Disabled -> immer schnell + // --------------------------- if !enabled { w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") - _ = json.NewEncoder(w).Encode(map[string]any{ + + out := map[string]any{ "enabled": false, "fetchedAt": time.Time{}, "count": 0, "lastError": "", - "rooms": []ChaturbateRoom{}, - }) + "rooms": []any{}, + } + body, _ := json.Marshal(out) + setCachedOnline(cacheKey, body) + _, _ = w.Write(body) return } - // optional: ?refresh=1 triggert einen direkten Fetch (falls aktiviert) - q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("refresh"))) - wantRefresh := q == "1" || q == "true" || q == "yes" - - // Snapshot des Caches + // --------------------------- + // Snapshot Cache (nur Lite-Index nutzen) + // --------------------------- cbMu.RLock() - rooms := cb.Rooms fetchedAt := cb.FetchedAt lastErr := cb.LastErr + lastAttempt := cb.LastAttempt + liteByUser := cb.LiteByUser // map[usernameLower]ChaturbateRoomLite cbMu.RUnlock() - // Wenn aktiviert aber Cache noch nie gefüllt wurde, einmalig automatisch fetchen. - // (Das verhindert das "count=0 / fetchedAt=0001" Verhalten direkt nach Neustart.) - const staleAfter = 20 * time.Second - isStale := fetchedAt.IsZero() || time.Since(fetchedAt) > staleAfter + // --------------------------- + // Refresh/Bootstrap-Strategie: + // - Handler blockiert NICHT auf Remote-Fetch (Performance!) + // - wenn refresh=true: triggert einen Fetch (best effort), aber liefert sofort Cache/leer zurück + // - wenn Cache noch nie erfolgreich war: "warming up" + best-effort Bootstrap, mit Cooldown + // --------------------------- + const bootstrapCooldown = 8 * time.Second - if enabled && (wantRefresh || isStale) { + needBootstrap := fetchedAt.IsZero() + shouldTriggerFetch := + wantRefresh || + (needBootstrap && time.Since(lastAttempt) >= bootstrapCooldown) - ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) - freshRooms, err := fetchChaturbateOnlineRooms(ctx) - cancel() - cbMu.Lock() - if err != nil { - cb.LastErr = err.Error() - - // ❗️WICHTIG: keine alten rooms weitergeben - cb.Rooms = nil - - // ❗️FetchedAt NICHT aktualisieren (bleibt letzte erfolgreiche Zeit) + if shouldTriggerFetch { + cbRefreshMu.Lock() + if cbRefreshInFlight { + cbRefreshMu.Unlock() } else { - cb.LastErr = "" - cb.Rooms = freshRooms - cb.FetchedAt = time.Now() + cbRefreshInFlight = true + cbRefreshMu.Unlock() + + // attempt timestamp sofort setzen (damit 100 Requests nicht alle triggern) + cbMu.Lock() + cb.LastAttempt = time.Now() + cbMu.Unlock() + + // ✅ background fetch (nicht blockieren) + go func() { + defer func() { + cbRefreshMu.Lock() + cbRefreshInFlight = false + cbRefreshMu.Unlock() + }() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + rooms, err := fetchChaturbateOnlineRooms(ctx) + cancel() + + cbMu.Lock() + if err != nil { + cb.LastErr = err.Error() + cb.Rooms = nil + cb.RoomsByUser = nil + cb.LiteByUser = nil + // fetchedAt NICHT ändern (bleibt letzte erfolgreiche Zeit) + } else { + cb.LastErr = "" + cb.Rooms = rooms + cb.RoomsByUser = indexRoomsByUser(rooms) + cb.LiteByUser = indexLiteByUser(rooms) // ✅ kleiner Index für Handler + cb.FetchedAt = time.Now() + } + cbMu.Unlock() + + // Tags optional übernehmen (nur bei Erfolg) + if cbModelStore != nil && err == nil && len(rooms) > 0 { + cbModelStore.FillMissingTagsFromChaturbateOnline(rooms) + } + }() } - - rooms = cb.Rooms - fetchedAt = cb.FetchedAt - lastErr = cb.LastErr - cbMu.Unlock() - } - // nil-slice vermeiden -> Frontend bekommt [] statt null - if rooms == nil { - rooms = []ChaturbateRoom{} + // --------------------------- + // Rooms bauen (LITE, O(Anzahl requested Users)) + // --------------------------- + type outRoom struct { + Username string `json:"username"` + CurrentShow string `json:"current_show"` + ChatRoomURL string `json:"chat_room_url"` + ImageURL string `json:"image_url"` } - // optional: ?show=public,private,hidden,away - showFilter := strings.TrimSpace(r.URL.Query().Get("show")) - if showFilter != "" { - allowed := map[string]bool{} - for _, s := range strings.Split(showFilter, ",") { - s = strings.ToLower(strings.TrimSpace(s)) - if s != "" { - allowed[s] = true + outRooms := make([]outRoom, 0, len(users)) + + if onlySpecificUsers && liteByUser != nil { + for _, u := range users { + rm, ok := liteByUser[u] + if !ok { + continue } - } - if len(allowed) > 0 { - filtered := make([]ChaturbateRoom, 0, len(rooms)) - for _, rm := range rooms { - if allowed[strings.ToLower(strings.TrimSpace(rm.CurrentShow))] { - filtered = append(filtered, rm) + // show filter + if len(allowedShow) > 0 { + s := strings.ToLower(strings.TrimSpace(rm.CurrentShow)) + if !allowedShow[s] { + continue } } - rooms = filtered + outRooms = append(outRooms, outRoom{ + Username: rm.Username, + CurrentShow: rm.CurrentShow, + ChatRoomURL: rm.ChatRoomURL, + ImageURL: rm.ImageURL, + }) } } + // wenn noch nie erfolgreich gefetched: nicer error + if needBootstrap && lastErr == "" { + lastErr = "warming up" + } + w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") - // Wir liefern ein kleines Meta-Objekt, damit du im UI sofort siehst, ob der Cache aktuell ist. out := map[string]any{ - "enabled": enabled, + "enabled": true, "fetchedAt": fetchedAt, - "count": len(rooms), + "count": len(outRooms), "lastError": lastErr, - "rooms": rooms, + "rooms": outRooms, // ✅ klein & schnell } - _ = json.NewEncoder(w).Encode(out) + + body, _ := json.Marshal(out) + setCachedOnline(cacheKey, body) + _, _ = w.Write(body) } diff --git a/backend/data/models_store.db b/backend/data/models_store.db index df6cb78..d5053ea 100644 Binary files a/backend/data/models_store.db and b/backend/data/models_store.db differ diff --git a/backend/data/models_store.db-shm b/backend/data/models_store.db-shm index b7a15f0..fa8c0e2 100644 Binary files a/backend/data/models_store.db-shm and b/backend/data/models_store.db-shm differ diff --git a/backend/data/models_store.db-wal b/backend/data/models_store.db-wal index b5e8586..e7d4c73 100644 Binary files a/backend/data/models_store.db-wal and b/backend/data/models_store.db-wal differ diff --git a/backend/go.mod b/backend/go.mod index 98beb2e..308a9e4 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -8,6 +8,16 @@ require ( github.com/grafov/m3u8 v0.12.1 ) +require ( + github.com/go-ole/go-ole v1.2.6 // indirect + github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect + github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect + github.com/shoenig/go-m1cpu v0.1.6 // indirect + github.com/tklauser/go-sysconf v0.3.12 // indirect + github.com/tklauser/numcpus v0.6.1 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect +) + require ( github.com/TheTitanrain/w32 v0.0.0-20180517000239-4f5cfb03fabf // indirect github.com/andybalholm/cascadia v1.3.3 // indirect @@ -15,6 +25,7 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/shirou/gopsutil/v3 v3.24.5 github.com/sqweek/dialog v0.0.0-20240226140203-065105509627 // indirect golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect golang.org/x/net v0.47.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index 439f685..ff8b10a 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -6,20 +6,37 @@ github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kk github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grafov/m3u8 v0.12.1 h1:DuP1uA1kvRRmGNAZ0m+ObLv1dvrfNO0TPx0c/enNk0s= github.com/grafov/m3u8 v0.12.1/go.mod h1:nqzOkfBiZJENr52zTVd/Dcl03yzphIMbJqkXGu+u080= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI= +github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk= +github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= +github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= github.com/sqweek/dialog v0.0.0-20240226140203-065105509627 h1:2JL2wmHXWIAxDofCK+AdkFi1KEg3dgkefCsm7isADzQ= github.com/sqweek/dialog v0.0.0-20240226140203-065105509627/go.mod h1:/qNPSY91qTz/8TgHEMioAUc6q7+3SOybeKczHMXFcXw= +github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU= +github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI= +github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk= +github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= @@ -52,13 +69,16 @@ golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= @@ -90,6 +110,7 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A= modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= diff --git a/backend/main.go b/backend/main.go index b62f7eb..d065583 100644 --- a/backend/main.go +++ b/backend/main.go @@ -1,3 +1,5 @@ +// backend\main.go + package main import ( @@ -8,6 +10,7 @@ import ( "encoding/json" "errors" "fmt" + "html" "io" "math" "net/http" @@ -22,12 +25,15 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "syscall" "time" "github.com/PuerkitoBio/goquery" "github.com/google/uuid" "github.com/grafov/m3u8" + gocpu "github.com/shirou/gopsutil/v3/cpu" + godisk "github.com/shirou/gopsutil/v3/disk" "github.com/sqweek/dialog" ) @@ -52,11 +58,19 @@ type RecordJob struct { DurationSeconds float64 `json:"durationSeconds,omitempty"` SizeBytes int64 `json:"sizeBytes,omitempty"` + Hidden bool `json:"-"` + Error string `json:"error,omitempty"` - PreviewDir string `json:"-"` - PreviewImage string `json:"-"` - previewCmd *exec.Cmd `json:"-"` + PreviewDir string `json:"-"` + PreviewImage string `json:"-"` + previewCmd *exec.Cmd `json:"-"` + LiveThumbStarted bool `json:"-"` + + // ✅ Preview-Status (z.B. private/offline anhand ffmpeg HTTP Fehler) + PreviewState string `json:"previewState,omitempty"` // "", "private", "offline", "error" + PreviewStateAt string `json:"previewStateAt,omitempty"` // RFC3339Nano + PreviewStateMsg string `json:"previewStateMsg,omitempty"` // kurze Info // Thumbnail cache (verhindert, dass pro HTTP-Request ffmpeg läuft) previewMu sync.Mutex `json:"-"` @@ -65,7 +79,7 @@ type RecordJob struct { previewGen bool `json:"-"` // ✅ Frontend Progress beim Stop/Finalize - Phase string `json:"phase,omitempty"` // stopping | remuxing | moving | finalizing + Phase string `json:"phase,omitempty"` // stopping | remuxing | moving Progress int `json:"progress,omitempty"` // 0..100 cancel context.CancelFunc `json:"-"` @@ -89,6 +103,13 @@ var ( jobsMu = sync.Mutex{} ) +var serverStartedAt = time.Now() + +var lastCPUUsageBits uint64 // atomic float64 bits + +func setLastCPUUsage(v float64) { atomic.StoreUint64(&lastCPUUsageBits, math.Float64bits(v)) } +func getLastCPUUsage() float64 { return math.Float64frombits(atomic.LoadUint64(&lastCPUUsageBits)) } + // -------------------- SSE: /api/record/stream -------------------- type sseHub struct { @@ -129,6 +150,9 @@ var recordJobsHub = newSSEHub() var recordJobsNotify = make(chan struct{}, 1) func init() { + initFFmpegSemaphores() + startAdaptiveSemController(context.Background()) + // Debounced broadcaster go func() { for range recordJobsNotify { @@ -149,6 +173,20 @@ func init() { }() } +func publishJob(jobID string) bool { + jobsMu.Lock() + j := jobs[jobID] + if j == nil || !j.Hidden { + jobsMu.Unlock() + return false + } + j.Hidden = false + jobsMu.Unlock() + + notifyJobsChanged() + return true +} + func notifyJobsChanged() { select { case recordJobsNotify <- struct{}{}: @@ -158,16 +196,20 @@ func notifyJobsChanged() { func jobsSnapshotJSON() []byte { jobsMu.Lock() - list := make([]RecordJob, 0, len(jobs)) + list := make([]*RecordJob, 0, len(jobs)) for _, j := range jobs { - if j == nil { + // ✅ Hidden-Jobs niemals an die UI senden (verhindert „UI springt“) + if j == nil || j.Hidden { continue } - c := *j // copy => stabiler Snapshot fürs JSON - list = append(list, c) + + c := *j + c.cancel = nil // nicht serialisieren + list = append(list, &c) } jobsMu.Unlock() + // optional: neueste zuerst sort.Slice(list, func(i, j int) bool { return list[i].StartedAt.After(list[j].StartedAt) }) @@ -188,44 +230,108 @@ func recordStream(w http.ResponseWriter, r *http.Request) { return } - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.Header().Set("X-Accel-Buffering", "no") // hilfreich bei Reverse-Proxies + // SSE-Header + h := w.Header() + h.Set("Content-Type", "text/event-stream; charset=utf-8") + h.Set("Cache-Control", "no-cache, no-transform") + h.Set("Connection", "keep-alive") + h.Set("X-Accel-Buffering", "no") // hilfreich bei Reverse-Proxies - // Reconnect-Hinweis für Browser - _, _ = fmt.Fprintf(w, "retry: 3000\n\n") + // sofort starten + w.WriteHeader(http.StatusOK) + + writeEvent := func(event string, data []byte) bool { + // returns false => client weg / write error + if event != "" { + if _, err := fmt.Fprintf(w, "event: %s\n", event); err != nil { + return false + } + } + if len(data) > 0 { + if _, err := fmt.Fprintf(w, "data: %s\n\n", data); err != nil { + return false + } + } else { + // empty payload ok (nur terminator) + if _, err := io.WriteString(w, "\n"); err != nil { + return false + } + } + flusher.Flush() + return true + } + + writeComment := func(msg string) bool { + if _, err := fmt.Fprintf(w, ": %s\n\n", msg); err != nil { + return false + } + flusher.Flush() + return true + } + + // Reconnect-Hinweis + if _, err := fmt.Fprintf(w, "retry: 3000\n\n"); err != nil { + return + } flusher.Flush() - ch := make(chan []byte, 16) + // Channel + Hub + ch := make(chan []byte, 32) recordJobsHub.add(ch) defer recordJobsHub.remove(ch) // Initialer Snapshot sofort if b := jobsSnapshotJSON(); len(b) > 0 { - _, _ = fmt.Fprintf(w, "event: jobs\ndata: %s\n\n", b) - flusher.Flush() + if !writeEvent("jobs", b) { + return + } } + ctx := r.Context() + + // Ping/Keepalive ping := time.NewTicker(15 * time.Second) defer ping.Stop() for { select { - case <-r.Context().Done(): + case <-ctx.Done(): return - case b := <-ch: + case b, ok := <-ch: + if !ok { + return + } if len(b) == 0 { continue } - _, _ = fmt.Fprintf(w, "event: jobs\ndata: %s\n\n", b) - flusher.Flush() + + // ✅ Burst-Coalescing: wenn viele Updates schnell kommen, nur das neueste senden + last := b + drain: + for i := 0; i < 64; i++ { + select { + case nb, ok := <-ch: + if !ok { + return + } + if len(nb) > 0 { + last = nb + } + default: + break drain + } + } + + if !writeEvent("jobs", last) { + return + } case <-ping.C: // Keepalive als Kommentar (stört nicht, hält Verbindungen offen) - _, _ = fmt.Fprintf(w, ": ping %d\n\n", time.Now().Unix()) - flusher.Flush() + if !writeComment(fmt.Sprintf("ping %d", time.Now().Unix())) { + return + } } } } @@ -283,8 +389,228 @@ func detectFFprobePath() string { return "ffprobe" } -// Preview/Teaser-Generierung nicht unendlich parallel -var genSem = make(chan struct{}, 2) +// ---------- Dynamic Semaphore (resizeable by load controller) ---------- + +type DynSem struct { + mu sync.Mutex + in int + max int + cap int +} + +func NewDynSem(initial, cap int) *DynSem { + if cap < 1 { + cap = 1 + } + if initial < 1 { + initial = 1 + } + if initial > cap { + initial = cap + } + return &DynSem{max: initial, cap: cap} +} + +func (s *DynSem) Acquire(ctx context.Context) error { + for { + if ctx != nil && ctx.Err() != nil { + return ctx.Err() + } + s.mu.Lock() + if s.in < s.max { + s.in++ + s.mu.Unlock() + return nil + } + s.mu.Unlock() + time.Sleep(25 * time.Millisecond) + } +} + +func (s *DynSem) Release() { + s.mu.Lock() + if s.in > 0 { + s.in-- + } + s.mu.Unlock() +} + +func (s *DynSem) SetMax(n int) { + if n < 1 { + n = 1 + } + if n > s.cap { + n = s.cap + } + s.mu.Lock() + s.max = n + s.mu.Unlock() +} + +func (s *DynSem) Max() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.max +} + +func (s *DynSem) Cap() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.cap +} + +func (s *DynSem) InUse() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.in +} + +var ( + genSem *DynSem + previewSem *DynSem + thumbSem *DynSem + durSem *DynSem +) + +func clamp(n, lo, hi int) int { + if n < lo { + return lo + } + if n > hi { + return hi + } + return n +} + +func envInt(name string) (int, bool) { + v := strings.TrimSpace(os.Getenv(name)) + if v == "" { + return 0, false + } + n, err := strconv.Atoi(v) + if err != nil { + return 0, false + } + return n, true +} + +func initFFmpegSemaphores() { + cpu := runtime.NumCPU() + if cpu <= 0 { + cpu = 2 + } + + // Defaults (heuristisch) + previewN := clamp((cpu+1)/2, 1, 6) // x264 live -> konservativ + thumbN := clamp(cpu, 2, 12) // Frames -> darf höher + genN := clamp((cpu+3)/4, 1, 4) // preview.mp4 clips -> eher klein + durN := clamp(cpu, 2, 16) // ffprobe: darf höher, aber nicht unbegrenzt + + // ENV Overrides (optional) + if n, ok := envInt("PREVIEW_WORKERS"); ok { + previewN = clamp(n, 1, 32) + } + if n, ok := envInt("THUMB_WORKERS"); ok { + thumbN = clamp(n, 1, 64) + } + if n, ok := envInt("GEN_WORKERS"); ok { + genN = clamp(n, 1, 16) + } + if n, ok := envInt("DUR_WORKERS"); ok { + durN = clamp(n, 1, 64) + } + + // Caps (Obergrenzen) – können via ENV überschrieben werden + previewCap := clamp(cpu, 2, 12) + thumbCap := clamp(cpu*2, 4, 32) + genCap := clamp((cpu+1)/2, 2, 12) + durCap := clamp(cpu*2, 4, 32) + + if n, ok := envInt("PREVIEW_CAP"); ok { + previewCap = clamp(n, 1, 64) + } + if n, ok := envInt("THUMB_CAP"); ok { + thumbCap = clamp(n, 1, 128) + } + if n, ok := envInt("GEN_CAP"); ok { + genCap = clamp(n, 1, 64) + } + if n, ok := envInt("DUR_CAP"); ok { + durCap = clamp(n, 1, 128) + } + + // Initial max (Startwerte) + previewSem = NewDynSem(previewN, previewCap) + thumbSem = NewDynSem(thumbN, thumbCap) + genSem = NewDynSem(genN, genCap) + durSem = NewDynSem(durN, durCap) + + fmt.Printf( + "🔧 semaphores(init): preview=%d/%d thumb=%d/%d gen=%d/%d dur=%d/%d (cpu=%d)\n", + previewSem.Max(), previewSem.Cap(), + thumbSem.Max(), thumbSem.Cap(), + genSem.Max(), genSem.Cap(), + durSem.Max(), durSem.Cap(), + cpu, + ) + + fmt.Printf( + "🔧 semaphores: preview=%d thumb=%d gen=%d dur=%d (cpu=%d)\n", + previewN, thumbN, genN, durN, cpu, + ) +} + +func startAdaptiveSemController(ctx context.Context) { + targetHi := 85.0 + targetLo := 65.0 + + if v := strings.TrimSpace(os.Getenv("CPU_TARGET_HI")); v != "" { + if f, err := strconv.ParseFloat(v, 64); err == nil { + targetHi = f + } + } + if v := strings.TrimSpace(os.Getenv("CPU_TARGET_LO")); v != "" { + if f, err := strconv.ParseFloat(v, 64); err == nil { + targetLo = f + } + } + + // Warmup (erste Messung kann 0 sein) + _, _ = gocpu.Percent(200*time.Millisecond, false) + + t := time.NewTicker(2 * time.Second) + go func() { + defer t.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-t.C: + p, err := gocpu.Percent(0, false) + if err != nil || len(p) == 0 { + continue + } + usage := p[0] + setLastCPUUsage(usage) + + // Preview ist am teuersten → konservativ + if usage > targetHi { + previewSem.SetMax(previewSem.Max() - 1) + genSem.SetMax(genSem.Max() - 1) + thumbSem.SetMax(thumbSem.Max() - 1) + } else if usage < targetLo { + previewSem.SetMax(previewSem.Max() + 1) + genSem.SetMax(genSem.Max() + 1) + thumbSem.SetMax(thumbSem.Max() + 1) + } + + // optional Debug: + // fmt.Printf("CPU %.1f%% -> preview=%d thumb=%d gen=%d\n", usage, previewSem.Max(), thumbSem.Max(), genSem.Max()) + } + } + }() +} type durEntry struct { size int64 @@ -301,6 +627,346 @@ var startedAtFromFilenameRe = regexp.MustCompile( `^(.+)_([0-9]{1,2})_([0-9]{1,2})_([0-9]{4})__([0-9]{1,2})-([0-9]{2})-([0-9]{2})$`, ) +func buildPerfSnapshot() map[string]any { + var ms runtime.MemStats + runtime.ReadMemStats(&ms) + + s := getSettings() + recordDir, _ := resolvePathRelativeToApp(s.RecordDir) + + var diskFreeBytes uint64 + var diskTotalBytes uint64 + var diskUsedPercent float64 + diskPath := recordDir + + if recordDir != "" { + if u, err := godisk.Usage(recordDir); err == nil && u != nil { + diskFreeBytes = u.Free + diskTotalBytes = u.Total + diskUsedPercent = u.UsedPercent + } + } + + resp := map[string]any{ + "ts": time.Now().UTC().Format(time.RFC3339Nano), + "serverMs": time.Now().UTC().UnixMilli(), // ✅ für "Ping" im Frontend (Approx) + "uptimeSec": time.Since(serverStartedAt).Seconds(), + "cpuPercent": func() float64 { + v := getLastCPUUsage() + if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 { + return 0 + } + return v + }(), + "diskPath": diskPath, + "diskFreeBytes": diskFreeBytes, + "diskTotalBytes": diskTotalBytes, + "diskUsedPercent": diskUsedPercent, + "diskEmergency": atomic.LoadInt32(&diskEmergency) == 1, + "diskPauseBelowGB": getSettings().LowDiskPauseBelowGB, + "diskResumeAboveGB": getSettings().LowDiskPauseBelowGB + 3, + "goroutines": runtime.NumGoroutine(), + "mem": map[string]any{ + "alloc": ms.Alloc, + "heapAlloc": ms.HeapAlloc, + "heapInuse": ms.HeapInuse, + "sys": ms.Sys, + "numGC": ms.NumGC, + }, + } + + sem := map[string]any{} + if genSem != nil { + sem["gen"] = map[string]any{"inUse": genSem.InUse(), "cap": genSem.Cap(), "max": genSem.Max()} + } + if previewSem != nil { + sem["preview"] = map[string]any{"inUse": previewSem.InUse(), "cap": previewSem.Cap(), "max": previewSem.Max()} + } + if thumbSem != nil { + sem["thumb"] = map[string]any{"inUse": thumbSem.InUse(), "cap": thumbSem.Cap(), "max": thumbSem.Max()} + } + if durSem != nil { + sem["dur"] = map[string]any{"inUse": durSem.InUse(), "cap": durSem.Cap(), "max": durSem.Max()} + } + if len(sem) > 0 { + resp["sem"] = sem + } + + return resp +} + +func pingHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + http.Error(w, "Nur GET/HEAD erlaubt", http.StatusMethodNotAllowed) + return + } + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusNoContent) +} + +func perfHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Nur GET erlaubt", http.StatusMethodNotAllowed) + return + } + + resp := buildPerfSnapshot() + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(resp) + + sem := map[string]any{} + + if genSem != nil { + sem["gen"] = map[string]any{"inUse": genSem.InUse(), "cap": genSem.Cap(), "max": genSem.Max()} + } + if previewSem != nil { + sem["preview"] = map[string]any{"inUse": previewSem.InUse(), "cap": previewSem.Cap(), "max": previewSem.Max()} + } + if thumbSem != nil { + sem["thumb"] = map[string]any{"inUse": thumbSem.InUse(), "cap": thumbSem.Cap(), "max": thumbSem.Max()} + } + if durSem != nil { + sem["dur"] = map[string]any{"inUse": durSem.InUse(), "cap": durSem.Cap(), "max": durSem.Max()} + } + + if len(sem) > 0 { + resp["sem"] = sem + } + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(resp) +} + +func perfStreamHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Nur GET erlaubt", http.StatusMethodNotAllowed) + return + } + + fl, ok := w.(http.Flusher) + if !ok { + http.Error(w, "Streaming nicht unterstützt", http.StatusInternalServerError) + return + } + + // Optional: client kann Intervall mitgeben: /api/perf/stream?ms=5000 + ms := 5000 + if q := r.URL.Query().Get("ms"); q != "" { + if v, err := strconv.Atoi(q); err == nil { + // clamp: 1000..30000 + if v < 1000 { + v = 1000 + } + if v > 30000 { + v = 30000 + } + ms = v + } + } + + w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Connection", "keep-alive") + // hilfreich hinter nginx/proxies: + w.Header().Set("X-Accel-Buffering", "no") + + ctx := r.Context() + + // sofort erstes Event schicken + send := func() error { + payload := buildPerfSnapshot() + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(payload); err != nil { + return err + } + + // event: perf + _, _ = io.WriteString(w, "event: perf\n") + _, _ = io.WriteString(w, "data: ") + _, _ = w.Write(buf.Bytes()) + _, _ = io.WriteString(w, "\n") + fl.Flush() + return nil + } + + // initial + _ = send() + + t := time.NewTicker(time.Duration(ms) * time.Millisecond) + hb := time.NewTicker(15 * time.Second) // heartbeat gegen Proxy timeouts + defer t.Stop() + defer hb.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-t.C: + _ = send() + case <-hb.C: + // SSE Kommentar als Heartbeat + _, _ = io.WriteString(w, ": keep-alive\n\n") + fl.Flush() + } + } +} + +// ------------------------- +// Low disk space guard +// - pausiert Autostart +// - stoppt laufende Downloads +// ------------------------- + +const ( + diskGuardInterval = 5 * time.Second +) + +var diskEmergency int32 // 0=false, 1=true + +// stopJobsInternal markiert Jobs als "stopping" und cancelt sie (inkl. Preview-FFmpeg Kill). +// Nutzt 2 notify-Pushes, damit die UI Phase/Progress sofort sieht. +func stopJobsInternal(list []*RecordJob) { + if len(list) == 0 { + return + } + + type payload struct { + cmd *exec.Cmd + cancel context.CancelFunc + } + + pl := make([]payload, 0, len(list)) + + jobsMu.Lock() + for _, job := range list { + if job == nil { + continue + } + job.Phase = "stopping" + job.Progress = 10 + pl = append(pl, payload{cmd: job.previewCmd, cancel: job.cancel}) + job.previewCmd = nil + } + jobsMu.Unlock() + + notifyJobsChanged() // 1) UI sofort updaten (Phase/Progress) + + for _, p := range pl { + if p.cmd != nil && p.cmd.Process != nil { + _ = p.cmd.Process.Kill() + } + if p.cancel != nil { + p.cancel() + } + } + + notifyJobsChanged() // 2) optional: nach Cancel/Kill nochmal pushen +} + +func stopAllStoppableJobs() int { + stoppable := make([]*RecordJob, 0, 16) + + jobsMu.Lock() + for _, j := range jobs { + if j == nil { + continue + } + phase := strings.TrimSpace(j.Phase) + if j.Status == JobRunning && phase == "" { + stoppable = append(stoppable, j) + } + } + jobsMu.Unlock() + + stopJobsInternal(stoppable) + return len(stoppable) +} + +// startDiskSpaceGuard läuft im Backend und reagiert auch ohne offenen Browser. +// Bei wenig freiem Platz: +// - Autostart pausieren +// - laufende Jobs stoppen (nur Status=running und Phase leer) +func startDiskSpaceGuard() { + t := time.NewTicker(diskGuardInterval) + defer t.Stop() + + for range t.C { + s := getSettings() + + // ✅ Schwellen aus Settings (GB -> Bytes) + pauseGB := s.LowDiskPauseBelowGB + + // Defaults / Safety + if pauseGB <= 0 { + pauseGB = 5 + } + if pauseGB < 1 { + pauseGB = 1 + } + if pauseGB > 10_000 { + pauseGB = 10_000 + } + + // ✅ Resume automatisch: +3GB Hysterese (wie vorher 5 -> 8) + resumeGB := pauseGB + 3 + if resumeGB > 10_000 { + resumeGB = 10_000 + } + + pauseBytes := uint64(pauseGB) * 1024 * 1024 * 1024 + resumeBytes := uint64(resumeGB) * 1024 * 1024 * 1024 + + recordDirAbs, _ := resolvePathRelativeToApp(s.RecordDir) + dir := strings.TrimSpace(recordDirAbs) + if dir == "" { + dir = strings.TrimSpace(s.RecordDir) + } + if dir == "" { + continue + } + + u, err := godisk.Usage(dir) + if err != nil || u == nil { + continue + } + free := u.Free + + // ✅ Hysterese: erst ab resumeBytes wieder "bereit" + if atomic.LoadInt32(&diskEmergency) == 1 { + if free >= resumeBytes { + atomic.StoreInt32(&diskEmergency, 0) + fmt.Printf("✅ [disk] Recovered: free=%dB (>= %dB) emergency cleared\n", free, resumeBytes) + } + continue + } + + // ✅ Normalzustand: solange free >= pauseBytes, nichts tun + if free >= pauseBytes { + continue + } + + atomic.StoreInt32(&diskEmergency, 1) + fmt.Printf( + "🛑 [disk] Low space: free=%dB (<%dB, pause=%dGB resume=%dGB) -> pause autostart + stop jobs\n", + free, pauseBytes, pauseGB, resumeGB, + ) + + // 1) Autostart pausieren + setAutostartPaused(true) + + // 2) laufende Downloads stoppen + stopped := stopAllStoppableJobs() + if stopped > 0 { + fmt.Printf("🛑 [disk] Stop requested for %d job(s)\n", stopped) + } + } + +} + func setJobPhase(job *RecordJob, phase string, progress int) { if progress < 0 { progress = 0 @@ -313,6 +979,9 @@ func setJobPhase(job *RecordJob, phase string, progress int) { job.Phase = phase job.Progress = progress jobsMu.Unlock() + + notifyJobsChanged() + } func durationSecondsCached(ctx context.Context, path string) (float64, error) { @@ -376,16 +1045,26 @@ func durationSecondsCached(ctx context.Context, path string) (float64, error) { type RecorderSettings struct { RecordDir string `json:"recordDir"` DoneDir string `json:"doneDir"` - FFmpegPath string `json:"ffmpegPath,omitempty"` + FFmpegPath string `json:"ffmpegPath"` - AutoAddToDownloadList bool `json:"autoAddToDownloadList,omitempty"` - AutoStartAddedDownloads bool `json:"autoStartAddedDownloads,omitempty"` + AutoAddToDownloadList bool `json:"autoAddToDownloadList"` + AutoStartAddedDownloads bool `json:"autoStartAddedDownloads"` - UseChaturbateAPI bool `json:"useChaturbateApi,omitempty"` - BlurPreviews bool `json:"blurPreviews,omitempty"` + UseChaturbateAPI bool `json:"useChaturbateApi"` + UseMyFreeCamsWatcher bool `json:"useMyFreeCamsWatcher"` + // Wenn aktiv, werden fertige Downloads automatisch gelöscht, wenn sie kleiner als der Grenzwert sind. + AutoDeleteSmallDownloads bool `json:"autoDeleteSmallDownloads"` + AutoDeleteSmallDownloadsBelowMB int `json:"autoDeleteSmallDownloadsBelowMB"` + + BlurPreviews bool `json:"blurPreviews"` + TeaserPlayback string `json:"teaserPlayback"` // still | hover | all + TeaserAudio bool `json:"teaserAudio"` // ✅ Vorschau/Teaser mit Ton abspielen + + // Low disk guard (GB) + LowDiskPauseBelowGB int `json:"lowDiskPauseBelowGB"` // z.B. 5 // EncryptedCookies contains base64(nonce+ciphertext) of a JSON cookie map. - EncryptedCookies string `json:"encryptedCookies,omitempty"` + EncryptedCookies string `json:"encryptedCookies"` } var ( @@ -398,13 +1077,35 @@ var ( AutoAddToDownloadList: false, AutoStartAddedDownloads: false, - UseChaturbateAPI: false, - BlurPreviews: false, + UseChaturbateAPI: false, + UseMyFreeCamsWatcher: false, + AutoDeleteSmallDownloads: false, + AutoDeleteSmallDownloadsBelowMB: 50, + + BlurPreviews: false, + TeaserPlayback: "hover", + TeaserAudio: false, + LowDiskPauseBelowGB: 5, + EncryptedCookies: "", } settingsFile = "recorder_settings.json" ) +func settingsFilePath() string { + // optionaler Override per ENV + name := strings.TrimSpace(os.Getenv("RECORDER_SETTINGS_FILE")) + if name == "" { + name = settingsFile + } + // Standard: relativ zur EXE / App-Dir (oder fallback auf Working Dir bei go run) + if p, err := resolvePathRelativeToApp(name); err == nil && strings.TrimSpace(p) != "" { + return p + } + // Fallback: so zurückgeben wie es ist + return name +} + func getSettings() RecorderSettings { settingsMu.Lock() defer settingsMu.Unlock() @@ -459,11 +1160,43 @@ func detectFFmpegPath() string { } func removeGeneratedForID(id string) { - thumbsRoot, _ := generatedThumbsRoot() - teaserRoot, _ := generatedTeaserRoot() + // canonical id (ohne HOT) + id = stripHotPrefix(strings.TrimSpace(id)) + if id == "" { + return + } - _ = os.RemoveAll(filepath.Join(thumbsRoot, id)) - _ = os.Remove(filepath.Join(teaserRoot, id+".mp4")) + // 1) NEU: generated// (enthält thumbs.jpg, preview.mp4, meta.json, t_*.jpg, ...) + if root, _ := generatedRoot(); strings.TrimSpace(root) != "" { + _ = os.RemoveAll(filepath.Join(root, id)) + } + + // 2) Temp Preview Segmente (HLS) wegräumen + // (%TEMP%/rec_preview/) + _ = os.RemoveAll(filepath.Join(os.TempDir(), "rec_preview", id)) + + // 3) Legacy Cleanup (best effort) + thumbsLegacy, _ := generatedThumbsRoot() + teaserLegacy, _ := generatedTeaserRoot() + + if strings.TrimSpace(thumbsLegacy) != "" { + _ = os.RemoveAll(filepath.Join(thumbsLegacy, id)) + _ = os.Remove(filepath.Join(thumbsLegacy, id+".jpg")) + } + if strings.TrimSpace(teaserLegacy) != "" { + _ = os.Remove(filepath.Join(teaserLegacy, id+".mp4")) + _ = os.Remove(filepath.Join(teaserLegacy, id+"_teaser.mp4")) + } +} + +func purgeDurationCacheForPath(p string) { + p = strings.TrimSpace(p) + if p == "" { + return + } + durCache.mu.Lock() + delete(durCache.m, p) + durCache.mu.Unlock() } func renameGenerated(oldID, newID string) { @@ -492,9 +1225,11 @@ func renameGenerated(oldID, newID string) { } func loadSettings() { - b, err := os.ReadFile(settingsFile) + p := settingsFilePath() + b, err := os.ReadFile(p) + fmt.Println("🔧 settingsFile:", p) if err == nil { - var s RecorderSettings + s := getSettings() // ✅ startet mit Defaults if json.Unmarshal(b, &s) == nil { if strings.TrimSpace(s.RecordDir) != "" { s.RecordDir = filepath.Clean(strings.TrimSpace(s.RecordDir)) @@ -506,6 +1241,30 @@ func loadSettings() { s.FFmpegPath = strings.TrimSpace(s.FFmpegPath) } + s.TeaserPlayback = strings.ToLower(strings.TrimSpace(s.TeaserPlayback)) + if s.TeaserPlayback == "" { + s.TeaserPlayback = "hover" + } + if s.TeaserPlayback != "still" && s.TeaserPlayback != "hover" && s.TeaserPlayback != "all" { + s.TeaserPlayback = "hover" + } + + // Auto-Delete: clamp + if s.AutoDeleteSmallDownloadsBelowMB < 0 { + s.AutoDeleteSmallDownloadsBelowMB = 0 + } + if s.AutoDeleteSmallDownloadsBelowMB > 100_000 { + s.AutoDeleteSmallDownloadsBelowMB = 100_000 + } + + // Low disk guard: clamp + Hysterese erzwingen + if s.LowDiskPauseBelowGB < 1 { + s.LowDiskPauseBelowGB = 1 + } + if s.LowDiskPauseBelowGB > 10_000 { + s.LowDiskPauseBelowGB = 10_000 + } + settingsMu.Lock() settings = s settingsMu.Unlock() @@ -514,8 +1273,14 @@ func loadSettings() { // Ordner sicherstellen s := getSettings() - _ = os.MkdirAll(s.RecordDir, 0o755) - _ = os.MkdirAll(s.DoneDir, 0o755) + recordAbs, _ := resolvePathRelativeToApp(s.RecordDir) + doneAbs, _ := resolvePathRelativeToApp(s.DoneDir) + if strings.TrimSpace(recordAbs) != "" { + _ = os.MkdirAll(recordAbs, 0o755) + } + if strings.TrimSpace(doneAbs) != "" { + _ = os.MkdirAll(doneAbs, 0o755) + } // ffmpeg-Pfad anhand Settings/Env/PATH bestimmen ffmpegPath = detectFFmpegPath() @@ -528,8 +1293,21 @@ func loadSettings() { func saveSettingsToDisk() { s := getSettings() - b, _ := json.MarshalIndent(s, "", " ") - _ = os.WriteFile(settingsFile, b, 0o644) + + b, err := json.MarshalIndent(s, "", " ") + if err != nil { + fmt.Println("⚠️ settings marshal:", err) + return + } + b = append(b, '\n') + + p := settingsFilePath() + if err := atomicWriteFile(p, b); err != nil { + fmt.Println("⚠️ settings write:", err) + return + } + // optional + // fmt.Println("✅ settings saved:", p) } func recordSettingsHandler(w http.ResponseWriter, r *http.Request) { @@ -546,34 +1324,66 @@ func recordSettingsHandler(w http.ResponseWriter, r *http.Request) { return } + // --- normalize --- in.RecordDir = filepath.Clean(strings.TrimSpace(in.RecordDir)) in.DoneDir = filepath.Clean(strings.TrimSpace(in.DoneDir)) in.FFmpegPath = strings.TrimSpace(in.FFmpegPath) + in.TeaserPlayback = strings.ToLower(strings.TrimSpace(in.TeaserPlayback)) + if in.TeaserPlayback == "" { + in.TeaserPlayback = "hover" + } + if in.TeaserPlayback != "still" && in.TeaserPlayback != "hover" && in.TeaserPlayback != "all" { + in.TeaserPlayback = "hover" + } + if in.RecordDir == "" || in.DoneDir == "" { http.Error(w, "recordDir und doneDir dürfen nicht leer sein", http.StatusBadRequest) return } - // Ordner erstellen (Fehler zurückgeben, falls z.B. keine Rechte) - if err := os.MkdirAll(in.RecordDir, 0o755); err != nil { + // Auto-Delete: clamp + if in.AutoDeleteSmallDownloadsBelowMB < 0 { + in.AutoDeleteSmallDownloadsBelowMB = 0 + } + if in.AutoDeleteSmallDownloadsBelowMB > 100_000 { + in.AutoDeleteSmallDownloadsBelowMB = 100_000 + } + + // Low disk guard: backward compat + clamp + current := getSettings() + if in.LowDiskPauseBelowGB <= 0 { + in.LowDiskPauseBelowGB = current.LowDiskPauseBelowGB + } + if in.LowDiskPauseBelowGB < 1 { + in.LowDiskPauseBelowGB = 1 + } + if in.LowDiskPauseBelowGB > 10_000 { + in.LowDiskPauseBelowGB = 10_000 + } + + // --- ensure folders (Fehler zurückgeben, falls z.B. keine Rechte) --- + recAbs, _ := resolvePathRelativeToApp(in.RecordDir) + doneAbs, _ := resolvePathRelativeToApp(in.DoneDir) + + if err := os.MkdirAll(recAbs, 0o755); err != nil { http.Error(w, "konnte recordDir nicht erstellen: "+err.Error(), http.StatusBadRequest) return } - if err := os.MkdirAll(in.DoneDir, 0o755); err != nil { + if err := os.MkdirAll(doneAbs, 0o755); err != nil { http.Error(w, "konnte doneDir nicht erstellen: "+err.Error(), http.StatusBadRequest) return } - current := getSettings() - in.EncryptedCookies = current.EncryptedCookies - + // ✅ WICHTIG: Settings im RAM aktualisieren settingsMu.Lock() settings = in settingsMu.Unlock() + + // ✅ WICHTIG: Settings auf Disk persistieren saveSettingsToDisk() - // ffmpeg-Pfad nach Änderungen neu bestimmen + // ✅ ffmpeg/ffprobe nach Änderungen neu bestimmen (nutzt jetzt die neuen Settings) ffmpegPath = detectFFmpegPath() fmt.Println("🔍 ffmpegPath:", ffmpegPath) @@ -581,6 +1391,7 @@ func recordSettingsHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("🔍 ffprobePath:", ffprobePath) w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(getSettings()) return @@ -768,6 +1579,144 @@ func remuxTSToMP4(tsPath, mp4Path string) error { return nil } +func parseFFmpegOutTime(v string) float64 { + v = strings.TrimSpace(v) + if v == "" { + return 0 + } + parts := strings.Split(v, ":") + if len(parts) != 3 { + return 0 + } + h, err1 := strconv.Atoi(parts[0]) + m, err2 := strconv.Atoi(parts[1]) + s, err3 := strconv.ParseFloat(parts[2], 64) // Sekunden können Dezimalstellen haben + if err1 != nil || err2 != nil || err3 != nil { + return 0 + } + return float64(h*3600+m*60) + s +} + +func remuxTSToMP4WithProgress( + ctx context.Context, + tsPath, mp4Path string, + durationSec float64, + inSize int64, + onRatio func(r float64), +) error { + // ffmpeg progress kommt auf stdout als key=value + cmd := exec.CommandContext(ctx, ffmpegPath, + "-y", + "-nostats", + "-progress", "pipe:1", + "-i", tsPath, + "-c", "copy", + "-movflags", "+faststart", + mp4Path, + ) + + stdout, err := cmd.StdoutPipe() + if err != nil { + return err + } + + var stderr bytes.Buffer + cmd.Stderr = &stderr + + if err := cmd.Start(); err != nil { + return err + } + + sc := bufio.NewScanner(stdout) + sc.Buffer(make([]byte, 0, 64*1024), 1024*1024) + + var ( + lastOutSec float64 + lastTotalSz int64 + ) + + send := func(outSec float64, totalSize int64, force bool) { + // bevorzugt: Zeit/Dauer + if durationSec > 0 && outSec > 0 { + r := outSec / durationSec + if r < 0 { + r = 0 + } + if r > 1 { + r = 1 + } + if onRatio != nil { + onRatio(r) + } + return + } + + // fallback: Bytes (bei remux meist okay-ish) + if inSize > 0 && totalSize > 0 { + r := float64(totalSize) / float64(inSize) + if r < 0 { + r = 0 + } + if r > 1 { + r = 1 + } + if onRatio != nil { + onRatio(r) + } + return + } + + // force (z.B. end) + if force && onRatio != nil { + onRatio(1) + } + } + + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" { + continue + } + k, v, ok := strings.Cut(line, "=") + if !ok { + continue + } + + switch k { + case "out_time_us": + if n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64); err == nil && n > 0 { + lastOutSec = float64(n) / 1_000_000.0 + send(lastOutSec, lastTotalSz, false) + } + case "out_time_ms": + if n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64); err == nil && n > 0 { + // out_time_ms ist i.d.R. Millisekunden + lastOutSec = float64(n) / 1_000.0 + send(lastOutSec, lastTotalSz, false) + } + case "out_time": + if s := parseFFmpegOutTime(v); s > 0 { + lastOutSec = s + send(lastOutSec, lastTotalSz, false) + } + case "total_size": + if n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64); err == nil && n > 0 { + lastTotalSz = n + send(lastOutSec, lastTotalSz, false) + } + case "progress": + if strings.TrimSpace(v) == "end" { + send(lastOutSec, lastTotalSz, true) + } + } + } + + if err := cmd.Wait(); err != nil { + return fmt.Errorf("ffmpeg remux failed: %v (%s)", err, strings.TrimSpace(stderr.String())) + } + return nil +} + // --- MP4 Streaming Optimierung (Fast Start) --- // "Fast Start" bedeutet: moov vor mdat (Browser kann sofort Metadaten lesen) func isFastStartMP4(path string) (bool, error) { @@ -931,6 +1880,93 @@ func extractFrameAtTimeJPEG(path string, seconds float64) ([]byte, error) { return out.Bytes(), nil } +func extractLastFrameJPEGScaled(path string, width int, q int) ([]byte, error) { + if width <= 0 { + width = 320 + } + if q <= 0 { + q = 14 + } + + // ffmpeg: letztes Frame, low-res + cmd := exec.Command( + ffmpegPath, + "-hide_banner", "-loglevel", "error", + "-sseof", "-0.25", + "-i", path, + "-frames:v", "1", + "-vf", fmt.Sprintf("scale=%d:-2", width), + "-q:v", strconv.Itoa(q), + "-f", "image2pipe", + "pipe:1", + ) + + var out bytes.Buffer + var stderr bytes.Buffer + cmd.Stdout = &out + cmd.Stderr = &stderr + + if err := cmd.Run(); err != nil { + return nil, fmt.Errorf("ffmpeg last-frame scaled: %w (%s)", err, strings.TrimSpace(stderr.String())) + } + + b := out.Bytes() + if len(b) == 0 { + return nil, fmt.Errorf("ffmpeg last-frame scaled: empty output") + } + return b, nil +} + +func extractFirstFrameJPEGScaled(path string, width int, q int) ([]byte, error) { + if width <= 0 { + width = 320 + } + if q <= 0 { + q = 14 + } + + cmd := exec.Command( + ffmpegPath, + "-hide_banner", "-loglevel", "error", + "-ss", "0", + "-i", path, + "-frames:v", "1", + "-vf", fmt.Sprintf("scale=%d:-2", width), + "-q:v", strconv.Itoa(q), + "-f", "image2pipe", + "pipe:1", + ) + + var out bytes.Buffer + var stderr bytes.Buffer + cmd.Stdout = &out + cmd.Stderr = &stderr + + if err := cmd.Run(); err != nil { + return nil, fmt.Errorf("ffmpeg first-frame scaled: %w (%s)", err, strings.TrimSpace(stderr.String())) + } + + b := out.Bytes() + if len(b) == 0 { + return nil, fmt.Errorf("ffmpeg first-frame scaled: empty output") + } + return b, nil +} + +func extractLastFrameFromPreviewDirThumb(previewDir string) ([]byte, error) { + seg, err := latestPreviewSegment(previewDir) + if err != nil { + return nil, err + } + + // low-res, notfalls fallback auf erstes Frame + img, err := extractLastFrameJPEGScaled(seg, 320, 14) + if err == nil && len(img) > 0 { + return img, nil + } + return extractFirstFrameJPEGScaled(seg, 320, 14) +} + // sucht das "neueste" Preview-Segment (seg_low_XXXXX.ts / seg_hq_XXXXX.ts) func latestPreviewSegment(previewDir string) (string, error) { entries, err := os.ReadDir(previewDir) @@ -995,6 +2031,67 @@ func generatedTeaserRoot() (string, error) { return resolvePathRelativeToApp(filepath.Join("generated", "teaser")) } +// -------------------------- +// generated//meta.json +// -------------------------- + +type videoMetaV1 struct { + Version int `json:"version"` + DurationSeconds float64 `json:"durationSeconds"` + FileSize int64 `json:"fileSize"` + FileModUnix int64 `json:"fileModUnix"` + UpdatedAtUnix int64 `json:"updatedAtUnix"` +} + +func generatedMetaFile(id string) (string, error) { + dir, err := generatedDirForID(id) // erzeugt KEIN Verzeichnis + if err != nil { + return "", err + } + return filepath.Join(dir, "meta.json"), nil +} + +func readVideoMetaDuration(metaPath string, fi os.FileInfo) (sec float64, ok bool) { + b, err := os.ReadFile(metaPath) + if err != nil || len(b) == 0 { + return 0, false + } + var m videoMetaV1 + if err := json.Unmarshal(b, &m); err != nil { + return 0, false + } + if m.Version != 1 { + return 0, false + } + // Invalidation: wenn Datei geändert wurde -> Meta ignorieren + if m.FileSize != fi.Size() || m.FileModUnix != fi.ModTime().Unix() { + return 0, false + } + if m.DurationSeconds <= 0 { + return 0, false + } + return m.DurationSeconds, true +} + +func writeVideoMeta(metaPath string, fi os.FileInfo, dur float64) error { + if strings.TrimSpace(metaPath) == "" || dur <= 0 { + return nil + } + m := videoMetaV1{ + Version: 1, + DurationSeconds: dur, + FileSize: fi.Size(), + FileModUnix: fi.ModTime().Unix(), + UpdatedAtUnix: time.Now().Unix(), + } + buf, err := json.Marshal(m) + if err != nil { + return err + } + buf = append(buf, '\n') + return atomicWriteFile(metaPath, buf) +} + // ✅ Neu: /generated//thumbs.jpg + /generated//preview.mp4 func generatedDirForID(id string) (string, error) { id, err := sanitizeID(id) @@ -1065,6 +2162,24 @@ func idFromVideoPath(videoPath string) string { return strings.TrimSuffix(name, filepath.Ext(name)) } +func assetIDForJob(job *RecordJob) string { + if job == nil { + return "" + } + + // Prefer: Dateiname ohne Endung (und ohne HOT Prefix) + out := strings.TrimSpace(job.Output) + if out != "" { + id := stripHotPrefix(idFromVideoPath(out)) + if strings.TrimSpace(id) != "" { + return id + } + } + + // Fallback: JobID (sollte praktisch nie nötig sein) + return strings.TrimSpace(job.ID) +} + func atomicWriteFile(dst string, data []byte) error { dir := filepath.Dir(dst) if err := os.MkdirAll(dir, 0o755); err != nil { @@ -1101,26 +2216,26 @@ func findFinishedFileByID(id string) (string, error) { return "", fmt.Errorf("not found") } - candidates := []string{ - // done - filepath.Join(doneAbs, base+".mp4"), - filepath.Join(doneAbs, "HOT "+base+".mp4"), - filepath.Join(doneAbs, base+".ts"), - filepath.Join(doneAbs, "HOT "+base+".ts"), - - // record - filepath.Join(recordAbs, base+".mp4"), - filepath.Join(recordAbs, "HOT "+base+".mp4"), - filepath.Join(recordAbs, base+".ts"), - filepath.Join(recordAbs, "HOT "+base+".ts"), + names := []string{ + base + ".mp4", + "HOT " + base + ".mp4", + base + ".ts", + "HOT " + base + ".ts", } - for _, p := range candidates { - fi, err := os.Stat(p) - if err == nil && !fi.IsDir() && fi.Size() > 0 { + // done (root + /done//) + keep (root + /done/keep//) + for _, name := range names { + if p, _, ok := findFileInDirOrOneLevelSubdirs(doneAbs, name, "keep"); ok { + return p, nil + } + if p, _, ok := findFileInDirOrOneLevelSubdirs(filepath.Join(doneAbs, "keep"), name, ""); ok { + return p, nil + } + if p, _, ok := findFileInDirOrOneLevelSubdirs(recordAbs, name, ""); ok { return p, nil } } + return "", fmt.Errorf("not found") } @@ -1143,11 +2258,26 @@ func recordPreview(w http.ResponseWriter, r *http.Request) { jobsMu.Unlock() if ok { - // ✅ Thumbnail-Caching: nicht pro HTTP-Request ffmpeg starten. + // ✅ 0) Running: wenn generated//thumbs.jpg existiert -> sofort ausliefern + // (kein ffmpeg pro HTTP-Request) + if job.Status == "running" { + assetID := assetIDForJob(job) + if assetID != "" { + if thumbPath, err := generatedThumbFile(assetID); err == nil { + if st, err := os.Stat(thumbPath); err == nil && !st.IsDir() && st.Size() > 0 { + serveLivePreviewJPEGFile(w, r, thumbPath) + return + } + } + } + } + + // ✅ Fallback: alter In-Memory-Cache (falls thumbs.jpg noch nicht da ist) job.previewMu.Lock() cached := job.previewJpeg cachedAt := job.previewJpegAt - fresh := len(cached) > 0 && !cachedAt.IsZero() && time.Since(cachedAt) < 10*time.Second + freshWindow := 8 * time.Second + fresh := len(cached) > 0 && !cachedAt.IsZero() && time.Since(cachedAt) < freshWindow // Wenn nicht frisch, ggf. im Hintergrund aktualisieren (einmal gleichzeitig) if !fresh && !job.previewGen { @@ -1200,9 +2330,24 @@ func recordPreview(w http.ResponseWriter, r *http.Request) { out := cached job.previewMu.Unlock() if len(out) > 0 { - servePreviewJPEGBytes(w, out) + serveLivePreviewJPEGBytes(w, out) // ✅ no-store für laufende Jobs return } + + // ✅ Wenn Preview definitiv nicht geht -> Placeholder statt 204 + jobsMu.Lock() + state := strings.TrimSpace(job.PreviewState) + jobsMu.Unlock() + + if state == "private" { + servePreviewStatusSVG(w, "Private") + return + } + if state == "offline" { + servePreviewStatusSVG(w, "Offline") + return + } + // noch kein Bild verfügbar -> 204 (Frontend zeigt Placeholder und retry) w.Header().Set("Cache-Control", "no-store") w.WriteHeader(http.StatusNoContent) @@ -1213,6 +2358,137 @@ func recordPreview(w http.ResponseWriter, r *http.Request) { servePreviewForFinishedFile(w, r, id) } +func serveLivePreviewJPEGFile(w http.ResponseWriter, r *http.Request, path string) { + f, err := os.Open(path) + if err != nil { + http.NotFound(w, r) + return + } + defer f.Close() + + st, err := f.Stat() + if err != nil || st.IsDir() || st.Size() == 0 { + http.NotFound(w, r) + return + } + + w.Header().Set("Content-Type", "image/jpeg") + w.Header().Set("Cache-Control", "no-store") + http.ServeContent(w, r, "thumbs.jpg", st.ModTime(), f) +} + +func updateLiveThumbOnce(ctx context.Context, job *RecordJob) { + // Snapshot unter Lock holen + jobsMu.Lock() + status := job.Status + previewDir := job.PreviewDir + out := job.Output + jobsMu.Unlock() + + if status != "running" { + return + } + + // Zielpfad: generated//thumbs.jpg + assetID := assetIDForJob(job) + thumbPath, err := generatedThumbFile(assetID) + + if err != nil { + return + } + + // Wenn frisch genug: skip + if st, err := os.Stat(thumbPath); err == nil && st.Size() > 0 { + if time.Since(st.ModTime()) < 10*time.Second { + return + } + } + + // Concurrency limit über thumbSem + if thumbSem != nil { + thumbCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + + if err := thumbSem.Acquire(thumbCtx); err != nil { + return + } + defer thumbSem.Release() + } + + var img []byte + + // 1) bevorzugt aus Preview-Segmenten + if previewDir != "" { + if b, err := extractLastFrameFromPreviewDirThumb(previewDir); err == nil && len(b) > 0 { + img = b + } + } + + // 2) fallback aus Output-Datei (kann bei partial files manchmal langsamer sein) + if len(img) == 0 && out != "" { + if b, err := extractLastFrameJPEGScaled(out, 320, 14); err == nil && len(b) > 0 { + img = b + } + } + + if len(img) == 0 { + return + } + + _ = atomicWriteFile(thumbPath, img) +} + +func startLiveThumbLoop(ctx context.Context, job *RecordJob) { + // einmalig starten + jobsMu.Lock() + if job.LiveThumbStarted { + jobsMu.Unlock() + return + } + job.LiveThumbStarted = true + jobsMu.Unlock() + + go func() { + // sofort einmal versuchen + updateLiveThumbOnce(ctx, job) + + for { + // dynamische Frequenz: je mehr aktive Jobs, desto langsamer (weniger Last) + jobsMu.Lock() + nRunning := 0 + for _, j := range jobs { + if j != nil && j.Status == "running" { + nRunning++ + } + } + jobsMu.Unlock() + + delay := 12 * time.Second + if nRunning >= 6 { + delay = 18 * time.Second + } + if nRunning >= 12 { + delay = 25 * time.Second + } + + select { + case <-ctx.Done(): + return + case <-time.After(delay): + // ✅ Stoppen, sobald Job nicht mehr läuft + jobsMu.Lock() + st := job.Status + jobsMu.Unlock() + if st != "running" { + return + } + + updateLiveThumbOnce(ctx, job) + } + } + }() +} + // Fallback: Preview für fertige Dateien nur anhand des Dateistamms (id) func servePreviewForFinishedFile(w http.ResponseWriter, r *http.Request, id string) { var err error @@ -1366,12 +2642,25 @@ func generateTeaserMP4(ctx context.Context, srcPath, outPath string, startSec, d "-ss", fmt.Sprintf("%.3f", startSec), "-i", srcPath, "-t", fmt.Sprintf("%.3f", durSec), + + // Video "-vf", "scale=720:-2", - "-an", + "-map", "0:v:0", + + // Audio (optional: falls kein Audio vorhanden ist, bricht ffmpeg NICHT ab) + "-map", "0:a:0?", + "-c:a", "aac", + "-b:a", "128k", + "-ac", "2", + "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", + + // Wenn Audio minimal kürzer/länger ist, sauber beenden + "-shortest", + "-movflags", "+faststart", "-f", "mp4", tmp, @@ -1457,8 +2746,11 @@ func generatedTeaser(w http.ResponseWriter, r *http.Request) { } // Neu erzeugen - genSem <- struct{}{} - defer func() { <-genSem }() + if err := genSem.Acquire(r.Context()); err != nil { + http.Error(w, "abgebrochen: "+err.Error(), http.StatusRequestTimeout) + return + } + defer genSem.Release() genCtx, cancel := context.WithTimeout(r.Context(), 3*time.Minute) defer cancel() @@ -1492,6 +2784,7 @@ type AssetsTaskState struct { var assetsTaskMu sync.Mutex var assetsTaskState AssetsTaskState +var assetsTaskCancel context.CancelFunc func tasksGenerateAssets(w http.ResponseWriter, r *http.Request) { switch r.Method { @@ -1511,6 +2804,10 @@ func tasksGenerateAssets(w http.ResponseWriter, r *http.Request) { return } + // ✅ cancelbaren Context erzeugen + ctx, cancel := context.WithCancel(context.Background()) + assetsTaskCancel = cancel + assetsTaskState = AssetsTaskState{ Running: true, StartedAt: time.Now(), @@ -1518,7 +2815,32 @@ func tasksGenerateAssets(w http.ResponseWriter, r *http.Request) { st := assetsTaskState assetsTaskMu.Unlock() - go runGenerateMissingAssets() + go runGenerateMissingAssets(ctx) + + writeJSON(w, http.StatusOK, st) + return + + case http.MethodDelete: + assetsTaskMu.Lock() + cancel := assetsTaskCancel + running := assetsTaskState.Running + assetsTaskMu.Unlock() + + if !running || cancel == nil { + // nichts zu stoppen + w.WriteHeader(http.StatusNoContent) + return + } + + cancel() + + // optional: sofortiges Feedback in state.error + assetsTaskMu.Lock() + if assetsTaskState.Running { + assetsTaskState.Error = "abgebrochen" + } + st := assetsTaskState + assetsTaskMu.Unlock() writeJSON(w, http.StatusOK, st) return @@ -1529,7 +2851,7 @@ func tasksGenerateAssets(w http.ResponseWriter, r *http.Request) { } } -func runGenerateMissingAssets() { +func runGenerateMissingAssets(ctx context.Context) { finishWithErr := func(err error) { now := time.Now() assetsTaskMu.Lock() @@ -1541,6 +2863,12 @@ func runGenerateMissingAssets() { assetsTaskMu.Unlock() } + defer func() { + assetsTaskMu.Lock() + assetsTaskCancel = nil + assetsTaskMu.Unlock() + }() + s := getSettings() doneAbs, err := resolvePathRelativeToApp(s.DoneDir) if err != nil || strings.TrimSpace(doneAbs) == "" { @@ -1548,33 +2876,60 @@ func runGenerateMissingAssets() { return } - entries, err := os.ReadDir(doneAbs) - if err != nil { - finishWithErr(fmt.Errorf("doneDir lesen fehlgeschlagen: %v", err)) - return - } - type item struct { name string path string } - items := make([]item, 0, len(entries)) - for _, e := range entries { - if e.IsDir() { - continue - } - name := e.Name() + + seen := map[string]struct{}{} + items := make([]item, 0, 512) + + addIfVideo := func(full string) { + name := filepath.Base(full) low := strings.ToLower(name) if strings.Contains(low, ".part") || strings.Contains(low, ".tmp") { - continue + return } ext := strings.ToLower(filepath.Ext(name)) if ext != ".mp4" && ext != ".ts" { - continue + return } - items = append(items, item{name: name, path: filepath.Join(doneAbs, name)}) + // Dedupe (falls du Files doppelt findest) + if _, ok := seen[full]; ok { + return + } + seen[full] = struct{}{} + items = append(items, item{name: name, path: full}) } + scanOneLevel := func(dir string) { + ents, err := os.ReadDir(dir) + if err != nil { + return + } + for _, e := range ents { + full := filepath.Join(dir, e.Name()) + if e.IsDir() { + sub, err := os.ReadDir(full) + if err != nil { + continue + } + for _, se := range sub { + if se.IsDir() { + continue + } + addIfVideo(filepath.Join(full, se.Name())) + } + continue + } + addIfVideo(full) + } + } + + // ✅ done + done// + done/keep + done/keep// + scanOneLevel(doneAbs) + scanOneLevel(filepath.Join(doneAbs, "keep")) + assetsTaskMu.Lock() assetsTaskState.Total = len(items) assetsTaskState.Done = 0 @@ -1585,6 +2940,10 @@ func runGenerateMissingAssets() { assetsTaskMu.Unlock() for i, it := range items { + if err := ctx.Err(); err != nil { + finishWithErr(err) // context.Canceled + return + } base := strings.TrimSuffix(it.name, filepath.Ext(it.name)) id := stripHotPrefix(base) if strings.TrimSpace(id) == "" { @@ -1616,7 +2975,34 @@ func runGenerateMissingAssets() { return err == nil && !fi.IsDir() && fi.Size() > 0 }() - if thumbOK && previewOK { + // Datei-Info (für Meta-Invaliderung) + vfi, verr := os.Stat(it.path) + if verr != nil || vfi.IsDir() || vfi.Size() <= 0 { + assetsTaskMu.Lock() + assetsTaskState.Done = i + 1 + assetsTaskMu.Unlock() + continue + } + + metaPath := filepath.Join(assetDir, "meta.json") + + // ✅ Dauer zuerst aus meta.json, sonst 1× ffprobe & meta.json schreiben + durSec := 0.0 + metaOK := false + if d, ok := readVideoMetaDuration(metaPath, vfi); ok { + durSec = d + metaOK = true + } else { + dctx, cancel := context.WithTimeout(ctx, 6*time.Second) + if d, derr := durationSecondsCached(dctx, it.path); derr == nil && d > 0 { + durSec = d + _ = writeVideoMeta(metaPath, vfi, durSec) + metaOK = true + } + cancel() + } + + if thumbOK && previewOK && metaOK { assetsTaskMu.Lock() assetsTaskState.Skipped++ assetsTaskState.Done = i + 1 @@ -1625,10 +3011,16 @@ func runGenerateMissingAssets() { } if !thumbOK { - genCtx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + genCtx, cancel := context.WithTimeout(ctx, 45*time.Second) + if err := thumbSem.Acquire(genCtx); err != nil { + cancel() + finishWithErr(err) + return + } + var t float64 = 0 - if dur, derr := durationSecondsCached(genCtx, it.path); derr == nil && dur > 0 { - t = dur * 0.5 + if durSec > 0 { + t = durSec * 0.5 } cancel() @@ -1639,6 +3031,9 @@ func runGenerateMissingAssets() { img, e1 = extractFirstFrameJPEG(it.path) } } + + thumbSem.Release() + if e1 == nil && len(img) > 0 { if err := atomicWriteFile(thumbPath, img); err == nil { assetsTaskMu.Lock() @@ -1651,11 +3046,17 @@ func runGenerateMissingAssets() { } if !previewOK { - genSem <- struct{}{} - genCtx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + genCtx, cancel := context.WithTimeout(ctx, 3*time.Minute) + if err := genSem.Acquire(genCtx); err != nil { + cancel() + finishWithErr(err) + return + } + err := generateTeaserClipsMP4(genCtx, it.path, previewPath, 1.0, 18) + + genSem.Release() cancel() - <-genSem if err == nil { assetsTaskMu.Lock() @@ -1675,6 +3076,16 @@ func runGenerateMissingAssets() { } func generateTeaserClipsMP4(ctx context.Context, srcPath, outPath string, clipLenSec float64, maxClips int) error { + return generateTeaserClipsMP4WithProgress(ctx, srcPath, outPath, clipLenSec, maxClips, nil) +} + +func generateTeaserClipsMP4WithProgress( + ctx context.Context, + srcPath, outPath string, + clipLenSec float64, + maxClips int, + onRatio func(r float64), +) error { if clipLenSec <= 0 { clipLenSec = 1 } @@ -1687,11 +3098,18 @@ func generateTeaserClipsMP4(ctx context.Context, srcPath, outPath string, clipLe // Wenn Dauer unbekannt/zu klein: einfach ab 0 ein kurzes Stück if !(dur > 0) || dur <= clipLenSec+0.2 { - return generateTeaserMP4(ctx, srcPath, outPath, 0, math.Min(8, math.Max(clipLenSec, dur))) + // hier kein großer Vorteil – trotzdem wenigstens 0..1 melden + if onRatio != nil { + onRatio(0) + } + err := generateTeaserMP4(ctx, srcPath, outPath, 0, math.Min(8, math.Max(clipLenSec, dur))) + if onRatio != nil { + onRatio(1) + } + return err } // Anzahl Clips ähnlich wie deine Frontend-"clips"-Logik: - // mind. 8, max. maxClips, aber nicht absurd groß count := int(math.Floor(dur)) if count < 8 { count = 8 @@ -1715,21 +3133,23 @@ func generateTeaserClipsMP4(ctx context.Context, srcPath, outPath string, clipLe starts = append(starts, t) } + // erwartete Output-Dauer (Concat der Clips) + expectedOutSec := float64(len(starts)) * clipLenSec + // temp schreiben -> rename (WICHTIG: temp endet auf .mp4, sonst Muxer-Error) tmp := strings.TrimSuffix(outPath, ".mp4") + ".part.mp4" args := []string{ "-y", + "-nostats", + "-progress", "pipe:1", "-hide_banner", "-loglevel", "error", } // Mehrere Inputs: gleiche Datei, aber je Clip mit eigenem -ss/-t for _, t := range starts { - // 1) erst die toleranten Input-Flags args = append(args, ffmpegInputTol...) - - // 2) dann die normalen Input-Parameter für diesen Clip args = append(args, "-ss", fmt.Sprintf("%.3f", t), "-t", fmt.Sprintf("%.3f", clipLenSec), @@ -1737,33 +3157,131 @@ func generateTeaserClipsMP4(ctx context.Context, srcPath, outPath string, clipLe ) } - // filter_complex: jedes Segment angleichen + concat + // pro Segment v+i und a+i erzeugen var fc strings.Builder for i := range starts { - // setpts: jedes Segment startet bei 0 - fmt.Fprintf(&fc, "[%d:v]scale=720:-2,setsar=1,setpts=PTS-STARTPTS,format=yuv420p[v%d];", i, i) + fmt.Fprintf(&fc, + "[%d:v]scale=720:-2,setsar=1,setpts=PTS-STARTPTS[v%d];", + i, i, + ) + fmt.Fprintf(&fc, + "[%d:a]aresample=48000,aformat=channel_layouts=stereo,asetpts=PTS-STARTPTS[a%d];", + i, i, + ) } + + // WICHTIG: interleaved! [v0][a0][v1][a1]... for i := range starts { - fmt.Fprintf(&fc, "[v%d]", i) + fmt.Fprintf(&fc, "[v%d][a%d]", i, i) } - fmt.Fprintf(&fc, "concat=n=%d:v=1:a=0[v]", len(starts)) + + fmt.Fprintf(&fc, "concat=n=%d:v=1:a=1[v][a]", len(starts)) args = append(args, "-filter_complex", fc.String(), "-map", "[v]", - "-an", + "-map", "[a]", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", + "-c:a", "aac", + "-b:a", "128k", + "-ac", "2", + "-shortest", "-movflags", "+faststart", tmp, ) cmd := exec.CommandContext(ctx, ffmpegPath, args...) - if out, err := cmd.CombinedOutput(); err != nil { + + stdout, err := cmd.StdoutPipe() + if err != nil { + return err + } + + var stderr bytes.Buffer + cmd.Stderr = &stderr + + if err := cmd.Start(); err != nil { + return err + } + + sc := bufio.NewScanner(stdout) + sc.Buffer(make([]byte, 0, 64*1024), 1024*1024) + + var lastSent float64 + var lastAt time.Time + + send := func(outSec float64, force bool) { + if onRatio == nil { + return + } + + if expectedOutSec > 0 && outSec > 0 { + r := outSec / expectedOutSec + if r < 0 { + r = 0 + } + if r > 1 { + r = 1 + } + + // throttle + if r-lastSent < 0.01 && !force { + return + } + if !lastAt.IsZero() && time.Since(lastAt) < 150*time.Millisecond && !force { + return + } + + lastSent = r + lastAt = time.Now() + onRatio(r) + return + } + + if force { + onRatio(1) + } + } + + var outSec float64 + + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" { + continue + } + parts := strings.SplitN(line, "=", 2) + if len(parts) != 2 { + continue + } + k := parts[0] + v := parts[1] + + switch k { + case "out_time_ms": + // ffmpeg liefert hier Mikrosekunden (trotz Name) + if n, perr := strconv.ParseInt(strings.TrimSpace(v), 10, 64); perr == nil && n > 0 { + outSec = float64(n) / 1_000_000.0 + send(outSec, false) + } + case "out_time": + if s := parseFFmpegOutTime(v); s > 0 { + outSec = s + send(outSec, false) + } + case "progress": + if strings.TrimSpace(v) == "end" { + send(outSec, true) + } + } + } + + if err := cmd.Wait(); err != nil { _ = os.Remove(tmp) - return fmt.Errorf("ffmpeg teaser clips failed: %v (%s)", err, strings.TrimSpace(string(out))) + return fmt.Errorf("ffmpeg teaser clips failed: %v (%s)", err, strings.TrimSpace(stderr.String())) } _ = os.Remove(outPath) @@ -1840,6 +3358,26 @@ func servePreviewJPEGBytes(w http.ResponseWriter, img []byte) { _, _ = w.Write(img) } +func servePreviewJPEGBytesNoStore(w http.ResponseWriter, img []byte) { + w.Header().Set("Content-Type", "image/jpeg") + w.Header().Set("Cache-Control", "no-store, max-age=0") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Expires", "0") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(img) +} + +func serveLivePreviewJPEGBytes(w http.ResponseWriter, img []byte) { + w.Header().Set("Content-Type", "image/jpeg") + w.Header().Set("Cache-Control", "no-store, max-age=0, must-revalidate") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Expires", "0") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(img) +} + func servePreviewJPEGFile(w http.ResponseWriter, r *http.Request, path string) { w.Header().Set("Content-Type", "image/jpeg") w.Header().Set("Cache-Control", "public, max-age=31536000") @@ -1856,6 +3394,10 @@ func recordList(w http.ResponseWriter, r *http.Request) { jobsMu.Lock() list := make([]*RecordJob, 0, len(jobs)) for _, j := range jobs { + // ✅ NEU: Hidden (und nil) nicht ausgeben -> UI sieht Probe-Jobs nicht + if j == nil || j.Hidden { + continue + } list = append(list, j) } jobsMu.Unlock() @@ -1872,6 +3414,31 @@ func recordList(w http.ResponseWriter, r *http.Request) { var previewFileRe = regexp.MustCompile(`^(index(_hq)?\.m3u8|seg_(low|hq)_\d+\.ts|seg_\d+\.ts)$`) +func serveEmptyLiveM3U8(w http.ResponseWriter, r *http.Request) { + // Für Player: gültige Playlist statt 204 liefern + w.Header().Set("Content-Type", "application/vnd.apple.mpegurl; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + // Optional: Player/Proxy darf schnell retryen + w.Header().Set("Retry-After", "1") + + // Bei HEAD nur Header schicken + if r.Method == http.MethodHead { + w.WriteHeader(http.StatusOK) + return + } + + // Minimal gültige LIVE-Playlist (keine Segmente, kein ENDLIST) + // Viele Player bleiben damit im "loading", statt hart zu failen. + body := "#EXTM3U\n" + + "#EXT-X-VERSION:3\n" + + "#EXT-X-TARGETDURATION:2\n" + + "#EXT-X-MEDIA-SEQUENCE:0\n" + + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(body)) +} + func servePreviewHLSFile(w http.ResponseWriter, r *http.Request, id, file string) { file = strings.TrimSpace(file) if file == "" || filepath.Base(file) != file || !previewFileRe.MatchString(file) { @@ -1883,7 +3450,23 @@ func servePreviewHLSFile(w http.ResponseWriter, r *http.Request, id, file string jobsMu.Lock() job, ok := jobs[id] + state := "" + if ok { + state = strings.TrimSpace(job.PreviewState) + } jobsMu.Unlock() + + if ok { + if state == "private" { + http.Error(w, "model private", http.StatusForbidden) + return + } + if state == "offline" { + http.Error(w, "model offline", http.StatusNotFound) + return + } + } + if !ok { // Job wirklich unbekannt => 404 ist ok http.Error(w, "job nicht gefunden", http.StatusNotFound) @@ -1893,8 +3476,7 @@ func servePreviewHLSFile(w http.ResponseWriter, r *http.Request, id, file string // Preview noch nicht initialisiert? Für index => 204 (kein roter Fehler im Browser) if strings.TrimSpace(job.PreviewDir) == "" { if isIndex { - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(http.StatusNoContent) + serveEmptyLiveM3U8(w, r) return } http.Error(w, "preview nicht verfügbar", http.StatusNotFound) @@ -1904,8 +3486,7 @@ func servePreviewHLSFile(w http.ResponseWriter, r *http.Request, id, file string p := filepath.Join(job.PreviewDir, file) if _, err := os.Stat(p); err != nil { if isIndex { - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(http.StatusNoContent) + serveEmptyLiveM3U8(w, r) return } http.Error(w, "datei nicht gefunden", http.StatusNotFound) @@ -1940,7 +3521,50 @@ func rewriteM3U8ToPreviewEndpoint(m3u8 string, id string) string { return strings.Join(lines, "\n") } -func startPreviewHLS(ctx context.Context, jobID, m3u8URL, previewDir, httpCookie, userAgent string) error { +func classifyPreviewFFmpegStderr(stderr string) (state string, httpStatus int) { + s := strings.ToLower(stderr) + + // ffmpeg schreibt typischerweise: + // "HTTP error 403 Forbidden" oder "Server returned 403 Forbidden" + if strings.Contains(s, "403 forbidden") || strings.Contains(s, "http error 403") || strings.Contains(s, "server returned 403") { + return "private", http.StatusForbidden + } + + // "HTTP error 404 Not Found" oder "Server returned 404 Not Found" + if strings.Contains(s, "404 not found") || strings.Contains(s, "http error 404") || strings.Contains(s, "server returned 404") { + return "offline", http.StatusNotFound + } + + return "", 0 +} + +func servePreviewStatusSVG(w http.ResponseWriter, label string) { + w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + + txt := html.EscapeString(label) + + svg := ` + + + + + + + + + + + ` + txt + ` + Preview nicht verfügbar +` + + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(svg)) +} + +func startPreviewHLS(ctx context.Context, job *RecordJob, m3u8URL, previewDir, httpCookie, userAgent string) error { if strings.TrimSpace(ffmpegPath) == "" { return fmt.Errorf("kein ffmpeg gefunden – setze FFMPEG_PATH oder lege ffmpeg(.exe) neben das Backend") } @@ -1949,6 +3573,13 @@ func startPreviewHLS(ctx context.Context, jobID, m3u8URL, previewDir, httpCookie return err } + // ✅ PreviewState reset (neuer Start) + jobsMu.Lock() + job.PreviewState = "" + job.PreviewStateAt = "" + job.PreviewStateMsg = "" + jobsMu.Unlock() + commonIn := []string{"-y"} if strings.TrimSpace(userAgent) != "" { commonIn = append(commonIn, "-user_agent", userAgent) @@ -1958,33 +3589,83 @@ func startPreviewHLS(ctx context.Context, jobID, m3u8URL, previewDir, httpCookie } commonIn = append(commonIn, "-i", m3u8URL) - baseURL := fmt.Sprintf("/api/record/preview?id=%s&file=", url.QueryEscape(jobID)) + baseURL := fmt.Sprintf("/api/record/preview?id=%s&file=", url.QueryEscape(job.ID)) - // ✅ Nur EIN Preview-Transcode pro Job (sonst wird es bei vielen Downloads sehr teuer). - // Wir nutzen das HQ-Playlist-Format (index_hq.m3u8), aber skalieren etwas kleiner. hqArgs := append(commonIn, "-vf", "scale=480:-2", "-c:v", "libx264", "-preset", "veryfast", "-tune", "zerolatency", + "-pix_fmt", "yuv420p", + "-profile:v", "main", + "-level", "3.1", + "-threads", "1", "-g", "48", "-keyint_min", "48", "-sc_threshold", "0", + "-map", "0:v:0", + "-map", "0:a?", "-c:a", "aac", "-b:a", "128k", "-ac", "2", "-f", "hls", "-hls_time", "2", - "-hls_list_size", "4", + "-hls_list_size", "10", + "-hls_delete_threshold", "20", + "-hls_allow_cache", "0", "-hls_flags", "delete_segments+append_list+independent_segments", "-hls_segment_filename", filepath.Join(previewDir, "seg_hq_%05d.ts"), "-hls_base_url", baseURL, filepath.Join(previewDir, "index_hq.m3u8"), ) - // Preview-Prozess starten (einfach & robust) - go func(kind string, args []string) { - cmd := exec.CommandContext(ctx, ffmpegPath, args...) - var stderr bytes.Buffer - cmd.Stderr = &stderr - if err := cmd.Run(); err != nil && ctx.Err() == nil { - fmt.Printf("⚠️ preview %s ffmpeg failed: %v (%s)\n", kind, err, strings.TrimSpace(stderr.String())) + cmd := exec.CommandContext(ctx, ffmpegPath, hqArgs...) + var stderr bytes.Buffer + cmd.Stderr = &stderr + + jobsMu.Lock() + job.previewCmd = cmd + jobsMu.Unlock() + + go func() { + if err := previewSem.Acquire(ctx); err != nil { + jobsMu.Lock() + if job.previewCmd == cmd { + job.previewCmd = nil + } + jobsMu.Unlock() + return } - }("hq", hqArgs) + defer previewSem.Release() + + if err := cmd.Run(); err != nil && ctx.Err() == nil { + st := strings.TrimSpace(stderr.String()) + + // ✅ 403/404 erkennen -> Private/Offline setzen + state, code := classifyPreviewFFmpegStderr(st) + + jobsMu.Lock() + if state != "" { + job.PreviewState = state + job.PreviewStateAt = time.Now().UTC().Format(time.RFC3339Nano) + job.PreviewStateMsg = fmt.Sprintf("ffmpeg input returned HTTP %d", code) + } else { + job.PreviewState = "error" + job.PreviewStateAt = time.Now().UTC().Format(time.RFC3339Nano) + if len(st) > 280 { + job.PreviewStateMsg = st[:280] + "…" + } else { + job.PreviewStateMsg = st + } + } + jobsMu.Unlock() + + fmt.Printf("⚠️ preview hq ffmpeg failed: %v (%s)\n", err, st) + } + + jobsMu.Lock() + if job.previewCmd == cmd { + job.previewCmd = nil + } + jobsMu.Unlock() + }() + + // ✅ Live thumb writer starten (schreibt generated//thumbs.jpg regelmäßig neu) + startLiveThumbLoop(ctx, job) return nil } @@ -2128,6 +3809,13 @@ func registerFrontend(mux *http.ServeMux) { func registerRoutes(mux *http.ServeMux) *ModelStore { mux.HandleFunc("/api/cookies", cookiesHandler) + mux.HandleFunc("/api/perf/stream", perfStreamHandler) + + mux.HandleFunc("/api/autostart/state", autostartStateHandler) + mux.HandleFunc("/api/autostart/state/stream", autostartStateStreamHandler) + mux.HandleFunc("/api/autostart/pause", autostartPauseQuickHandler) + mux.HandleFunc("/api/autostart/resume", autostartResumeHandler) + mux.HandleFunc("/api/settings", recordSettingsHandler) mux.HandleFunc("/api/settings/browse", settingsBrowse) @@ -2145,6 +3833,7 @@ func registerRoutes(mux *http.ServeMux) *ModelStore { mux.HandleFunc("/api/record/keep", recordKeepVideo) mux.HandleFunc("/api/chaturbate/online", chaturbateOnlineHandler) + mux.HandleFunc("/api/chaturbate/biocontext", chaturbateBioContextHandler) mux.HandleFunc("/api/generated/teaser", generatedTeaser) // Tasks @@ -2161,6 +3850,9 @@ func registerRoutes(mux *http.ServeMux) *ModelStore { // ✅ registriert /api/models/list, /parse, /upsert, /flags, /delete RegisterModelAPI(mux, store) + // ✅ ModelStore auch für Chaturbate-Online/biocontext nutzen (Tags/Bio persistieren) + setChaturbateOnlineModelStore(store) + // ✅ Frontend (SPA) ausliefern registerFrontend(mux) @@ -2174,8 +3866,10 @@ func main() { mux := http.NewServeMux() store := registerRoutes(mux) - go startChaturbateOnlinePoller() // ✅ hält Online-Liste aktuell + go startChaturbateOnlinePoller(store) // ✅ hält Online-Liste aktuell go startChaturbateAutoStartWorker(store) // ✅ startet watched+public automatisch + go startMyFreeCamsAutoStartWorker(store) + go startDiskSpaceGuard() // ✅ reagiert auch ohne Frontend fmt.Println("🌐 HTTP-API aktiv: http://localhost:9999") if err := http.ListenAndServe(":9999", mux); err != nil { @@ -2188,6 +3882,43 @@ type RecordRequest struct { URL string `json:"url"` Cookie string `json:"cookie,omitempty"` UserAgent string `json:"userAgent,omitempty"` + Hidden bool `json:"hidden,omitempty"` +} + +type videoMeta struct { + SizeBytes int64 `json:"sizeBytes"` + ModTimeUnix int64 `json:"modTimeUnix"` + DurationSeconds float64 `json:"durationSeconds"` +} + +func readVideoMeta(metaPath string) (videoMeta, bool) { + b, err := os.ReadFile(metaPath) + if err != nil || len(b) == 0 { + return videoMeta{}, false + } + var m videoMeta + if json.Unmarshal(b, &m) != nil { + return videoMeta{}, false + } + if m.SizeBytes <= 0 || m.ModTimeUnix <= 0 || m.DurationSeconds <= 0 { + return videoMeta{}, false + } + return m, true +} + +func durationFromMetaIfFresh(videoPath, assetDir string, fi os.FileInfo) (float64, bool) { + metaPath := filepath.Join(assetDir, "meta.json") + m, ok := readVideoMeta(metaPath) + if !ok { + return 0, false + } + if m.SizeBytes != fi.Size() { + return 0, false + } + if m.ModTimeUnix != fi.ModTime().Unix() { + return 0, false + } + return m.DurationSeconds, true } // shared: wird vom HTTP-Handler UND vom Autostart-Worker genutzt @@ -2201,11 +3932,48 @@ func startRecordingInternal(req RecordRequest) (*RecordJob, error) { jobsMu.Lock() for _, j := range jobs { if j != nil && j.Status == JobRunning && strings.TrimSpace(j.SourceURL) == url { + // ✅ Wenn ein versteckter Auto-Check-Job läuft und der User manuell startet -> sofort sichtbar machen + if j.Hidden && !req.Hidden { + j.Hidden = false + jobsMu.Unlock() + + notifyJobsChanged() + return j, nil + } + jobsMu.Unlock() return j, nil } } + // ✅ Timestamp + Output schon hier setzen, damit UI sofort Model/Filename/Details hat + startedAt := time.Now() + provider := detectProvider(url) + + // best-effort Username aus URL + username := "" + switch provider { + case "chaturbate": + username = extractUsername(url) + case "mfc": + username = extractMFCUsername(url) + } + if strings.TrimSpace(username) == "" { + username = "unknown" + } + + // Dateiname (konsistent zu runJob: gleicher Timestamp) + filename := fmt.Sprintf("%s_%s.ts", username, startedAt.Format("01_02_2006__15-04-05")) + + // best-effort: absoluter RecordDir (fallback auf Settings-Wert) + s := getSettings() + recordDirAbs, _ := resolvePathRelativeToApp(s.RecordDir) + recordDir := strings.TrimSpace(recordDirAbs) + if recordDir == "" { + recordDir = strings.TrimSpace(s.RecordDir) + } + outPath := filepath.Join(recordDir, filename) + jobID := uuid.NewString() ctx, cancel := context.WithCancel(context.Background()) @@ -2213,14 +3981,19 @@ func startRecordingInternal(req RecordRequest) (*RecordJob, error) { ID: jobID, SourceURL: url, Status: JobRunning, - StartedAt: time.Now(), + StartedAt: startedAt, + Output: outPath, // ✅ sofort befüllt + Hidden: req.Hidden, // ✅ NEU cancel: cancel, } jobs[jobID] = job jobsMu.Unlock() - notifyJobsChanged() + // ✅ NEU: Hidden-Jobs nicht sofort ins UI broadcasten + if !job.Hidden { + notifyJobsChanged() + } go runJob(ctx, job, req) return job, nil @@ -2279,7 +4052,11 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { provider := detectProvider(req.URL) var err error - now := time.Now() + // ✅ nutze den Timestamp vom Job (damit Start/Output konsistent sind) + now := job.StartedAt + if now.IsZero() { + now = time.Now() + } // ---- Aufnahme starten (Output-Pfad sauber relativ zur EXE auflösen) ---- switch provider { @@ -2299,13 +4076,24 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { username := extractUsername(req.URL) filename := fmt.Sprintf("%s_%s.ts", username, now.Format("01_02_2006__15-04-05")) - outPath := filepath.Join(recordDirAbs, filename) - // Output setzen (kurz locken) + // ✅ wenn Output schon beim Start gesetzt wurde, nutze ihn (falls absolut) jobsMu.Lock() - job.Output = outPath + existingOut := strings.TrimSpace(job.Output) jobsMu.Unlock() - notifyJobsChanged() + + outPath := existingOut + if outPath == "" || !filepath.IsAbs(outPath) { + outPath = filepath.Join(recordDirAbs, filename) + } + + // Output nur aktualisieren, wenn es sich ändert + if strings.TrimSpace(existingOut) != strings.TrimSpace(outPath) { + jobsMu.Lock() + job.Output = outPath + jobsMu.Unlock() + notifyJobsChanged() + } err = RecordStream(ctx, hc, "https://chaturbate.com/", username, outPath, req.Cookie, job) @@ -2325,6 +4113,7 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { jobsMu.Lock() job.Output = outPath jobsMu.Unlock() + notifyJobsChanged() err = RecordStreamMFC(ctx, hc, username, outPath, job) @@ -2356,113 +4145,333 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { // Output lokal kopieren, damit wir ohne lock weiterarbeiten können out := strings.TrimSpace(job.Output) jobsMu.Unlock() + notifyJobsChanged() // Falls Output fehlt (z.B. provider error), direkt final status setzen if out == "" { - setJobPhase(job, "finalizing", 95) jobsMu.Lock() job.Status = target job.Phase = "" job.Progress = 100 jobsMu.Unlock() + notifyJobsChanged() return } - // 1) Remux (auch bei STOP/FAILED best-effort) - setJobPhase(job, "remuxing", 45) - if newOut, err2 := maybeRemuxTS(out); err2 == nil && strings.TrimSpace(newOut) != "" { - out = strings.TrimSpace(newOut) - jobsMu.Lock() - job.Output = out - jobsMu.Unlock() + // 1) Remux (nur wenn TS) + if strings.EqualFold(filepath.Ext(out), ".ts") { + setJobPhase(job, "remuxing", 10) + if newOut, err2 := maybeRemuxTSForJob(job, out); err2 == nil && strings.TrimSpace(newOut) != "" { + out = strings.TrimSpace(newOut) + jobsMu.Lock() + job.Output = out + jobsMu.Unlock() + notifyJobsChanged() + } } // 2) Move to done (best-effort) - setJobPhase(job, "moving", 80) + setJobPhase(job, "moving", 70) if moved, err2 := moveToDoneDir(out); err2 == nil && strings.TrimSpace(moved) != "" { out = strings.TrimSpace(moved) jobsMu.Lock() job.Output = out jobsMu.Unlock() + notifyJobsChanged() + } + setJobPhase(job, "moving", 80) + + // ✅ Optional: kleine Downloads automatisch löschen (nach move, vor ffprobe/assets) + if target == JobFinished || target == JobStopped { + if fi, serr := os.Stat(out); serr == nil && fi != nil && !fi.IsDir() { + // SizeBytes am Job speichern (praktisch fürs UI) + jobsMu.Lock() + job.SizeBytes = fi.Size() + jobsMu.Unlock() + notifyJobsChanged() + + s := getSettings() + minMB := s.AutoDeleteSmallDownloadsBelowMB + if s.AutoDeleteSmallDownloads && minMB > 0 { + threshold := int64(minMB) * 1024 * 1024 + if fi.Size() > 0 && fi.Size() < threshold { + + base := filepath.Base(out) + id := stripHotPrefix(strings.TrimSuffix(base, filepath.Ext(base))) + + // Datei löschen (mit Windows file-lock retry) + if derr := removeWithRetry(out); derr == nil || os.IsNotExist(derr) { + // generated/ + legacy cleanup (best-effort) + removeGeneratedForID(id) + if doneAbs, rerr := resolvePathRelativeToApp(getSettings().DoneDir); rerr == nil && strings.TrimSpace(doneAbs) != "" { + _ = os.RemoveAll(filepath.Join(doneAbs, "preview", id)) + _ = os.RemoveAll(filepath.Join(doneAbs, "thumbs", id)) + } + purgeDurationCacheForPath(out) + + // Job entfernen, damit er nicht im Finished landet + jobsMu.Lock() + delete(jobs, job.ID) + jobsMu.Unlock() + notifyJobsChanged() + + fmt.Println("🧹 auto-deleted:", base, "size:", formatBytesSI(fi.Size())) + return + } else { + fmt.Println("⚠️ auto-delete failed:", derr) + } + } + } + } } - // 3) Finalize - setJobPhase(job, "finalizing", 95) + // ✅ NEU: Dauer einmalig zuverlässig bestimmen (ffprobe) und am Job speichern + if target == JobFinished || target == JobStopped { + dctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + if sec, derr := durationSecondsCached(dctx, out); derr == nil && sec > 0 { + jobsMu.Lock() + job.DurationSeconds = sec + jobsMu.Unlock() + notifyJobsChanged() + } + cancel() + } - // Jetzt erst finalen Status setzen + // 3) Assets (thumbs.jpg + preview.mp4) mit Live-Progress + // Nur wenn Finished oder Stopped (bei Failed skip) + if target == JobFinished || target == JobStopped { + const ( + assetsStart = 86 + assetsEnd = 99 + ) + + setJobPhase(job, "assets", assetsStart) + + // Throttle damit UI nicht bei jedem ffmpeg-tick spammt + lastPct := -1 + lastTick := time.Time{} + + update := func(r float64) { + if r < 0 { + r = 0 + } + if r > 1 { + r = 1 + } + + pct := assetsStart + int(math.Round(r*float64(assetsEnd-assetsStart))) + if pct < assetsStart { + pct = assetsStart + } + if pct > assetsEnd { + pct = assetsEnd + } + + if pct == lastPct { + return + } + if !lastTick.IsZero() && time.Since(lastTick) < 150*time.Millisecond { + return + } + + lastPct = pct + lastTick = time.Now() + setJobPhase(job, "assets", pct) + } + + // best-effort: Job NICHT failen, nur loggen + if err := ensureAssetsForVideoWithProgress(out, update); err != nil { + fmt.Println("⚠️ ensureAssetsForVideo:", err) + } + + setJobPhase(job, "assets", assetsEnd) + } + + // 4) Finalize (erst jetzt endgültigen Status setzen) jobsMu.Lock() job.Status = target job.Phase = "" job.Progress = 100 - finalOut := strings.TrimSpace(job.Output) - finalStatus := job.Status jobsMu.Unlock() notifyJobsChanged() +} - // ---- Nach Abschluss Assets erzeugen (Preview + Teaser) ---- - // nur bei Finished/Stopped, und nur wenn die Datei existiert - if finalOut != "" && (finalStatus == JobFinished || finalStatus == JobStopped) { - go func(videoPath string) { - fi, statErr := os.Stat(videoPath) - if statErr != nil || fi.IsDir() || fi.Size() <= 0 { - return - } - - // ✅ ID = Dateiname ohne Endung (immer OHNE "HOT " Prefix) - base := filepath.Base(videoPath) - id := strings.TrimSuffix(base, filepath.Ext(base)) - id = stripHotPrefix(id) - if id == "" { - return - } - - // ✅ /generated//thumbs.jpg + /generated//preview.mp4 - assetDir, gerr := ensureGeneratedDir(id) - if gerr != nil || strings.TrimSpace(assetDir) == "" { - fmt.Println("⚠️ generated dir:", gerr) - return - } - - thumbPath := filepath.Join(assetDir, "thumbs.jpg") - if tfi, err := os.Stat(thumbPath); err != nil || tfi.IsDir() || tfi.Size() <= 0 { - genCtx, cancel := context.WithTimeout(context.Background(), 45*time.Second) - defer cancel() - - t := 0.0 - if dur, derr := durationSecondsCached(genCtx, videoPath); derr == nil && dur > 0 { - t = dur * 0.5 - } - - img, e1 := extractFrameAtTimeJPEG(videoPath, t) - if e1 != nil || len(img) == 0 { - img, e1 = extractLastFrameJPEG(videoPath) - if e1 != nil || len(img) == 0 { - img, e1 = extractFirstFrameJPEG(videoPath) - } - } - - if e1 == nil && len(img) > 0 { - if err := atomicWriteFile(thumbPath, img); err != nil { - fmt.Println("⚠️ thumb write:", err) - } - } - } - - previewPath := filepath.Join(assetDir, "preview.mp4") - if tfi, err := os.Stat(previewPath); err != nil || tfi.IsDir() || tfi.Size() <= 0 { - genSem <- struct{}{} - defer func() { <-genSem }() - - genCtx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) - defer cancel() - - if err := generateTeaserClipsMP4(genCtx, videoPath, previewPath, 1.0, 18); err != nil { - fmt.Println("⚠️ preview clips:", err) - } - } - }(finalOut) - +func formatBytesSI(b int64) string { + if b < 0 { + b = 0 } + const unit = 1024 + if b < unit { + return fmt.Sprintf("%d B", b) + } + div, exp := int64(unit), 0 + for n := b / unit; n >= unit; n /= unit { + div *= unit + exp++ + } + suffix := []string{"KB", "MB", "GB", "TB", "PB"} + v := float64(b) / float64(div) + // 1 Nachkommastelle, außer sehr große ganze Zahlen + if v >= 10 { + return fmt.Sprintf("%.0f %s", v, suffix[exp]) + } + return fmt.Sprintf("%.1f %s", v, suffix[exp]) +} + +func ensureAssetsForVideo(videoPath string) error { + return ensureAssetsForVideoWithProgress(videoPath, nil) +} + +// onRatio: 0..1 (Assets-Gesamtfortschritt) +func ensureAssetsForVideoWithProgress(videoPath string, onRatio func(r float64)) error { + videoPath = strings.TrimSpace(videoPath) + if videoPath == "" { + return nil + } + + fi, statErr := os.Stat(videoPath) + if statErr != nil || fi.IsDir() || fi.Size() <= 0 { + return nil + } + + // ✅ ID = Dateiname ohne Endung (immer OHNE "HOT " Prefix) + base := filepath.Base(videoPath) + id := strings.TrimSuffix(base, filepath.Ext(base)) + id = stripHotPrefix(id) + if strings.TrimSpace(id) == "" { + return nil + } + + // ✅ /generated//thumbs.jpg + /generated//preview.mp4 + assetDir, gerr := ensureGeneratedDir(id) + if gerr != nil || strings.TrimSpace(assetDir) == "" { + return fmt.Errorf("generated dir: %v", gerr) + } + + metaPath := filepath.Join(assetDir, "meta.json") + + // Dauer bevorzugt aus meta.json (schnell & stabil) + durSec := 0.0 + if d, ok := readVideoMetaDuration(metaPath, fi); ok { + durSec = d + } else { + // Fallback: 1× ffprobe über durationSecondsCached (und dann persistieren) + dctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + if d, derr := durationSecondsCached(dctx, videoPath); derr == nil && d > 0 { + durSec = d + _ = writeVideoMeta(metaPath, fi, durSec) + } + cancel() + } + + // Gewichte: thumbs klein, preview groß (preview dauert) + const ( + thumbsW = 0.25 + previewW = 0.75 + ) + + progress := func(r float64) { + if onRatio == nil { + return + } + if r < 0 { + r = 0 + } + if r > 1 { + r = 1 + } + onRatio(r) + } + + progress(0) + + // ---------------- + // Thumbs erzeugen + // ---------------- + thumbPath := filepath.Join(assetDir, "thumbs.jpg") + if tfi, err := os.Stat(thumbPath); err == nil && !tfi.IsDir() && tfi.Size() > 0 { + progress(thumbsW) + } else { + progress(0.05) + + genCtx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + + if err := thumbSem.Acquire(genCtx); err != nil { + // best-effort + progress(thumbsW) + goto PREVIEW + } + defer thumbSem.Release() + + progress(0.10) + + t := 0.0 + if durSec > 0 { + t = durSec * 0.5 + } + + progress(0.15) + + img, e1 := extractFrameAtTimeJPEG(videoPath, t) + if e1 != nil || len(img) == 0 { + img, e1 = extractLastFrameJPEG(videoPath) + if e1 != nil || len(img) == 0 { + img, e1 = extractFirstFrameJPEG(videoPath) + } + } + + progress(0.20) + + if e1 == nil && len(img) > 0 { + if err := atomicWriteFile(thumbPath, img); err != nil { + fmt.Println("⚠️ thumb write:", err) + } + } + + progress(thumbsW) + } + +PREVIEW: + // ---------------- + // Preview erzeugen + // ---------------- + previewPath := filepath.Join(assetDir, "preview.mp4") + if pfi, err := os.Stat(previewPath); err == nil && !pfi.IsDir() && pfi.Size() > 0 { + progress(1) + return nil + } + + // Preview ist der teure Part -> hier Live-Progress durchreichen + genCtx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + + progress(thumbsW + 0.02) + + if err := genSem.Acquire(genCtx); err != nil { + // best-effort + progress(1) + return nil + } + defer genSem.Release() + + progress(thumbsW + 0.05) + + if err := generateTeaserClipsMP4WithProgress(genCtx, videoPath, previewPath, 1.0, 18, func(r float64) { + // r 0..1 nur für preview -> mappe in Gesamtfortschritt + if r < 0 { + r = 0 + } + if r > 1 { + r = 1 + } + progress(thumbsW + r*previewW) + }); err != nil { + fmt.Println("⚠️ preview clips:", err) + } + + progress(1) + return nil } func recordVideo(w http.ResponseWriter, r *http.Request) { @@ -2503,29 +4512,35 @@ func recordVideo(w http.ResponseWriter, r *http.Request) { return } - // Kandidaten: erst doneDir, dann recordDir - candidates := []string{ - filepath.Join(doneAbs, file), - filepath.Join(recordAbs, file), - } + // Kandidaten: erst done (inkl. 1 Level Subdir, aber ohne "keep"), + // dann keep (inkl. 1 Level Subdir), dann recordDir + names := []string{file} // Falls UI noch ".ts" kennt, die Datei aber schon als ".mp4" existiert: if ext == ".ts" { mp4File := strings.TrimSuffix(file, ext) + ".mp4" - candidates = append(candidates, - filepath.Join(doneAbs, mp4File), - filepath.Join(recordAbs, mp4File), - ) + names = append(names, mp4File) } var outPath string - for _, p := range candidates { - fi, err := os.Stat(p) - if err == nil && !fi.IsDir() && fi.Size() > 0 { + for _, name := range names { + // done root + done// (skip "keep") + if p, _, ok := findFileInDirOrOneLevelSubdirs(doneAbs, name, "keep"); ok { + outPath = p + break + } + // keep root + keep// + if p, _, ok := findFileInDirOrOneLevelSubdirs(filepath.Join(doneAbs, "keep"), name, ""); ok { + outPath = p + break + } + // record root (+ optional 1 Level Subdir) + if p, _, ok := findFileInDirOrOneLevelSubdirs(recordAbs, name, ""); ok { outPath = p break } } + if outPath == "" { http.Error(w, "datei nicht gefunden", http.StatusNotFound) return @@ -2616,6 +4631,13 @@ func recordVideo(w http.ResponseWriter, r *http.Request) { serveVideoFile(w, r, outPath) } +func setNoStoreHeaders(w http.ResponseWriter) { + // verhindert Browser/Proxy Caching (wichtig für Logs/Status) + w.Header().Set("Cache-Control", "no-store, max-age=0") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Expires", "0") +} + func durationSecondsCacheOnly(path string, fi os.FileInfo) float64 { durCache.mu.Lock() e, ok := durCache.m[path] @@ -2627,12 +4649,59 @@ func durationSecondsCacheOnly(path string, fi os.FileInfo) float64 { return 0 } +func findFileInDirOrOneLevelSubdirs(root string, file string, skipDirName string) (string, os.FileInfo, bool) { + // direct + p := filepath.Join(root, file) + if fi, err := os.Stat(p); err == nil && !fi.IsDir() && fi.Size() > 0 { + return p, fi, true + } + + entries, err := os.ReadDir(root) + if err != nil { + return "", nil, false + } + + for _, e := range entries { + if !e.IsDir() { + continue + } + if skipDirName != "" && e.Name() == skipDirName { + continue + } + pp := filepath.Join(root, e.Name(), file) + if fi, err := os.Stat(pp); err == nil && !fi.IsDir() && fi.Size() > 0 { + return pp, fi, true + } + } + + return "", nil, false +} + +func resolveDoneFileByName(doneAbs string, file string) (full string, from string, fi os.FileInfo, err error) { + // 1) done (root + /done//) — "keep" wird übersprungen + if p, fi, ok := findFileInDirOrOneLevelSubdirs(doneAbs, file, "keep"); ok { + return p, "done", fi, nil + } + + // 2) keep (root + /done/keep//) + keepDir := filepath.Join(doneAbs, "keep") + if p, fi, ok := findFileInDirOrOneLevelSubdirs(keepDir, file, ""); ok { + return p, "keep", fi, nil + } + + return "", "", nil, fmt.Errorf("not found") +} + func recordDoneList(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "Nur GET erlaubt", http.StatusMethodNotAllowed) return } + // ✅ optional: auch /done/keep/ einbeziehen (Standard: false) + qKeep := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("includeKeep"))) + includeKeep := qKeep == "1" || qKeep == "true" || qKeep == "yes" + // optional: Pagination (1-based). Wenn page/pageSize fehlen -> wie vorher: komplette Liste page := 0 pageSize := 0 @@ -2647,13 +4716,21 @@ func recordDoneList(w http.ResponseWriter, r *http.Request) { } } - // optional: Sort (für später) + // optional: Sort // supported: completed_(asc|desc), model_(asc|desc), file_(asc|desc), duration_(asc|desc), size_(asc|desc) sortMode := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("sort"))) if sortMode == "" { sortMode = "completed_desc" } + // ✅ NEU: all=1 -> immer komplette Liste zurückgeben (Pagination deaktivieren) + qAll := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("all"))) + fetchAll := qAll == "1" || qAll == "true" || qAll == "yes" + if fetchAll { + page = 0 + pageSize = 0 + } + s := getSettings() doneAbs, err := resolvePathRelativeToApp(s.DoneDir) if err != nil { @@ -2669,17 +4746,125 @@ func recordDoneList(w http.ResponseWriter, r *http.Request) { return } - entries, err := os.ReadDir(doneAbs) - if err != nil { - // Wenn Verzeichnis nicht existiert → leere Liste statt 500 - if os.IsNotExist(err) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - _ = json.NewEncoder(w).Encode([]*RecordJob{}) + type scanDir struct { + dir string + skipKeep bool // nur für doneAbs: "keep" nicht doppelt scannen + } + + dirs := []scanDir{{dir: doneAbs, skipKeep: true}} + if includeKeep { + dirs = append(dirs, scanDir{dir: filepath.Join(doneAbs, "keep"), skipKeep: false}) + } + + list := make([]*RecordJob, 0, 256) + + addFile := func(full string, fi os.FileInfo) { + name := filepath.Base(full) + ext := strings.ToLower(filepath.Ext(name)) + if ext != ".mp4" && ext != ".ts" { return } - http.Error(w, "doneDir lesen fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) - return + + base := strings.TrimSuffix(name, filepath.Ext(name)) + t := fi.ModTime() + + // StartedAt aus Dateiname (Fallback: ModTime) + start := t + stem := base + if strings.HasPrefix(stem, "HOT ") { + stem = strings.TrimPrefix(stem, "HOT ") + } + if m := startedAtFromFilenameRe.FindStringSubmatch(stem); m != nil { + mm, _ := strconv.Atoi(m[2]) + dd, _ := strconv.Atoi(m[3]) + yy, _ := strconv.Atoi(m[4]) + hh, _ := strconv.Atoi(m[5]) + mi, _ := strconv.Atoi(m[6]) + ss, _ := strconv.Atoi(m[7]) + start = time.Date(yy, time.Month(mm), dd, hh, mi, ss, 0, time.Local) + } + + dur := 0.0 + + // 1) meta.json aus generated//meta.json lesen (schnell) + id := stripHotPrefix(strings.TrimSuffix(filepath.Base(full), filepath.Ext(full))) + if strings.TrimSpace(id) != "" { + if mp, err := generatedMetaFile(id); err == nil { + if d, ok := readVideoMetaDuration(mp, fi); ok { + dur = d + } + } + } + + // 2) Fallback: RAM-Cache only (immer noch schnell, kein ffprobe) + if dur <= 0 { + dur = durationSecondsCacheOnly(full, fi) + } + + // 3) KEIN ffprobe hier! (sonst wird die API wieder langsam) + + list = append(list, &RecordJob{ + ID: base, // ✅ KEIN keep/ prefix (würde Assets/Preview killen) + Output: full, + Status: JobFinished, + StartedAt: start, + EndedAt: &t, + DurationSeconds: dur, + SizeBytes: fi.Size(), + }) + } + + for _, sd := range dirs { + entries, err := os.ReadDir(sd.dir) + if err != nil { + if os.IsNotExist(err) { + if sd.dir == doneAbs { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode([]*RecordJob{}) + return + } + continue + } + if sd.dir == doneAbs { + http.Error(w, "doneDir lesen fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + continue + } + + for _, e := range entries { + // Subdir: 1 Level rein (z.B. /done// oder /done/keep//) + if e.IsDir() { + if sd.skipKeep && e.Name() == "keep" { + continue + } + sub := filepath.Join(sd.dir, e.Name()) + subEntries, err := os.ReadDir(sub) + if err != nil { + continue + } + for _, se := range subEntries { + if se.IsDir() { + continue + } + full := filepath.Join(sub, se.Name()) + fi, err := os.Stat(full) + if err != nil || fi.IsDir() || fi.Size() == 0 { + continue + } + addFile(full, fi) + } + continue + } + + full := filepath.Join(sd.dir, e.Name()) + fi, err := os.Stat(full) + if err != nil || fi.IsDir() || fi.Size() == 0 { + continue + } + addFile(full, fi) + } } // helpers (Sort) @@ -2712,55 +4897,6 @@ func recordDoneList(w http.ResponseWriter, r *http.Request) { return 0, false } - list := make([]*RecordJob, 0, len(entries)) - for _, e := range entries { - if e.IsDir() { - continue - } - name := e.Name() - ext := strings.ToLower(filepath.Ext(name)) - if ext != ".mp4" && ext != ".ts" { - continue - } - - full := filepath.Join(doneAbs, name) - fi, err := os.Stat(full) - if err != nil || fi.IsDir() { - continue - } - - base := strings.TrimSuffix(name, filepath.Ext(name)) - t := fi.ModTime() - - // ✅ StartedAt aus Dateiname (Fallback: ModTime) - start := t - stem := base - if strings.HasPrefix(stem, "HOT ") { - stem = strings.TrimPrefix(stem, "HOT ") - } - if m := startedAtFromFilenameRe.FindStringSubmatch(stem); m != nil { - mm, _ := strconv.Atoi(m[2]) - dd, _ := strconv.Atoi(m[3]) - yy, _ := strconv.Atoi(m[4]) - hh, _ := strconv.Atoi(m[5]) - mi, _ := strconv.Atoi(m[6]) - ss, _ := strconv.Atoi(m[7]) - start = time.Date(yy, time.Month(mm), dd, hh, mi, ss, 0, time.Local) - } - - dur := durationSecondsCacheOnly(full, fi) - - list = append(list, &RecordJob{ - ID: base, - Output: full, - Status: JobFinished, - StartedAt: start, - EndedAt: &t, - DurationSeconds: dur, - SizeBytes: fi.Size(), - }) - } - // Sortierung sort.Slice(list, func(i, j int) bool { a, b := list[i], list[j] @@ -2873,8 +5009,8 @@ func recordDoneList(w http.ResponseWriter, r *http.Request) { } }) - // Pagination (nach Sort!) - if pageSize > 0 { + // Pagination (nach Sort!) – nur wenn pageSize > 0 und NICHT all=1 + if pageSize > 0 && !fetchAll { if page <= 0 { page = 1 } @@ -2906,6 +5042,10 @@ func recordDoneMeta(w http.ResponseWriter, r *http.Request) { return } + // ✅ optional: auch /done/keep/ einbeziehen (Standard: false) + qKeep := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("includeKeep"))) + includeKeep := qKeep == "1" || qKeep == "true" || qKeep == "yes" + s := getSettings() doneAbs, err := resolvePathRelativeToApp(s.DoneDir) if err != nil { @@ -2917,27 +5057,51 @@ func recordDoneMeta(w http.ResponseWriter, r *http.Request) { return } - entries, err := os.ReadDir(doneAbs) - if err != nil { - if os.IsNotExist(err) { - writeJSON(w, http.StatusOK, doneMetaResp{Count: 0}) - return - } - http.Error(w, "readdir fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) - return + dirs := []string{doneAbs} + if includeKeep { + dirs = append(dirs, filepath.Join(doneAbs, "keep")) } cnt := 0 - for _, e := range entries { - if e.IsDir() { - continue + + countIn := func(dir string, skipKeep bool) { + entries, err := os.ReadDir(dir) + if err != nil { + return } - ext := strings.ToLower(filepath.Ext(e.Name())) - // gleiche Allowlist wie bei deinen Done-Aktionen (HOT/keep etc.) - if ext != ".mp4" && ext != ".ts" { - continue + + for _, e := range entries { + if e.IsDir() { + if skipKeep && e.Name() == "keep" { + continue + } + sub := filepath.Join(dir, e.Name()) + subEntries, err := os.ReadDir(sub) + if err != nil { + continue + } + for _, se := range subEntries { + if se.IsDir() { + continue + } + ext := strings.ToLower(filepath.Ext(se.Name())) + if ext == ".mp4" || ext == ".ts" { + cnt++ + } + } + continue + } + + ext := strings.ToLower(filepath.Ext(e.Name())) + if ext == ".mp4" || ext == ".ts" { + cnt++ + } } - cnt++ + } + + countIn(doneAbs, true) + if includeKeep { + countIn(filepath.Join(doneAbs, "keep"), false) } writeJSON(w, http.StatusOK, doneMetaResp{Count: cnt}) @@ -2953,6 +5117,63 @@ type durationItem struct { Error string `json:"error,omitempty"` } +func removeJobsByOutputBasename(file string) { + file = strings.TrimSpace(file) + if file == "" { + return + } + + removed := false + jobsMu.Lock() + for id, j := range jobs { + if j == nil { + continue + } + out := strings.TrimSpace(j.Output) + if out == "" { + continue + } + if filepath.Base(out) == file { + delete(jobs, id) + removed = true + } + } + jobsMu.Unlock() + + if removed { + notifyJobsChanged() + } +} + +func renameJobsOutputBasename(oldFile, newFile string) { + oldFile = strings.TrimSpace(oldFile) + newFile = strings.TrimSpace(newFile) + if oldFile == "" || newFile == "" { + return + } + + changed := false + jobsMu.Lock() + for _, j := range jobs { + if j == nil { + continue + } + out := strings.TrimSpace(j.Output) + if out == "" { + continue + } + if filepath.Base(out) == oldFile { + j.Output = filepath.Join(filepath.Dir(out), newFile) + changed = true + } + } + jobsMu.Unlock() + + if changed { + notifyJobsChanged() + } +} + func recordDeleteVideo(w http.ResponseWriter, r *http.Request) { // Frontend nutzt aktuell POST (siehe FinishedDownloads), daher erlauben wir POST + DELETE if r.Method != http.MethodPost && r.Method != http.MethodDelete { @@ -2972,20 +5193,16 @@ func recordDeleteVideo(w http.ResponseWriter, r *http.Request) { http.Error(w, "ungültiger file", http.StatusBadRequest) return } - file = strings.TrimSpace(file) - if file == "" { - http.Error(w, "file leer", http.StatusBadRequest) - return - } - // Pfad absichern: nur Dateiname, keine Unterordner/Traversal - clean := filepath.Clean(file) - if clean == "." || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) || filepath.IsAbs(clean) { + // ✅ nur Basename erlauben (keine Unterordner, kein Traversal) + if file == "" || + strings.Contains(file, "/") || + strings.Contains(file, "\\") || + filepath.Base(file) != file { http.Error(w, "ungültiger file", http.StatusBadRequest) return } - file = clean ext := strings.ToLower(filepath.Ext(file)) if ext != ".mp4" && ext != ".ts" { @@ -3004,18 +5221,13 @@ func recordDeleteVideo(w http.ResponseWriter, r *http.Request) { return } - target := filepath.Join(doneAbs, file) - - fi, err := os.Stat(target) + // ✅ done + done/ sowie keep + keep/ + target, from, fi, err := resolveDoneFileByName(doneAbs, file) if err != nil { - if os.IsNotExist(err) { - http.Error(w, "datei nicht gefunden", http.StatusNotFound) - return - } - http.Error(w, "stat fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + http.Error(w, "datei nicht gefunden", http.StatusNotFound) return } - if fi.IsDir() { + if fi != nil && fi.IsDir() { http.Error(w, "ist ein verzeichnis", http.StatusBadRequest) return } @@ -3032,21 +5244,19 @@ func recordDeleteVideo(w http.ResponseWriter, r *http.Request) { return } - // ✅ generated Assets löschen (best effort) base := strings.TrimSuffix(file, filepath.Ext(file)) canonical := stripHotPrefix(base) - // Neu: /generated// - if genAbs, _ := generatedRoot(); strings.TrimSpace(genAbs) != "" { - if strings.TrimSpace(canonical) != "" { - _ = os.RemoveAll(filepath.Join(genAbs, canonical)) - } - // falls irgendwo alte Assets mit HOT im Ordnernamen liegen - if strings.TrimSpace(base) != "" && base != canonical { - _ = os.RemoveAll(filepath.Join(genAbs, base)) - } + // Alles weg inkl. meta/frames/temp preview + removeGeneratedForID(canonical) + + // Safety: falls irgendwo Assets “mit HOT im Ordnernamen” entstanden sind (sollte nicht, aber best-effort) + if base != canonical { + removeGeneratedForID(base) } + purgeDurationCacheForPath(target) + // Legacy-Cleanup (optional) thumbsLegacy, _ := generatedThumbsRoot() teaserLegacy, _ := generatedTeaserRoot() @@ -3065,11 +5275,14 @@ func recordDeleteVideo(w http.ResponseWriter, r *http.Request) { _ = os.Remove(filepath.Join(teaserLegacy, base+".mp4")) } + removeJobsByOutputBasename(file) + w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(map[string]any{ "ok": true, "file": file, + "from": from, // "done" | "keep" }) } @@ -3111,20 +5324,16 @@ func recordKeepVideo(w http.ResponseWriter, r *http.Request) { http.Error(w, "ungültiger file", http.StatusBadRequest) return } - file = strings.TrimSpace(file) - if file == "" { - http.Error(w, "file leer", http.StatusBadRequest) - return - } - // Pfad absichern - clean := filepath.Clean(file) - if clean == "." || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) || filepath.IsAbs(clean) { + // ✅ nur Basename erlauben + if file == "" || + strings.Contains(file, "/") || + strings.Contains(file, "\\") || + filepath.Base(file) != file { http.Error(w, "ungültiger file", http.StatusBadRequest) return } - file = clean ext := strings.ToLower(filepath.Ext(file)) if ext != ".mp4" && ext != ".ts" { @@ -3143,31 +5352,53 @@ func recordKeepVideo(w http.ResponseWriter, r *http.Request) { return } - src := filepath.Join(doneAbs, file) + keepRoot := filepath.Join(doneAbs, "keep") - fi, err := os.Stat(src) - if err != nil { - if os.IsNotExist(err) { - http.Error(w, "datei nicht gefunden", http.StatusNotFound) - return - } - http.Error(w, "stat fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) - return - } - if fi.IsDir() { - http.Error(w, "ist ein verzeichnis", http.StatusBadRequest) - return - } - - keepDir := filepath.Join(doneAbs, "keep") - if err := os.MkdirAll(keepDir, 0o755); err != nil { + // keep root sicherstellen + if err := os.MkdirAll(keepRoot, 0o755); err != nil { http.Error(w, "keep dir erstellen fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) return } - dst := filepath.Join(keepDir, file) + // ✅ Wenn schon irgendwo in keep (root oder keep/) => idempotent OK + if p, _, ok := findFileInDirOrOneLevelSubdirs(keepRoot, file, ""); ok { + _ = p // nur für Klarheit + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{ + "ok": true, + "file": file, + "alreadyKept": true, + }) + return + } - // falls schon vorhanden => Fehler + // ✅ Quelle in done (root oder done/), aber NICHT aus keep + src, fi, ok := findFileInDirOrOneLevelSubdirs(doneAbs, file, "keep") + if !ok { + http.Error(w, "datei nicht gefunden", http.StatusNotFound) + return + } + if fi == nil || fi.IsDir() { + http.Error(w, "ist ein verzeichnis", http.StatusBadRequest) + return + } + + // ✅ Ziel: /done/keep//file (wenn model aus Dateiname ableitbar) + dstDir := keepRoot + modelKey := strings.TrimSpace(modelNameFromFilename(file)) + modelKey = stripHotPrefix(modelKey) + if modelKey != "" && modelKey != "—" && !strings.ContainsAny(modelKey, `/\`) { + dstDir = filepath.Join(dstDir, modelKey) + } + if err := os.MkdirAll(dstDir, 0o755); err != nil { + http.Error(w, "keep subdir erstellen fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + + dst := filepath.Join(dstDir, file) + + // falls schon vorhanden => Konflikt (sollte durch already-check oben selten passieren) if _, err := os.Stat(dst); err == nil { http.Error(w, "ziel existiert bereits", http.StatusConflict) return @@ -3219,11 +5450,14 @@ func recordKeepVideo(w http.ResponseWriter, r *http.Request) { _ = os.Remove(filepath.Join(teaserLegacy, base+".mp4")) } + removeJobsByOutputBasename(file) + w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(map[string]any{ - "ok": true, - "file": file, + "ok": true, + "file": file, + "alreadyKept": false, }) } @@ -3246,7 +5480,7 @@ func recordToggleHot(w http.ResponseWriter, r *http.Request) { } file = strings.TrimSpace(file) - // kein Pfad, keine Backslashes, kein Traversal + // ✅ nur Basename erlauben if file == "" || strings.Contains(file, "/") || strings.Contains(file, "\\") || @@ -3272,21 +5506,19 @@ func recordToggleHot(w http.ResponseWriter, r *http.Request) { return } - src := filepath.Join(doneAbs, file) - fi, err := os.Stat(src) + // ✅ Quelle kann in done/, done/, keep/, keep/ liegen + src, from, fi, err := resolveDoneFileByName(doneAbs, file) if err != nil { - if os.IsNotExist(err) { - http.Error(w, "datei nicht gefunden", http.StatusNotFound) - return - } - http.Error(w, "stat fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + http.Error(w, "datei nicht gefunden", http.StatusNotFound) return } - if fi.IsDir() { + if fi != nil && fi.IsDir() { http.Error(w, "ist ein verzeichnis", http.StatusBadRequest) return } + srcDir := filepath.Dir(src) // ✅ wichtig: toggeln im tatsächlichen Ordner + // toggle: HOT Prefix newFile := file if strings.HasPrefix(file, "HOT ") { @@ -3295,7 +5527,7 @@ func recordToggleHot(w http.ResponseWriter, r *http.Request) { newFile = "HOT " + file } - dst := filepath.Join(doneAbs, newFile) + dst := filepath.Join(srcDir, newFile) // ✅ im selben Ordner toggeln (done oder keep) if _, err := os.Stat(dst); err == nil { http.Error(w, "ziel existiert bereits", http.StatusConflict) return @@ -3313,18 +5545,20 @@ func recordToggleHot(w http.ResponseWriter, r *http.Request) { return } - // ✅ KEIN generated-rename mehr! - // Assets bleiben canonical: generated/thumbs/.jpg und generated/teaser/_teaser.mp4 (ohne HOT) - + // ✅ KEIN generated-rename! + // Assets bleiben canonical (ohne HOT) canonicalID := stripHotPrefix(strings.TrimSuffix(file, filepath.Ext(file))) + renameJobsOutputBasename(file, newFile) + w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(map[string]any{ "ok": true, "oldFile": file, "newFile": newFile, - "canonicalID": canonicalID, // optional fürs Frontend + "canonicalID": canonicalID, + "from": from, // "done" | "keep" }) } @@ -3349,6 +5583,75 @@ func maybeRemuxTS(path string) (string, error) { return mp4, nil } +func maybeRemuxTSForJob(job *RecordJob, path string) (string, error) { + path = strings.TrimSpace(path) + if path == "" { + return "", nil + } + + if !strings.EqualFold(filepath.Ext(path), ".ts") { + return "", nil + } + + mp4 := strings.TrimSuffix(path, filepath.Ext(path)) + ".mp4" + + // input size für fallback + var inSize int64 + if fi, err := os.Stat(path); err == nil && !fi.IsDir() { + inSize = fi.Size() + } + + // duration (für sauberen progress) + var durSec float64 + { + durCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + durSec, _ = durationSecondsCached(durCtx, path) + cancel() + } + + const base = 10 + const span = 60 // 10..69 (70 startet "moving") + + lastProgress := base + lastTick := time.Now().Add(-time.Second) + + onRatio := func(r float64) { + if r < 0 { + r = 0 + } + if r > 1 { + r = 1 + } + p := base + int(r*float64(span)) + if p >= 70 { + p = 69 + } + + if p <= lastProgress { + return + } + // leicht throttlen + if time.Since(lastTick) < 150*time.Millisecond && p < 79 { + return + } + lastProgress = p + lastTick = time.Now() + setJobPhase(job, "remuxing", p) + } + + remuxCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) + defer cancel() + + if err := remuxTSToMP4WithProgress(remuxCtx, path, mp4, durSec, inSize, onRatio); err != nil { + return "", err + } + + _ = os.Remove(path) // TS entfernen, wenn MP4 ok + setJobPhase(job, "remuxing", 69) // ✅ Remux finished (nie rückwärts) + return mp4, nil + +} + func moveFile(src, dst string) error { // zuerst Rename (schnell) if err := os.Rename(src, dst); err == nil { @@ -3489,32 +5792,13 @@ func recordStop(w http.ResponseWriter, r *http.Request) { jobsMu.Lock() job, ok := jobs[id] - if ok { - job.Phase = "stopping" - job.Progress = 10 - } jobsMu.Unlock() - - if ok { - notifyJobsChanged() // ✅ 1) UI sofort updaten (Phase/Progress) - } - if !ok { http.Error(w, "job nicht gefunden", http.StatusNotFound) return } - // Preview wird bei dir über ctx beendet – kill kann bleiben, ist aber oft nil. - if job.previewCmd != nil && job.previewCmd.Process != nil { - _ = job.previewCmd.Process.Kill() - job.previewCmd = nil - } - - if job.cancel != nil { - job.cancel() - } - - notifyJobsChanged() // ✅ 2) optional: nach Cancel/Kill nochmal pushen + stopJobsInternal([]*RecordJob{job}) w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(job) @@ -3537,6 +5821,9 @@ func RecordStream( pageURL := base + "/" + username body, err := hc.FetchPage(ctx, pageURL, httpCookie) + if err != nil { + return fmt.Errorf("seite laden: %w", err) + } // 2) HLS-URL aus roomDossier extrahieren (wie DVR.ParseStream) hlsURL, err := ParseStream(body) @@ -3551,13 +5838,17 @@ func RecordStream( } if job != nil && strings.TrimSpace(job.PreviewDir) == "" { - previewDir := filepath.Join(os.TempDir(), "rec_preview", job.ID) + assetID := assetIDForJob(job) + if strings.TrimSpace(assetID) == "" { + assetID = job.ID + } + previewDir := filepath.Join(os.TempDir(), "rec_preview", assetID) jobsMu.Lock() job.PreviewDir = previewDir jobsMu.Unlock() - if err := startPreviewHLS(ctx, job.ID, playlist.PlaylistURL, previewDir, httpCookie, hc.userAgent); err != nil { + if err := startPreviewHLS(ctx, job, playlist.PlaylistURL, previewDir, httpCookie, hc.userAgent); err != nil { fmt.Println("⚠️ preview start fehlgeschlagen:", err) } } @@ -3571,12 +5862,33 @@ func RecordStream( _ = file.Close() }() + // live size tracking (für UI) + var written int64 + var lastPush time.Time + var lastBytes int64 + // 5) Segmente „watchen“ – analog zu WatchSegments + HandleSegment im DVR err = playlist.WatchSegments(ctx, hc, httpCookie, func(b []byte, duration float64) error { // Hier wäre im DVR ch.HandleSegment – bei dir einfach in eine Datei schreiben if _, err := file.Write(b); err != nil { return fmt.Errorf("schreibe segment: %w", err) } + + // ✅ live size (UI) – throttled + written += int64(len(b)) + if job != nil { + now := time.Now() + if lastPush.IsZero() || now.Sub(lastPush) >= 750*time.Millisecond || (written-lastBytes) >= 2*1024*1024 { + jobsMu.Lock() + job.SizeBytes = written + jobsMu.Unlock() + notifyJobsChanged() + + lastPush = now + lastBytes = written + } + } + // Könntest hier z.B. auch Dauer/Größe loggen, wenn du möchtest _ = duration // aktuell unbenutzt return nil @@ -3619,17 +5931,22 @@ func RecordStreamMFC( // ✅ Preview starten if job != nil && job.PreviewDir == "" { - previewDir := filepath.Join(os.TempDir(), "preview_"+job.ID) + assetID := assetIDForJob(job) + if strings.TrimSpace(assetID) == "" { + assetID = job.ID + } + previewDir := filepath.Join(os.TempDir(), "rec_preview", assetID) + job.PreviewDir = previewDir - if err := startPreviewHLS(ctx, job.ID, m3u8URL, previewDir, "", hc.userAgent); err != nil { + if err := startPreviewHLS(ctx, job, m3u8URL, previewDir, "", hc.userAgent); err != nil { fmt.Println("⚠️ preview start fehlgeschlagen:", err) job.PreviewDir = "" // rollback } } // Aufnahme starten - return handleM3U8Mode(ctx, m3u8URL, outputPath) + return handleM3U8Mode(ctx, m3u8URL, outputPath, job) } func detectProvider(raw string) string { @@ -3763,7 +6080,7 @@ func FetchPlaylist(ctx context.Context, hc *HTTPClient, hlsSource, httpCookie st continue } - width, err := strconv.Atoi(parts[1]) + width, err := strconv.Atoi(parts[0]) if err != nil { continue } @@ -4046,7 +6363,7 @@ func runMFC(ctx context.Context, username string, outArg string) error { return errors.New("keine m3u8 URL gefunden") } - return handleM3U8Mode(ctx, m3u8URL, outArg) + return handleM3U8Mode(ctx, m3u8URL, outArg, nil) } /* ─────────────────────────────── @@ -4115,7 +6432,7 @@ func getWantedResolutionPlaylist(playlistURL string) (string, error) { return root + bestURI, nil } -func handleM3U8Mode(ctx context.Context, m3u8URL, outFile string) error { +func handleM3U8Mode(ctx context.Context, m3u8URL, outFile string, job *RecordJob) error { // Validierung u, err := url.Parse(m3u8URL) if err != nil || (u.Scheme != "http" && u.Scheme != "https") { @@ -4147,20 +6464,52 @@ func handleM3U8Mode(ctx context.Context, m3u8URL, outFile string) error { ctx, ffmpegPath, "-y", + "-hide_banner", + "-nostats", + "-loglevel", "warning", // alternativ: "error" (noch leiser) "-i", m3u8URL, "-c", "copy", outFile, ) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - if errors.Is(ctx.Err(), context.Canceled) { - return ctx.Err() - } - return fmt.Errorf("ffmpeg fehlgeschlagen: %w", err) + // FFmpeg nicht direkt in stdout/stderr schreiben lassen -> sonst spammt es Log/Console + var stderr bytes.Buffer + cmd.Stdout = io.Discard + cmd.Stderr = &stderr + + // ✅ live size polling während ffmpeg läuft + stopStat := make(chan struct{}) + defer close(stopStat) + + if job != nil { + go func() { + t := time.NewTicker(1 * time.Second) + defer t.Stop() + + var last int64 + for { + select { + case <-ctx.Done(): + return + case <-stopStat: + return + case <-t.C: + fi, err := os.Stat(outFile) + if err != nil { + continue + } + sz := fi.Size() + if sz > 0 && sz != last { + jobsMu.Lock() + job.SizeBytes = sz + jobsMu.Unlock() + notifyJobsChanged() + last = sz + } + } + } + }() } - return nil } diff --git a/backend/models.go b/backend/models.go index 42d7f3a..249fdb7 100644 --- a/backend/models.go +++ b/backend/models.go @@ -104,17 +104,22 @@ func modelNameFromFilename(file string) string { base := file[strings.LastIndex(file, "/")+1:] base = strings.TrimSuffix(base, filepath.Ext(base)) + // ✅ HOT Prefix beim Parsen ignorieren (case-insensitive) + if strings.HasPrefix(strings.ToUpper(base), "HOT ") { + base = strings.TrimSpace(base[4:]) + } + if m := reModel.FindStringSubmatch(base); len(m) == 2 && strings.TrimSpace(m[1]) != "" { - return m[1] + return strings.TrimSpace(m[1]) } // fallback: bis zum letzten "_" (wie bisher) if i := strings.LastIndex(base, "_"); i > 0 { - return base[:i] + return strings.TrimSpace(base[:i]) } if base == "" { return "—" } - return base + return strings.TrimSpace(base) } func modelsEnsureLoaded() error { diff --git a/backend/models_api.go b/backend/models_api.go index b04a0e0..066b5c2 100644 --- a/backend/models_api.go +++ b/backend/models_api.go @@ -1,3 +1,5 @@ +// backend\models_api.go + package main import ( @@ -128,13 +130,20 @@ func importModelsCSV(store *ModelStore, r io.Reader, kind string) (importResult, idx[strings.ToLower(strings.TrimSpace(h))] = i } - need := []string{"url", "last_stream", "tags", "watch"} + need := []string{"url", "last_stream", "tags"} for _, k := range need { if _, ok := idx[k]; !ok { return importResult{}, errors.New("CSV: Spalte fehlt: " + k) } } + // ✅ watch ODER watched akzeptieren + if _, ok := idx["watch"]; !ok { + if _, ok2 := idx["watched"]; !ok2 { + return importResult{}, errors.New("CSV: Spalte fehlt: watch oder watched") + } + } + seen := map[string]bool{} out := importResult{} @@ -171,6 +180,10 @@ func importModelsCSV(store *ModelStore, r io.Reader, kind string) (importResult, lastStream := get("last_stream") watchStr := get("watch") + if watchStr == "" { + watchStr = get("watched") + } + watch := false if watchStr != "" { if n, err := strconv.Atoi(watchStr); err == nil { @@ -274,19 +287,24 @@ func RegisterModelAPI(mux *http.ServeMux, store *ModelStore) { var req struct { ModelKey string `json:"modelKey"` + Host string `json:"host,omitempty"` } + if err := modelsReadJSON(r, &req); err != nil { modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) return } key := strings.TrimSpace(req.ModelKey) + host := strings.ToLower(strings.TrimSpace(req.Host)) + host = strings.TrimPrefix(host, "www.") + if key == "" { modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": "modelKey fehlt"}) return } - m, err := store.EnsureByModelKey(key) + m, err := store.EnsureByHostModelKey(host, key) if err != nil { modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) return @@ -338,11 +356,38 @@ func RegisterModelAPI(mux *http.ServeMux, store *ModelStore) { modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) return } + // ✅ id optional: wenn fehlt -> per (host, modelKey) sicherstellen + id setzen + if strings.TrimSpace(req.ID) == "" { + key := strings.TrimSpace(req.ModelKey) + host := strings.TrimSpace(req.Host) + + if key == "" { + modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": "id oder modelKey fehlt"}) + return + } + + ensured, err := store.EnsureByHostModelKey(host, key) // host darf leer sein + if err != nil { + modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) + return + } + req.ID = ensured.ID + } m, err := store.PatchFlags(req) if err != nil { modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) return } + + // ✅ Wenn ein Model weder beobachtet noch favorisiert/geliked ist, fliegt es aus dem Store. + // (Damit bleibt der Store „sauber“ und ModelsTab listet nur relevante Einträge.) + likedOn := (m.Liked != nil && *m.Liked) + if !m.Watching && !m.Favorite && !likedOn { + _ = store.Delete(m.ID) // best-effort: Patch war erfolgreich, Delete darf hier nicht „fatal“ sein + w.WriteHeader(http.StatusNoContent) + return + } + modelsWriteJSON(w, http.StatusOK, m) }) diff --git a/backend/models_store.go b/backend/models_store.go index 21c3024..2cc142d 100644 --- a/backend/models_store.go +++ b/backend/models_store.go @@ -58,13 +58,13 @@ type ParsedModelDTO struct { } type ModelFlagsPatch struct { - ID string `json:"id"` - Watching *bool `json:"watching,omitempty"` - Favorite *bool `json:"favorite,omitempty"` - Hot *bool `json:"hot,omitempty"` - Keep *bool `json:"keep,omitempty"` - Liked *bool `json:"liked,omitempty"` - ClearLiked bool `json:"clearLiked,omitempty"` + Host string `json:"host,omitempty"` // ✅ neu + ModelKey string `json:"modelKey,omitempty"` // ✅ wenn id fehlt + ID string `json:"id,omitempty"` // ✅ optional + + Watched *bool `json:"watched,omitempty"` + Favorite *bool `json:"favorite,omitempty"` + Liked *bool `json:"liked,omitempty"` } type ModelStore struct { @@ -79,6 +79,71 @@ type ModelStore struct { mu sync.Mutex } +func (s *ModelStore) EnsureByHostModelKey(host, modelKey string) (StoredModel, error) { + if err := s.ensureInit(); err != nil { + return StoredModel{}, err + } + + key := strings.TrimSpace(modelKey) + if key == "" { + return StoredModel{}, errors.New("modelKey fehlt") + } + + h := canonicalHost(host) + + // host optional: wenn leer -> fallback auf bisherigen Weg (best match über alle Hosts) + if h == "" { + return s.EnsureByModelKey(key) + } + + // 1) explizit host+key suchen + var existingID string + err := s.db.QueryRow(` + SELECT id + FROM models + WHERE lower(trim(host)) = lower(trim(?)) + AND lower(trim(model_key)) = lower(trim(?)) + LIMIT 1; + `, h, key).Scan(&existingID) + + if err == nil && existingID != "" { + return s.getByID(existingID) + } + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return StoredModel{}, err + } + + // 2) nicht vorhanden -> "manual" anlegen (is_url=0, input=modelKey), ABER host gesetzt + now := time.Now().UTC().Format(time.RFC3339Nano) + id := canonicalID(h, key) + + s.mu.Lock() + defer s.mu.Unlock() + + _, err = s.db.Exec(` +INSERT INTO models ( + id,input,is_url,host,path,model_key, + tags,last_stream, + watching,favorite,hot,keep,liked, + created_at,updated_at +) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) +ON CONFLICT(id) DO UPDATE SET + model_key=excluded.model_key, + host=excluded.host, + updated_at=excluded.updated_at; +`, + id, key, int64(0), h, "", key, + "", "", + int64(0), int64(0), int64(0), int64(0), nil, + now, now, + ) + if err != nil { + return StoredModel{}, err + } + + return s.getByID(id) +} + // EnsureByModelKey: // - liefert ein bestehendes Model (best match) wenn vorhanden // - sonst legt es ein "manual" Model ohne URL an (Input=modelKey, IsURL=false) @@ -94,15 +159,20 @@ func (s *ModelStore) EnsureByModelKey(modelKey string) (StoredModel, error) { return StoredModel{}, errors.New("modelKey fehlt") } + // Erst schauen ob es das Model schon gibt (egal welcher Host) // Erst schauen ob es das Model schon gibt (egal welcher Host) var existingID string err := s.db.QueryRow(` -SELECT id -FROM models -WHERE lower(model_key) = lower(?) -ORDER BY favorite DESC, updated_at DESC -LIMIT 1; -`, key).Scan(&existingID) + SELECT id + FROM models + WHERE lower(trim(model_key)) = lower(trim(?)) + ORDER BY + CASE WHEN is_url=1 THEN 1 ELSE 0 END DESC, + CASE WHEN host IS NOT NULL AND trim(host)<>'' THEN 1 ELSE 0 END DESC, + favorite DESC, + updated_at DESC + LIMIT 1; + `, key).Scan(&existingID) if err == nil && existingID != "" { return s.getByID(existingID) @@ -141,6 +211,52 @@ ON CONFLICT(id) DO UPDATE SET return s.getByID(id) } +func (s *ModelStore) FillMissingTagsFromChaturbateOnline(rooms []ChaturbateRoom) { + if err := s.ensureInit(); err != nil { + return + } + if len(rooms) == 0 { + return + } + + now := time.Now().UTC().Format(time.RFC3339Nano) + + s.mu.Lock() + defer s.mu.Unlock() + + tx, err := s.db.Begin() + if err != nil { + return + } + defer func() { _ = tx.Rollback() }() + + stmt, err := tx.Prepare(` +UPDATE models +SET tags = ?, updated_at = ? +WHERE lower(trim(host)) = 'chaturbate.com' + AND lower(trim(model_key)) = lower(trim(?)) + AND (tags IS NULL OR trim(tags) = ''); +`) + if err != nil { + return + } + defer stmt.Close() + + for _, rm := range rooms { + key := strings.TrimSpace(rm.Username) + if key == "" || len(rm.Tags) == 0 { + continue + } + tags := strings.TrimSpace(strings.Join(rm.Tags, ", ")) + if tags == "" { + continue + } + _, _ = stmt.Exec(tags, now, key) + } + + _ = tx.Commit() +} + // Backwards compatible: // - wenn du ".json" übergibst (wie aktuell in main.go), wird daraus automatisch ".db" // und die JSON-Datei wird als Legacy-Quelle für die 1x Migration genutzt. @@ -188,7 +304,9 @@ func (s *ModelStore) init() error { return err } // SQLite am besten single-conn im Server-Prozess - db.SetMaxOpenConns(1) + db.SetMaxOpenConns(5) + db.SetMaxIdleConns(5) + _, _ = db.Exec(`PRAGMA busy_timeout = 2500;`) // Pragmas (einzeln ausführen) _, _ = db.Exec(`PRAGMA foreign_keys = ON;`) @@ -215,6 +333,11 @@ func (s *ModelStore) init() error { } } + // ✅ beim Einlesen normalisieren + if err := s.normalizeNameOnlyChaturbate(); err != nil { + return err + } + return nil } @@ -230,6 +353,8 @@ CREATE TABLE IF NOT EXISTS models ( tags TEXT NOT NULL DEFAULT '', last_stream TEXT, + biocontext_json TEXT, + biocontext_fetched_at TEXT, watching INTEGER NOT NULL DEFAULT 0, favorite INTEGER NOT NULL DEFAULT 0, @@ -245,7 +370,6 @@ CREATE TABLE IF NOT EXISTS models ( return err } - // optionaler Unique-Index (hilft bei Konsistenz) _, _ = db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_models_host_key ON models(host, model_key);`) _, _ = db.Exec(`CREATE INDEX IF NOT EXISTS idx_models_updated ON models(updated_at);`) return nil @@ -281,6 +405,19 @@ func ensureModelsColumns(db *sql.DB) error { return err } } + + // ✅ Biocontext (persistente Bio-Infos) + if !cols["biocontext_json"] { + if _, err := db.Exec(`ALTER TABLE models ADD COLUMN biocontext_json TEXT;`); err != nil { + return err + } + } + if !cols["biocontext_fetched_at"] { + if _, err := db.Exec(`ALTER TABLE models ADD COLUMN biocontext_fetched_at TEXT;`); err != nil { + return err + } + } + return nil } @@ -321,6 +458,104 @@ func ptrLikedFromNull(n sql.NullInt64) *bool { return &v } +// --- Biocontext Cache (persistente Bio-Infos aus Chaturbate) --- + +// GetBioContext liefert das zuletzt gespeicherte Biocontext-JSON (+ Zeitstempel). +// ok=false wenn nichts gespeichert ist. +func (s *ModelStore) GetBioContext(host, modelKey string) (jsonStr string, fetchedAt string, ok bool, err error) { + if err := s.ensureInit(); err != nil { + return "", "", false, err + } + host = canonicalHost(host) + key := strings.TrimSpace(modelKey) + if host == "" || key == "" { + return "", "", false, errors.New("host/modelKey fehlt") + } + + var js sql.NullString + var ts sql.NullString + err = s.db.QueryRow(` + SELECT biocontext_json, biocontext_fetched_at + FROM models + WHERE lower(trim(host)) = lower(trim(?)) + AND lower(trim(model_key)) = lower(trim(?)) + LIMIT 1; + `, host, key).Scan(&js, &ts) + + if errors.Is(err, sql.ErrNoRows) { + return "", "", false, nil + } + if err != nil { + return "", "", false, err + } + + val := strings.TrimSpace(js.String) + if val == "" { + return "", strings.TrimSpace(ts.String), false, nil + } + return val, strings.TrimSpace(ts.String), true, nil +} + +// SetBioContext speichert/aktualisiert das Biocontext-JSON dauerhaft in der DB. +// Es legt das Model (host+modelKey) bei Bedarf minimal an. +func (s *ModelStore) SetBioContext(host, modelKey, jsonStr, fetchedAt string) error { + if err := s.ensureInit(); err != nil { + return err + } + host = canonicalHost(host) + key := strings.TrimSpace(modelKey) + if host == "" || key == "" { + return errors.New("host/modelKey fehlt") + } + + js := strings.TrimSpace(jsonStr) + ts := strings.TrimSpace(fetchedAt) + now := time.Now().UTC().Format(time.RFC3339Nano) + + s.mu.Lock() + defer s.mu.Unlock() + + res, err := s.db.Exec(` + UPDATE models + SET biocontext_json=?, biocontext_fetched_at=?, updated_at=? + WHERE lower(trim(host)) = lower(trim(?)) + AND lower(trim(model_key)) = lower(trim(?)); + `, js, ts, now, host, key) + if err != nil { + return err + } + + aff, _ := res.RowsAffected() + if aff > 0 { + return nil + } + + // Model existiert noch nicht -> minimal anlegen (als URL) + id := canonicalID(host, key) + input := "https://" + host + "/" + key + "/" + path := "/" + key + "/" + + _, err = s.db.Exec(` + INSERT INTO models ( + id,input,is_url,host,path,model_key, + tags,last_stream, + biocontext_json,biocontext_fetched_at, + watching,favorite,hot,keep,liked, + created_at,updated_at + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + ON CONFLICT(id) DO UPDATE SET + biocontext_json=excluded.biocontext_json, + biocontext_fetched_at=excluded.biocontext_fetched_at, + updated_at=excluded.updated_at; + `, id, input, int64(1), host, path, key, + "", "", + js, ts, + int64(0), int64(0), int64(0), int64(0), nil, + now, now, + ) + return err +} + func (s *ModelStore) migrateFromJSONIfEmpty() error { // DB leer? var cnt int @@ -433,20 +668,172 @@ func bytesTrimSpace(b []byte) []byte { return []byte(strings.TrimSpace(string(b))) } +func (s *ModelStore) normalizeNameOnlyChaturbate() error { + // Kandidaten: is_url=0 UND input==model_key UND host leer oder schon chaturbate + rows, err := s.db.Query(` +SELECT + id, model_key, + tags, COALESCE(last_stream,''), + watching,favorite,hot,keep,liked, + created_at,updated_at +FROM models +WHERE is_url = 0 + AND lower(trim(input)) = lower(trim(model_key)) + AND (host IS NULL OR trim(host)='' OR lower(trim(host))='chaturbate.com'); +`) + if err != nil { + return err + } + defer rows.Close() + + type rowT struct { + oldID, key, tags, lastStream, createdAt, updatedAt string + watching, favorite, hot, keep int64 + liked sql.NullInt64 + } + var items []rowT + + for rows.Next() { + var r rowT + if err := rows.Scan( + &r.oldID, &r.key, + &r.tags, &r.lastStream, + &r.watching, &r.favorite, &r.hot, &r.keep, &r.liked, + &r.createdAt, &r.updatedAt, + ); err != nil { + continue + } + r.key = strings.TrimSpace(r.key) + if r.key == "" || strings.TrimSpace(r.oldID) == "" { + continue + } + items = append(items, r) + } + + if len(items) == 0 { + return nil + } + + s.mu.Lock() + defer s.mu.Unlock() + + tx, err := s.db.Begin() + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + const host = "chaturbate.com" + + for _, it := range items { + newInput := "https://" + host + "/" + it.key + "/" + newPath := "/" + it.key + "/" + + // Ziel-Datensatz: wenn bereits chaturbate.com: existiert, dorthin mergen + var targetID string + err := tx.QueryRow(` +SELECT id +FROM models +WHERE lower(trim(host)) = lower(?) AND lower(trim(model_key)) = lower(?) +LIMIT 1; +`, host, it.key).Scan(&targetID) + + if errors.Is(err, sql.ErrNoRows) { + targetID = "" + err = nil + } + if err != nil { + return err + } + + var likedArg any + if it.liked.Valid { + likedArg = it.liked.Int64 + } else { + likedArg = nil + } + + // Wenn es keinen Ziel-Datensatz gibt: neu anlegen mit canonical ID + if targetID == "" { + targetID = canonicalID(host, it.key) + + _, err = tx.Exec(` +INSERT INTO models ( + id,input,is_url,host,path,model_key, + tags,last_stream, + watching,favorite,hot,keep,liked, + created_at,updated_at +) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?); +`, + targetID, newInput, int64(1), host, newPath, it.key, + it.tags, it.lastStream, + it.watching, it.favorite, it.hot, it.keep, likedArg, + it.createdAt, it.updatedAt, + ) + if err != nil { + return err + } + } else { + // Ziel existiert: Flags mergen + fehlende Felder auffüllen + _, err = tx.Exec(` +UPDATE models SET + input = CASE + WHEN is_url=0 OR input IS NULL OR trim(input)='' OR lower(trim(input))=lower(trim(model_key)) + THEN ? ELSE input END, + is_url = CASE WHEN is_url=0 THEN 1 ELSE is_url END, + host = CASE WHEN host IS NULL OR trim(host)='' THEN ? ELSE host END, + path = CASE WHEN path IS NULL OR trim(path)='' THEN ? ELSE path END, + + tags = CASE WHEN (tags IS NULL OR tags='') AND ?<>'' THEN ? ELSE tags END, + last_stream = CASE WHEN (last_stream IS NULL OR last_stream='') AND ?<>'' THEN ? ELSE last_stream END, + + watching = CASE WHEN ?=1 THEN 1 ELSE watching END, + favorite = CASE WHEN ?=1 THEN 1 ELSE favorite END, + hot = CASE WHEN ?=1 THEN 1 ELSE hot END, + keep = CASE WHEN ?=1 THEN 1 ELSE keep END, + liked = CASE WHEN liked IS NULL AND ? IS NOT NULL THEN ? ELSE liked END, + + updated_at = CASE WHEN updated_at < ? THEN ? ELSE updated_at END +WHERE id = ?; +`, + newInput, host, newPath, + it.tags, it.tags, + it.lastStream, it.lastStream, + it.watching, it.favorite, it.hot, it.keep, + likedArg, likedArg, + it.updatedAt, it.updatedAt, + targetID, + ) + if err != nil { + return err + } + } + + // alten "manual" Datensatz löschen (nur wenn anderer Ziel-Datensatz) + if it.oldID != targetID { + if _, err := tx.Exec(`DELETE FROM models WHERE id=?;`, it.oldID); err != nil { + return err + } + } + } + + return tx.Commit() +} + func (s *ModelStore) List() []StoredModel { if err := s.ensureInit(); err != nil { return []StoredModel{} } rows, err := s.db.Query(` -SELECT - id,input,is_url,host,path,model_key, - tags, COALESCE(last_stream,''), - watching,favorite,hot,keep,liked, - created_at,updated_at -FROM models -ORDER BY updated_at DESC; -`) + SELECT + id,input,is_url,host,path,model_key, + tags, COALESCE(last_stream,''), + watching,favorite,hot,keep,liked, + created_at,updated_at + FROM models + ORDER BY updated_at DESC; + `) if err != nil { return []StoredModel{} } @@ -643,31 +1030,31 @@ func (s *ModelStore) PatchFlags(patch ModelFlagsPatch) (StoredModel, error) { return StoredModel{}, err } - if patch.Watching != nil { - watching = boolToInt(*patch.Watching) + // ✅ watched -> watching (DB) + if patch.Watched != nil { + watching = boolToInt(*patch.Watched) } + if patch.Favorite != nil { favorite = boolToInt(*patch.Favorite) } - if patch.Hot != nil { - hot = boolToInt(*patch.Hot) + + // ✅ liked ist true/false (kein ClearLiked mehr) + if patch.Liked != nil { + liked = sql.NullInt64{Valid: true, Int64: boolToInt(*patch.Liked)} } - if patch.Keep != nil { - keep = boolToInt(*patch.Keep) - } - // ✅ Business-Rule (robust, auch wenn Frontend es mal nicht mitsendet): - // - Liked=true => Favorite=false - // - Favorite=true => Liked wird gelöscht (NULL) + + // ✅ Exklusivität serverseitig (robust): + // - liked=true => favorite=false + // - favorite=true => liked=false (nicht NULL) if patch.Liked != nil && *patch.Liked { favorite = int64(0) } if patch.Favorite != nil && *patch.Favorite { - liked = sql.NullInt64{Valid: false} - } - if patch.ClearLiked { - liked = sql.NullInt64{Valid: false} - } else if patch.Liked != nil { - liked = sql.NullInt64{Valid: true, Int64: boolToInt(*patch.Liked)} + // Wenn Frontend nicht explizit liked=true sendet, force liked=false + if patch.Liked == nil || !*patch.Liked { + liked = sql.NullInt64{Valid: true, Int64: 0} + } } now := time.Now().UTC().Format(time.RFC3339Nano) diff --git a/backend/myfreecams_autostart.go b/backend/myfreecams_autostart.go new file mode 100644 index 0000000..03f49a4 --- /dev/null +++ b/backend/myfreecams_autostart.go @@ -0,0 +1,185 @@ +package main + +import ( + "os" + "strings" + "time" +) + +// Startet watched MyFreeCams Models (ohne API) "best-effort". +// Wenn nach kurzer Zeit keine Output-Datei existiert (oder 0 Bytes), wird abgebrochen und der Job wieder entfernt. +func startMyFreeCamsAutoStartWorker(store *ModelStore) { + if store == nil { + return + } + + // pro Model: Retry-Cooldown, damit du nicht permanent die gleichen Models spamst + const cooldown = 2 * time.Minute + + // wie lange wir nach Start warten, ob eine Datei entsteht + const outputProbeMax = 12 * time.Second + + lastAttempt := map[string]time.Time{} + + tick := time.NewTicker(6 * time.Second) + defer tick.Stop() + + for range tick.C { + s := getSettings() + if !s.UseMyFreeCamsWatcher { + continue + } + + // watched Models aus DB + watched := store.ListWatchedLite("myfreecams.com") + if len(watched) == 0 { + continue + } + + // langsam nacheinander starten (keine API -> einzelnes "Anprobieren") + for _, m := range watched { + + // ✅ Wenn User den Switch während eines Ticks deaktiviert, sofort stoppen + if !getSettings().UseMyFreeCamsWatcher { + break + } + + // ✅ Wenn im UI "Alle Stoppen" -> Autostart pausiert, sofort aufhören + if isAutostartPaused() { + break + } + + u := strings.TrimSpace(m.Input) + if u == "" { + continue + } + + modelID := strings.TrimSpace(m.ID) + if modelID == "" { + // Fallback + modelID = strings.TrimSpace(m.Host) + ":" + strings.TrimSpace(m.ModelKey) + } + + // Cooldown + if t, ok := lastAttempt[modelID]; ok && time.Since(t) < cooldown { + continue + } + + // bereits als Job aktiv? + if isJobRunningForURL(u) { + continue + } + + lastAttempt[modelID] = time.Now() + + job, err := startRecordingInternal(RecordRequest{URL: u, Hidden: true}) + if err != nil || job == nil { + continue + } + + // Output prüfen: wenn nichts entsteht -> abbrechen + aus jobs entfernen + go mfcAbortIfNoOutput(job.ID, outputProbeMax) + + // kleine Pause, damit du nicht 20 Models in einem Tick startest + time.Sleep(1200 * time.Millisecond) + } + } +} + +func isJobRunningForURL(u string) bool { + u = strings.TrimSpace(u) + if u == "" { + return false + } + + jobsMu.Lock() + defer jobsMu.Unlock() + + for _, j := range jobs { + if j == nil { + continue + } + if j.Status == JobRunning && strings.TrimSpace(j.SourceURL) == u { + return true + } + } + return false +} + +// Wenn nach maxWait keine Output-Datei (>0 Bytes) existiert, stoppen + Job entfernen. +// Hintergrund: bei MFC kann "offline/away/private" sein => keine Ausgabe entsteht. +func mfcAbortIfNoOutput(jobID string, maxWait time.Duration) { + deadline := time.Now().Add(maxWait) + + for time.Now().Before(deadline) { + jobsMu.Lock() + job := jobs[jobID] + status := JobStatus("") + out := "" + if job != nil { + status = job.Status + out = strings.TrimSpace(job.Output) + } + jobsMu.Unlock() + + // Job schon weg oder nicht mehr running -> nix tun + if job == nil || status != JobRunning { + return + } + + // Output schon da? + if out != "" { + if fi, err := os.Stat(out); err == nil && !fi.IsDir() && fi.Size() > 0 { + // ✅ jetzt ist es ein "echter" Download -> im UI sichtbar machen + publishJob(jobID) + return + } + } + + time.Sleep(900 * time.Millisecond) + } + + // nach Wartezeit immer noch keine Datei => stoppen + löschen + jobsMu.Lock() + job := jobs[jobID] + if job == nil || job.Status != JobRunning { + jobsMu.Unlock() + return + } + + // Snapshot: was wir ohne Lock beenden können + pc := job.previewCmd + job.previewCmd = nil + cancel := job.cancel + out := strings.TrimSpace(job.Output) + jobsMu.Unlock() + + // preview kill + if pc != nil && pc.Process != nil { + _ = pc.Process.Kill() + } + // recording cancel + if cancel != nil { + cancel() + } + + // 0-Byte Datei ggf. wegwerfen (damit "leere Starts" nicht im recordDir liegen bleiben) + if out != "" { + if fi, err := os.Stat(out); err == nil && !fi.IsDir() && fi.Size() == 0 { + _ = os.Remove(out) + } + } + + // Job aus der Liste entfernen (UI bleibt sauber) + jobsMu.Lock() + j := jobs[jobID] + wasVisible := (j != nil && !j.Hidden) + delete(jobs, jobID) + jobsMu.Unlock() + + // ✅ wenn der Job nie sichtbar war, nicht unnötig UI refreshen + if wasVisible { + notifyJobsChanged() + } + +} diff --git a/backend/nsfwapp.exe b/backend/nsfwapp.exe index 4f0c212..b336ef8 100644 Binary files a/backend/nsfwapp.exe and b/backend/nsfwapp.exe differ diff --git a/backend/sharedelete_other.go b/backend/sharedelete_other.go index 46654bc..3c701e4 100644 --- a/backend/sharedelete_other.go +++ b/backend/sharedelete_other.go @@ -1,3 +1,5 @@ +// backend\sharedelete_other.go + //go:build !windows package main diff --git a/backend/sharedelete_windows.go b/backend/sharedelete_windows.go index 3de2d53..f8b5aaa 100644 --- a/backend/sharedelete_windows.go +++ b/backend/sharedelete_windows.go @@ -1,3 +1,5 @@ +// backend\sharedelete_windows.go + //go:build windows package main diff --git a/backend/web/dist/assets/index-ZZZa38Qs.css b/backend/web/dist/assets/index-ZZZa38Qs.css deleted file mode 100644 index a941b29..0000000 --- a/backend/web/dist/assets/index-ZZZa38Qs.css +++ /dev/null @@ -1 +0,0 @@ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-200:oklch(88.5% .062 18.334);--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-800:oklch(47.3% .137 46.201);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-200:oklch(92.5% .084 155.995);--color-green-500:oklch(72.3% .219 149.579);--color-green-700:oklch(52.7% .154 150.069);--color-emerald-50:oklch(97.9% .021 166.113);--color-emerald-100:oklch(95% .052 163.051);--color-emerald-200:oklch(90.5% .093 164.15);--color-emerald-300:oklch(84.5% .143 164.978);--color-emerald-400:oklch(76.5% .177 163.223);--color-emerald-500:oklch(69.6% .17 162.48);--color-emerald-600:oklch(59.6% .145 163.225);--color-emerald-700:oklch(50.8% .118 165.612);--color-emerald-800:oklch(43.2% .095 166.913);--color-sky-50:oklch(97.7% .013 236.62);--color-sky-200:oklch(90.1% .058 230.902);--color-sky-500:oklch(68.5% .169 237.323);--color-sky-700:oklch(50% .134 242.749);--color-blue-50:oklch(97% .014 254.604);--color-blue-100:oklch(93.2% .032 255.585);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-indigo-50:oklch(96.2% .018 272.314);--color-indigo-100:oklch(93% .034 272.788);--color-indigo-200:oklch(87% .065 274.039);--color-indigo-300:oklch(78.5% .115 274.713);--color-indigo-400:oklch(67.3% .182 276.935);--color-indigo-500:oklch(58.5% .233 277.117);--color-indigo-600:oklch(51.1% .262 276.966);--color-indigo-700:oklch(45.7% .24 277.023);--color-rose-300:oklch(81% .117 11.638);--color-rose-500:oklch(64.5% .246 16.439);--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-800:oklch(27.8% .033 256.848);--color-gray-900:oklch(21% .034 264.665);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-lg:32rem;--container-7xl:80rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--font-weight-medium:500;--font-weight-semibold:600;--tracking-wide:.025em;--leading-tight:1.25;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--ease-in:cubic-bezier(.4,0,1,1);--ease-out:cubic-bezier(0,0,.2,1);--ease-in-out:cubic-bezier(.4,0,.2,1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4,0,.6,1)infinite;--blur-sm:8px;--blur-md:12px;--aspect-video:16/9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing)*0)}.inset-4{inset:calc(var(--spacing)*4)}.inset-x-0{inset-inline:calc(var(--spacing)*0)}.inset-x-2{inset-inline:calc(var(--spacing)*2)}.inset-x-3{inset-inline:calc(var(--spacing)*3)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.right-12{right:calc(var(--spacing)*12)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-2{bottom:calc(var(--spacing)*2)}.bottom-3{bottom:calc(var(--spacing)*3)}.bottom-7{bottom:calc(var(--spacing)*7)}.left-0{left:calc(var(--spacing)*0)}.left-2{left:calc(var(--spacing)*2)}.isolate{isolation:isolate}.z-0{z-index:0}.z-10{z-index:10}.z-20{z-index:20}.z-40{z-index:40}.z-50{z-index:50}.col-span-1{grid-column:span 1/span 1}.col-start-1{grid-column-start:1}.row-start-1{grid-row-start:1}.mx-2{margin-inline:calc(var(--spacing)*2)}.mx-auto{margin-inline:auto}.-my-1{margin-block:calc(var(--spacing)*-1)}.mt-0\.5{margin-top:calc(var(--spacing)*.5)}.mt-1{margin-top:calc(var(--spacing)*1)}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mt-4{margin-top:calc(var(--spacing)*4)}.mt-6{margin-top:calc(var(--spacing)*6)}.mt-8{margin-top:calc(var(--spacing)*8)}.-mr-0\.5{margin-right:calc(var(--spacing)*-.5)}.mr-2{margin-right:calc(var(--spacing)*2)}.-mb-px{margin-bottom:-1px}.mb-3{margin-bottom:calc(var(--spacing)*3)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.-ml-0\.5{margin-left:calc(var(--spacing)*-.5)}.-ml-px{margin-left:-1px}.ml-1\.5{margin-left:calc(var(--spacing)*1.5)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-3{margin-left:calc(var(--spacing)*3)}.block{display:block}.flex{display:flex}.flow-root{display:flow-root}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.size-1\.5{width:calc(var(--spacing)*1.5);height:calc(var(--spacing)*1.5)}.size-3{width:calc(var(--spacing)*3);height:calc(var(--spacing)*3)}.size-4{width:calc(var(--spacing)*4);height:calc(var(--spacing)*4)}.size-5{width:calc(var(--spacing)*5);height:calc(var(--spacing)*5)}.size-full{width:100%;height:100%}.h-0\.5{height:calc(var(--spacing)*.5)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-9{height:calc(var(--spacing)*9)}.h-12{height:calc(var(--spacing)*12)}.h-16{height:calc(var(--spacing)*16)}.h-20{height:calc(var(--spacing)*20)}.h-24{height:calc(var(--spacing)*24)}.h-28{height:calc(var(--spacing)*28)}.h-full{height:100%}.min-h-0{min-height:calc(var(--spacing)*0)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-6{width:calc(var(--spacing)*6)}.w-9{width:calc(var(--spacing)*9)}.w-10{width:calc(var(--spacing)*10)}.w-11{width:calc(var(--spacing)*11)}.w-12{width:calc(var(--spacing)*12)}.w-20{width:calc(var(--spacing)*20)}.w-28{width:calc(var(--spacing)*28)}.w-\[140px\]{width:140px}.w-\[220px\]{width:220px}.w-\[420px\]{width:420px}.w-full{width:100%}.max-w-7xl{max-width:var(--container-7xl)}.max-w-\[11rem\]{max-width:11rem}.max-w-\[70vw\]{max-width:70vw}.max-w-\[240px\]{max-width:240px}.max-w-\[520px\]{max-width:520px}.max-w-\[calc\(100vw-1\.5rem\)\]{max-width:calc(100vw - 1.5rem)}.max-w-\[calc\(100vw-16px\)\]{max-width:calc(100vw - 16px)}.max-w-lg{max-width:var(--container-lg)}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-\[220px\]{min-width:220px}.min-w-full{min-width:100%}.flex-1{flex:1}.flex-none{flex:none}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.translate-x-5{--tw-translate-x:calc(var(--spacing)*5);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-0{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-2{--tw-translate-y:calc(var(--spacing)*2);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-4{--tw-translate-y:calc(var(--spacing)*4);translate:var(--tw-translate-x)var(--tw-translate-y)}.scale-\[0\.98\]{scale:.98}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.resize{resize:both}.appearance-none{appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-1{gap:calc(var(--spacing)*1)}.gap-1\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*4)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*6)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*6)*calc(1 - var(--tw-space-y-reverse)))}.gap-x-1\.5{column-gap:calc(var(--spacing)*1.5)}.gap-x-8{column-gap:calc(var(--spacing)*8)}:where(.-space-x-px>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(-1px*var(--tw-space-x-reverse));margin-inline-end:calc(-1px*calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-4>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*4)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-8>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*8)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*8)*calc(1 - var(--tw-space-x-reverse)))}:where(.divide-x>:not(:last-child)){--tw-divide-x-reverse:0;border-inline-style:var(--tw-border-style);border-inline-start-width:calc(1px*var(--tw-divide-x-reverse));border-inline-end-width:calc(1px*calc(1 - var(--tw-divide-x-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-gray-200>:not(:last-child)){border-color:var(--color-gray-200)}.self-center{align-self:center}.justify-self-end{justify-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-none{border-radius:0}.rounded-sm{border-radius:var(--radius-sm)}.rounded-l-lg{border-top-left-radius:var(--radius-lg);border-bottom-left-radius:var(--radius-lg)}.rounded-l-md{border-top-left-radius:var(--radius-md);border-bottom-left-radius:var(--radius-md)}.rounded-r-lg{border-top-right-radius:var(--radius-lg);border-bottom-right-radius:var(--radius-lg)}.rounded-r-md{border-top-right-radius:var(--radius-md);border-bottom-right-radius:var(--radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-gray-200{border-color:var(--color-gray-200)}.border-gray-300{border-color:var(--color-gray-300)}.border-indigo-500{border-color:var(--color-indigo-500)}.border-transparent{border-color:#0000}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/15{background-color:#f99c0026}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/15{background-color:color-mix(in oklab,var(--color-amber-500)15%,transparent)}}.bg-amber-500\/25{background-color:#f99c0040}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/25{background-color:color-mix(in oklab,var(--color-amber-500)25%,transparent)}}.bg-black{background-color:var(--color-black)}.bg-black\/5{background-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.bg-black\/5{background-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab,red,red)){.bg-black\/40{background-color:color-mix(in oklab,var(--color-black)40%,transparent)}}.bg-black\/45{background-color:#00000073}@supports (color:color-mix(in lab,red,red)){.bg-black\/45{background-color:color-mix(in oklab,var(--color-black)45%,transparent)}}.bg-black\/55{background-color:#0000008c}@supports (color:color-mix(in lab,red,red)){.bg-black\/55{background-color:color-mix(in oklab,var(--color-black)55%,transparent)}}.bg-blue-50{background-color:var(--color-blue-50)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-emerald-50{background-color:var(--color-emerald-50)}.bg-emerald-50\/60{background-color:#ecfdf599}@supports (color:color-mix(in lab,red,red)){.bg-emerald-50\/60{background-color:color-mix(in oklab,var(--color-emerald-50)60%,transparent)}}.bg-emerald-500\/20{background-color:#00bb7f33}@supports (color:color-mix(in lab,red,red)){.bg-emerald-500\/20{background-color:color-mix(in oklab,var(--color-emerald-500)20%,transparent)}}.bg-emerald-600{background-color:var(--color-emerald-600)}.bg-gray-50{background-color:var(--color-gray-50)}.bg-gray-50\/90{background-color:#f9fafbe6}@supports (color:color-mix(in lab,red,red)){.bg-gray-50\/90{background-color:color-mix(in oklab,var(--color-gray-50)90%,transparent)}}.bg-gray-100{background-color:var(--color-gray-100)}.bg-gray-200{background-color:var(--color-gray-200)}.bg-gray-500\/75{background-color:#6a7282bf}@supports (color:color-mix(in lab,red,red)){.bg-gray-500\/75{background-color:color-mix(in oklab,var(--color-gray-500)75%,transparent)}}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-indigo-50{background-color:var(--color-indigo-50)}.bg-indigo-100{background-color:var(--color-indigo-100)}.bg-indigo-500{background-color:var(--color-indigo-500)}.bg-indigo-600{background-color:var(--color-indigo-600)}.bg-red-50{background-color:var(--color-red-50)}.bg-red-50\/60{background-color:#fef2f299}@supports (color:color-mix(in lab,red,red)){.bg-red-50\/60{background-color:color-mix(in oklab,var(--color-red-50)60%,transparent)}}.bg-red-500\/20{background-color:#fb2c3633}@supports (color:color-mix(in lab,red,red)){.bg-red-500\/20{background-color:color-mix(in oklab,var(--color-red-500)20%,transparent)}}.bg-red-600{background-color:var(--color-red-600)}.bg-red-600\/35{background-color:#e4001459}@supports (color:color-mix(in lab,red,red)){.bg-red-600\/35{background-color:color-mix(in oklab,var(--color-red-600)35%,transparent)}}.bg-red-600\/90{background-color:#e40014e6}@supports (color:color-mix(in lab,red,red)){.bg-red-600\/90{background-color:color-mix(in oklab,var(--color-red-600)90%,transparent)}}.bg-sky-50{background-color:var(--color-sky-50)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.bg-white\/60{background-color:#fff9}@supports (color:color-mix(in lab,red,red)){.bg-white\/60{background-color:color-mix(in oklab,var(--color-white)60%,transparent)}}.bg-white\/70{background-color:#ffffffb3}@supports (color:color-mix(in lab,red,red)){.bg-white\/70{background-color:color-mix(in oklab,var(--color-white)70%,transparent)}}.bg-gradient-to-t{--tw-gradient-position:to top in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-black\/65{--tw-gradient-from:#000000a6}@supports (color:color-mix(in lab,red,red)){.from-black\/65{--tw-gradient-from:color-mix(in oklab,var(--color-black)65%,transparent)}}.from-black\/65{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-black\/70{--tw-gradient-from:#000000b3}@supports (color:color-mix(in lab,red,red)){.from-black\/70{--tw-gradient-from:color-mix(in oklab,var(--color-black)70%,transparent)}}.from-black\/70{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-transparent{--tw-gradient-to:transparent;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.fill-gray-500{fill:var(--color-gray-500)}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing)*0)}.p-0\.5{padding:calc(var(--spacing)*.5)}.p-1\.5{padding:calc(var(--spacing)*1.5)}.p-2{padding:calc(var(--spacing)*2)}.p-4{padding:calc(var(--spacing)*4)}.p-6{padding:calc(var(--spacing)*6)}.px-1{padding-inline:calc(var(--spacing)*1)}.px-1\.5{padding-inline:calc(var(--spacing)*1.5)}.px-2{padding-inline:calc(var(--spacing)*2)}.px-2\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-3\.5{padding-inline:calc(var(--spacing)*3.5)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-0\.5{padding-block:calc(var(--spacing)*.5)}.py-1{padding-block:calc(var(--spacing)*1)}.py-1\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-2\.5{padding-block:calc(var(--spacing)*2.5)}.py-3{padding-block:calc(var(--spacing)*3)}.py-3\.5{padding-block:calc(var(--spacing)*3.5)}.py-4{padding-block:calc(var(--spacing)*4)}.py-5{padding-block:calc(var(--spacing)*5)}.py-6{padding-block:calc(var(--spacing)*6)}.pt-4{padding-top:calc(var(--spacing)*4)}.pr-8{padding-right:calc(var(--spacing)*8)}.pb-\[env\(safe-area-inset-bottom\)\]{padding-bottom:env(safe-area-inset-bottom)}.pl-3{padding-left:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-sm\/6{font-size:var(--text-sm);line-height:calc(var(--spacing)*6)}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.whitespace-nowrap{white-space:nowrap}.text-amber-300{color:var(--color-amber-300)}.text-amber-500{color:var(--color-amber-500)}.text-amber-600{color:var(--color-amber-600)}.text-amber-800{color:var(--color-amber-800)}.text-blue-600{color:var(--color-blue-600)}.text-emerald-300{color:var(--color-emerald-300)}.text-emerald-600{color:var(--color-emerald-600)}.text-emerald-700{color:var(--color-emerald-700)}.text-emerald-800{color:var(--color-emerald-800)}.text-gray-400{color:var(--color-gray-400)}.text-gray-500{color:var(--color-gray-500)}.text-gray-600{color:var(--color-gray-600)}.text-gray-700{color:var(--color-gray-700)}.text-gray-800{color:var(--color-gray-800)}.text-gray-900{color:var(--color-gray-900)}.text-green-700{color:var(--color-green-700)}.text-indigo-500{color:var(--color-indigo-500)}.text-indigo-600{color:var(--color-indigo-600)}.text-indigo-700{color:var(--color-indigo-700)}.text-red-300{color:var(--color-red-300)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-red-800{color:var(--color-red-800)}.text-rose-300{color:var(--color-rose-300)}.text-rose-500{color:var(--color-rose-500)}.text-sky-700{color:var(--color-sky-700)}.text-white{color:var(--color-white)}.text-white\/80{color:#fffc}@supports (color:color-mix(in lab,red,red)){.text-white\/80{color:color-mix(in oklab,var(--color-white)80%,transparent)}}.text-white\/90{color:#ffffffe6}@supports (color:color-mix(in lab,red,red)){.text-white\/90{color:color-mix(in oklab,var(--color-white)90%,transparent)}}.italic{font-style:italic}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.opacity-100{opacity:1}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a),0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow:0 1px 2px 0 var(--tw-shadow-color,#0000000d);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-1{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(1px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.inset-ring,.inset-ring-1{--tw-inset-ring-shadow:inset 0 0 0 1px var(--tw-inset-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-amber-200{--tw-ring-color:var(--color-amber-200)}.ring-black\/5{--tw-ring-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.ring-black\/5{--tw-ring-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.ring-black\/10{--tw-ring-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.ring-black\/10{--tw-ring-color:color-mix(in oklab,var(--color-black)10%,transparent)}}.ring-emerald-200{--tw-ring-color:var(--color-emerald-200)}.ring-emerald-300{--tw-ring-color:var(--color-emerald-300)}.ring-gray-200{--tw-ring-color:var(--color-gray-200)}.ring-gray-900\/5{--tw-ring-color:#1018280d}@supports (color:color-mix(in lab,red,red)){.ring-gray-900\/5{--tw-ring-color:color-mix(in oklab,var(--color-gray-900)5%,transparent)}}.ring-red-200{--tw-ring-color:var(--color-red-200)}.ring-red-300{--tw-ring-color:var(--color-red-300)}.inset-ring-gray-300{--tw-inset-ring-color:var(--color-gray-300)}.inset-ring-gray-900\/5{--tw-inset-ring-color:#1018280d}@supports (color:color-mix(in lab,red,red)){.inset-ring-gray-900\/5{--tw-inset-ring-color:color-mix(in oklab,var(--color-gray-900)5%,transparent)}}.outline-1{outline-style:var(--tw-outline-style);outline-width:1px}.-outline-offset-1{outline-offset:-1px}.outline-offset-2{outline-offset:2px}.outline-black\/5{outline-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.outline-black\/5{outline-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.outline-gray-300{outline-color:var(--color-gray-300)}.outline-indigo-600{outline-color:var(--color-indigo-600)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.blur-md{--tw-blur:blur(var(--blur-md));filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-\[1px\]{--tw-backdrop-blur:blur(1px);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-100{--tw-duration:.1s;transition-duration:.1s}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.select-none{-webkit-user-select:none;user-select:none}.ring-inset{--tw-ring-inset:inset}.group-focus-within\:opacity-0:is(:where(.group):focus-within *){opacity:0}.group-focus-within\:opacity-100:is(:where(.group):focus-within *){opacity:1}@media(hover:hover){.group-hover\:pointer-events-auto:is(:where(.group):hover *){pointer-events:auto}.group-hover\:visible:is(:where(.group):hover *){visibility:visible}.group-hover\:text-gray-500:is(:where(.group):hover *){color:var(--color-gray-500)}.group-hover\:opacity-0:is(:where(.group):hover *){opacity:0}.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.group-focus-visible\:visible:is(:where(.group):focus-visible *){visibility:visible}.file\:mr-4::file-selector-button{margin-right:calc(var(--spacing)*4)}.file\:rounded-md::file-selector-button{border-radius:var(--radius-md)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-gray-100::file-selector-button{background-color:var(--color-gray-100)}.file\:px-3::file-selector-button{padding-inline:calc(var(--spacing)*3)}.file\:py-2::file-selector-button{padding-block:calc(var(--spacing)*2)}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-semibold::file-selector-button{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.file\:text-gray-900::file-selector-button{color:var(--color-gray-900)}.even\:bg-gray-50:nth-child(2n){background-color:var(--color-gray-50)}@media(hover:hover){.hover\:-translate-y-0\.5:hover{--tw-translate-y:calc(var(--spacing)*-.5);translate:var(--tw-translate-x)var(--tw-translate-y)}.hover\:border-gray-300:hover{border-color:var(--color-gray-300)}.hover\:border-transparent:hover{border-color:#0000}.hover\:bg-amber-100:hover{background-color:var(--color-amber-100)}.hover\:bg-amber-400:hover{background-color:var(--color-amber-400)}.hover\:bg-black\/5:hover{background-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/5:hover{background-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.hover\:bg-black\/10:hover{background-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/10:hover{background-color:color-mix(in oklab,var(--color-black)10%,transparent)}}.hover\:bg-black\/55:hover{background-color:#0000008c}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/55:hover{background-color:color-mix(in oklab,var(--color-black)55%,transparent)}}.hover\:bg-black\/60:hover{background-color:#0009}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/60:hover{background-color:color-mix(in oklab,var(--color-black)60%,transparent)}}.hover\:bg-black\/65:hover{background-color:#000000a6}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/65:hover{background-color:color-mix(in oklab,var(--color-black)65%,transparent)}}.hover\:bg-black\/70:hover{background-color:#000000b3}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/70:hover{background-color:color-mix(in oklab,var(--color-black)70%,transparent)}}.hover\:bg-blue-100:hover{background-color:var(--color-blue-100)}.hover\:bg-blue-500:hover{background-color:var(--color-blue-500)}.hover\:bg-emerald-100:hover{background-color:var(--color-emerald-100)}.hover\:bg-emerald-500:hover{background-color:var(--color-emerald-500)}.hover\:bg-gray-50:hover{background-color:var(--color-gray-50)}.hover\:bg-gray-100\/70:hover{background-color:#f3f4f6b3}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-100\/70:hover{background-color:color-mix(in oklab,var(--color-gray-100)70%,transparent)}}.hover\:bg-indigo-100:hover{background-color:var(--color-indigo-100)}.hover\:bg-indigo-500:hover{background-color:var(--color-indigo-500)}.hover\:bg-red-100:hover{background-color:var(--color-red-100)}.hover\:bg-red-500:hover{background-color:var(--color-red-500)}.hover\:bg-red-600\/55:hover{background-color:#e400148c}@supports (color:color-mix(in lab,red,red)){.hover\:bg-red-600\/55:hover{background-color:color-mix(in oklab,var(--color-red-600)55%,transparent)}}.hover\:bg-transparent:hover{background-color:#0000}.hover\:text-gray-500:hover{color:var(--color-gray-500)}.hover\:text-gray-700:hover{color:var(--color-gray-700)}.hover\:text-gray-800:hover{color:var(--color-gray-800)}.hover\:text-inherit:hover{color:inherit}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-md:hover{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a),0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\:file\:bg-gray-200:hover::file-selector-button{background-color:var(--color-gray-200)}}.focus\:z-10:focus{z-index:10}.focus\:z-20:focus{z-index:20}.focus\:outline-hidden:focus{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline-offset:2px;outline:2px solid #0000}}.focus\:outline-2:focus{outline-style:var(--tw-outline-style);outline-width:2px}.focus\:-outline-offset-2:focus{outline-offset:-2px}.focus\:outline-offset-0:focus{outline-offset:0px}.focus\:outline-indigo-600:focus{outline-color:var(--color-indigo-600)}.focus-visible\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\:outline-amber-500:focus-visible{outline-color:var(--color-amber-500)}.focus-visible\:outline-blue-600:focus-visible{outline-color:var(--color-blue-600)}.focus-visible\:outline-emerald-600:focus-visible{outline-color:var(--color-emerald-600)}.focus-visible\:outline-indigo-500:focus-visible{outline-color:var(--color-indigo-500)}.focus-visible\:outline-indigo-600:focus-visible{outline-color:var(--color-indigo-600)}.focus-visible\:outline-red-600:focus-visible{outline-color:var(--color-red-600)}.focus-visible\:outline-white\/70:focus-visible{outline-color:#ffffffb3}@supports (color:color-mix(in lab,red,red)){.focus-visible\:outline-white\/70:focus-visible{outline-color:color-mix(in oklab,var(--color-white)70%,transparent)}}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.has-focus-visible\:outline-2:has(:focus-visible){outline-style:var(--tw-outline-style);outline-width:2px}@media(min-width:40rem){.sm\:inset-6{inset:calc(var(--spacing)*6)}.sm\:right-4{right:calc(var(--spacing)*4)}.sm\:bottom-4{bottom:calc(var(--spacing)*4)}.sm\:left-auto{left:auto}.sm\:col-span-2{grid-column:span 2/span 2}.sm\:col-span-3{grid-column:span 3/span 3}.sm\:col-span-9{grid-column:span 9/span 9}.sm\:mt-0{margin-top:calc(var(--spacing)*0)}.sm\:ml-16{margin-left:calc(var(--spacing)*16)}.sm\:block{display:block}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:inline{display:inline}.sm\:w-\[420px\]{width:420px}.sm\:max-w-\[360px\]{max-width:360px}.sm\:flex-1{flex:1}.sm\:flex-auto{flex:auto}.sm\:flex-none{flex:none}.sm\:translate-y-0{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.sm\:scale-95{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x)var(--tw-scale-y)}.sm\:scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x)var(--tw-scale-y)}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-12{grid-template-columns:repeat(12,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-4{gap:calc(var(--spacing)*4)}.sm\:rounded-lg{border-radius:var(--radius-lg)}.sm\:p-0{padding:calc(var(--spacing)*0)}.sm\:p-6{padding:calc(var(--spacing)*6)}.sm\:px-6{padding-inline:calc(var(--spacing)*6)}}@media(min-width:48rem){.md\:inline-block{display:inline-block}}@media(min-width:64rem){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:px-8{padding-inline:calc(var(--spacing)*8)}}@media(prefers-color-scheme:dark){:where(.dark\:divide-white\/10>:not(:last-child)){border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){:where(.dark\:divide-white\/10>:not(:last-child)){border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:border-indigo-400{border-color:var(--color-indigo-400)}.dark\:border-white\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:border-white\/10{border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:bg-amber-500{background-color:var(--color-amber-500)}.dark\:bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500)10%,transparent)}}.dark\:bg-amber-500\/15{background-color:#f99c0026}@supports (color:color-mix(in lab,red,red)){.dark\:bg-amber-500\/15{background-color:color-mix(in oklab,var(--color-amber-500)15%,transparent)}}.dark\:bg-amber-500\/20{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.dark\:bg-amber-500\/20{background-color:color-mix(in oklab,var(--color-amber-500)20%,transparent)}}.dark\:bg-blue-500{background-color:var(--color-blue-500)}.dark\:bg-blue-500\/20{background-color:#3080ff33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-blue-500\/20{background-color:color-mix(in oklab,var(--color-blue-500)20%,transparent)}}.dark\:bg-emerald-500{background-color:var(--color-emerald-500)}.dark\:bg-emerald-500\/10{background-color:#00bb7f1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-emerald-500\/10{background-color:color-mix(in oklab,var(--color-emerald-500)10%,transparent)}}.dark\:bg-emerald-500\/15{background-color:#00bb7f26}@supports (color:color-mix(in lab,red,red)){.dark\:bg-emerald-500\/15{background-color:color-mix(in oklab,var(--color-emerald-500)15%,transparent)}}.dark\:bg-emerald-500\/20{background-color:#00bb7f33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-emerald-500\/20{background-color:color-mix(in oklab,var(--color-emerald-500)20%,transparent)}}.dark\:bg-gray-700\/50{background-color:#36415380}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-700\/50{background-color:color-mix(in oklab,var(--color-gray-700)50%,transparent)}}.dark\:bg-gray-800{background-color:var(--color-gray-800)}.dark\:bg-gray-800\/50{background-color:#1e293980}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-800\/50{background-color:color-mix(in oklab,var(--color-gray-800)50%,transparent)}}.dark\:bg-gray-800\/70{background-color:#1e2939b3}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-800\/70{background-color:color-mix(in oklab,var(--color-gray-800)70%,transparent)}}.dark\:bg-gray-900{background-color:var(--color-gray-900)}.dark\:bg-gray-900\/40{background-color:#10182866}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-900\/40{background-color:color-mix(in oklab,var(--color-gray-900)40%,transparent)}}.dark\:bg-gray-900\/50{background-color:#10182880}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-900\/50{background-color:color-mix(in oklab,var(--color-gray-900)50%,transparent)}}.dark\:bg-green-500\/10{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-green-500\/10{background-color:color-mix(in oklab,var(--color-green-500)10%,transparent)}}.dark\:bg-indigo-400{background-color:var(--color-indigo-400)}.dark\:bg-indigo-500{background-color:var(--color-indigo-500)}.dark\:bg-indigo-500\/10{background-color:#625fff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-500\/10{background-color:color-mix(in oklab,var(--color-indigo-500)10%,transparent)}}.dark\:bg-indigo-500\/20{background-color:#625fff33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-500\/20{background-color:color-mix(in oklab,var(--color-indigo-500)20%,transparent)}}.dark\:bg-red-500{background-color:var(--color-red-500)}.dark\:bg-red-500\/10{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-500\/10{background-color:color-mix(in oklab,var(--color-red-500)10%,transparent)}}.dark\:bg-red-500\/15{background-color:#fb2c3626}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-500\/15{background-color:color-mix(in oklab,var(--color-red-500)15%,transparent)}}.dark\:bg-red-500\/20{background-color:#fb2c3633}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-500\/20{background-color:color-mix(in oklab,var(--color-red-500)20%,transparent)}}.dark\:bg-sky-500\/10{background-color:#00a5ef1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-sky-500\/10{background-color:color-mix(in oklab,var(--color-sky-500)10%,transparent)}}.dark\:bg-transparent{background-color:#0000}.dark\:bg-white\/5{background-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/5{background-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:bg-white\/10{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/10{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:bg-white\/20{background-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/20{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}}.dark\:fill-gray-400{fill:var(--color-gray-400)}.dark\:text-amber-200{color:var(--color-amber-200)}.dark\:text-amber-300{color:var(--color-amber-300)}.dark\:text-amber-400{color:var(--color-amber-400)}.dark\:text-blue-400{color:var(--color-blue-400)}.dark\:text-emerald-300{color:var(--color-emerald-300)}.dark\:text-emerald-400{color:var(--color-emerald-400)}.dark\:text-gray-100{color:var(--color-gray-100)}.dark\:text-gray-200{color:var(--color-gray-200)}.dark\:text-gray-300{color:var(--color-gray-300)}.dark\:text-gray-400{color:var(--color-gray-400)}.dark\:text-gray-500{color:var(--color-gray-500)}.dark\:text-gray-600{color:var(--color-gray-600)}.dark\:text-green-200{color:var(--color-green-200)}.dark\:text-indigo-200{color:var(--color-indigo-200)}.dark\:text-indigo-300{color:var(--color-indigo-300)}.dark\:text-indigo-400{color:var(--color-indigo-400)}.dark\:text-indigo-500{color:var(--color-indigo-500)}.dark\:text-red-200{color:var(--color-red-200)}.dark\:text-red-300{color:var(--color-red-300)}.dark\:text-red-400{color:var(--color-red-400)}.dark\:text-sky-200{color:var(--color-sky-200)}.dark\:text-white{color:var(--color-white)}.dark\:shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.dark\:ring-amber-500\/30{--tw-ring-color:#f99c004d}@supports (color:color-mix(in lab,red,red)){.dark\:ring-amber-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-amber-500)30%,transparent)}}.dark\:ring-emerald-500\/30{--tw-ring-color:#00bb7f4d}@supports (color:color-mix(in lab,red,red)){.dark\:ring-emerald-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-emerald-500)30%,transparent)}}.dark\:ring-red-500\/30{--tw-ring-color:#fb2c364d}@supports (color:color-mix(in lab,red,red)){.dark\:ring-red-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-red-500)30%,transparent)}}.dark\:ring-white\/10{--tw-ring-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:ring-white\/10{--tw-ring-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:inset-ring-gray-700{--tw-inset-ring-color:var(--color-gray-700)}.dark\:inset-ring-white\/5{--tw-inset-ring-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:inset-ring-white\/5{--tw-inset-ring-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:inset-ring-white\/10{--tw-inset-ring-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:inset-ring-white\/10{--tw-inset-ring-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:outline{outline-style:var(--tw-outline-style);outline-width:1px}.dark\:-outline-offset-1{outline-offset:-1px}.dark\:outline-indigo-500{outline-color:var(--color-indigo-500)}.dark\:outline-white\/10{outline-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:outline-white\/10{outline-color:color-mix(in oklab,var(--color-white)10%,transparent)}}:is(.dark\:\*\:bg-gray-800>*){background-color:var(--color-gray-800)}@media(hover:hover){.dark\:group-hover\:text-gray-400:is(:where(.group):hover *){color:var(--color-gray-400)}}.dark\:file\:bg-white\/10::file-selector-button{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:file\:bg-white\/10::file-selector-button{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:file\:text-white::file-selector-button{color:var(--color-white)}.dark\:even\:bg-gray-800\/50:nth-child(2n){background-color:#1e293980}@supports (color:color-mix(in lab,red,red)){.dark\:even\:bg-gray-800\/50:nth-child(2n){background-color:color-mix(in oklab,var(--color-gray-800)50%,transparent)}}@media(hover:hover){.dark\:hover\:border-white\/20:hover{border-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:border-white\/20:hover{border-color:color-mix(in oklab,var(--color-white)20%,transparent)}}.dark\:hover\:bg-amber-400:hover{background-color:var(--color-amber-400)}.dark\:hover\:bg-amber-500\/30:hover{background-color:#f99c004d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-amber-500\/30:hover{background-color:color-mix(in oklab,var(--color-amber-500)30%,transparent)}}.dark\:hover\:bg-blue-400:hover{background-color:var(--color-blue-400)}.dark\:hover\:bg-blue-500\/30:hover{background-color:#3080ff4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-blue-500\/30:hover{background-color:color-mix(in oklab,var(--color-blue-500)30%,transparent)}}.dark\:hover\:bg-emerald-400:hover{background-color:var(--color-emerald-400)}.dark\:hover\:bg-emerald-500\/30:hover{background-color:#00bb7f4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-emerald-500\/30:hover{background-color:color-mix(in oklab,var(--color-emerald-500)30%,transparent)}}.dark\:hover\:bg-indigo-400:hover{background-color:var(--color-indigo-400)}.dark\:hover\:bg-indigo-500\/30:hover{background-color:#625fff4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-indigo-500\/30:hover{background-color:color-mix(in oklab,var(--color-indigo-500)30%,transparent)}}.dark\:hover\:bg-red-400:hover{background-color:var(--color-red-400)}.dark\:hover\:bg-red-500\/30:hover{background-color:#fb2c364d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-red-500\/30:hover{background-color:color-mix(in oklab,var(--color-red-500)30%,transparent)}}.dark\:hover\:bg-white\/5:hover{background-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/5:hover{background-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:hover\:bg-white\/10:hover{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/10:hover{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:hover\:bg-white\/15:hover{background-color:#ffffff26}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/15:hover{background-color:color-mix(in oklab,var(--color-white)15%,transparent)}}.dark\:hover\:bg-white\/20:hover{background-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/20:hover{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}}.dark\:hover\:text-gray-200:hover{color:var(--color-gray-200)}.dark\:hover\:text-gray-300:hover{color:var(--color-gray-300)}.dark\:hover\:text-gray-400:hover{color:var(--color-gray-400)}.dark\:hover\:text-white:hover{color:var(--color-white)}.dark\:hover\:shadow-none:hover{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.dark\:hover\:file\:bg-white\/20:hover::file-selector-button{background-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:file\:bg-white\/20:hover::file-selector-button{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}}}.dark\:focus\:outline-indigo-500:focus{outline-color:var(--color-indigo-500)}.dark\:focus-visible\:outline-amber-500:focus-visible{outline-color:var(--color-amber-500)}.dark\:focus-visible\:outline-blue-500:focus-visible{outline-color:var(--color-blue-500)}.dark\:focus-visible\:outline-emerald-500:focus-visible{outline-color:var(--color-emerald-500)}.dark\:focus-visible\:outline-indigo-500:focus-visible{outline-color:var(--color-indigo-500)}.dark\:focus-visible\:outline-red-500:focus-visible{outline-color:var(--color-red-500)}}}:root{color-scheme:light dark;color:#ffffffde;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background-color:#242424;font-family:system-ui,Avenir,Helvetica,Arial,sans-serif;font-weight:400;line-height:1.5}@media(prefers-color-scheme:light){:root{color:#213547;background-color:#fff}a:hover{color:#747bff}button{background-color:#f9f9f9}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}}.vjs-svg-icon{display:inline-block;background-repeat:no-repeat;background-position:center;fill:currentColor;height:1.8em;width:1.8em}.vjs-svg-icon:before{content:none!important}.vjs-svg-icon:hover,.vjs-control:focus .vjs-svg-icon{filter:drop-shadow(0 0 .25em #fff)}.vjs-modal-dialog .vjs-modal-dialog-content,.video-js .vjs-modal-dialog,.vjs-button>.vjs-icon-placeholder:before,.video-js .vjs-big-play-button .vjs-icon-placeholder:before{position:absolute;top:0;left:0;width:100%;height:100%}.vjs-button>.vjs-icon-placeholder:before,.video-js .vjs-big-play-button .vjs-icon-placeholder:before{text-align:center}@font-face{font-family:VideoJS;src:url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABTsAAsAAAAAIpAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAADsAAABUIIslek9TLzIAAAFEAAAAPgAAAFZRiV32Y21hcAAAAYQAAAEJAAAD5p42+VxnbHlmAAACkAAADtIAABckI4l972hlYWQAABFkAAAAKwAAADYsvIjpaGhlYQAAEZAAAAAdAAAAJA+RCL1obXR4AAARsAAAABcAAAC8Q2YAAGxvY2EAABHIAAAAYAAAAGB7CIGGbWF4cAAAEigAAAAfAAAAIAFAAI9uYW1lAAASSAAAASUAAAIK1cf1oHBvc3QAABNwAAABfAAAAnXdFqh1eJxjYGRgYOBiMGCwY2BycfMJYeDLSSzJY5BiYGGAAJA8MpsxJzM9kYEDxgPKsYBpDiBmg4gCACY7BUgAeJxjYGR7yDiBgZWBgaWQ5RkDA8MvCM0cwxDOeI6BgYmBlZkBKwhIc01hcPjI+FGPHcRdyA4RZgQRADaGCyYAAHic7dPXbcMwAEXRK1vuvffem749XAbKV3bjBA6fXsaIgMMLEWoQJaAEFKNnlELyQ4K27zib5PNF6vl8yld+TKr5kH0+cUw0xv00Hwvx2DResUyFKrV4XoMmLdp06NKjz4AhI8ZMmDJjzoIlK9Zs2LJjz4EjJ85cuHLjziPe/0UWL17mf2tqKLz/9jK9f8tXpGCoRdPKhtS0RqFkWvVQNtSKoVYNtWaoddPXEBqG2jQ9XWgZattQO4baNdSeofYNdWCoQ0MdGerYUCeGOjXUmaHODXVhqEtDXRnq2lA3hro11J2h7g31YKhHQz0Z6tlQL4Z6NdSbod4N9WGoT9MfHF6GmhnZLxyDcRMAAAB4nJ1YC1hU17U+a5/HMA4iA3NmVBDmoQwP5TFnHlFeA4gYiUFRQINoSCBAyK3G2yi+0aipYtFcHYo2xsb4NiY3+VrNxSaX5uvt495ozNdoYoxmem2/L8HGpLc+InB279pnhlGr5mvL4eyz99nrrL32eu1/DQcc/okdYgdHOA6MQKp4r9gx0EcMHMezOalVasW5BM7NcXoSb9fFgE6KtSSBxWz1FYDPG+vMBGcKb9cebu2VS5s2aaTkCvRSf6C7Y+Ppibm5E09v7IDs2/3uZQtbD0zIyppwoHXh/93ukmyYgdePNRp65p5v+3v/9otQl2O7wP34cT88p8Md2YxpYLQZoRcy6FlSBRnwnGAe6BPMSCZo+7NJVqS0cE4uHendzhSnbPH6TDqL1+Nme5LZXkCHnGyoH0kne30WH+gswhm3q+pt/mTas9NLS64GnjmSlTPw0wVQT/ewRaBgxtydy3cuUB9/6SW+vb5yRvr+t0eOfPKJZ/9t3+4tL7xj32Xd3thCxi+ge6ifdsAN+l5+wi5HQ/cCoeull1AszS7CUfEcJzK7sKWJAdJhCd0sPM4+EY7QDm5ov08hXRQXE5bf6PV5Q5+IjW7X7Nku92Ask4l2hCRRD6TPqISiCJeQna3SCFwrhrNzXHzo4yFevBwxpzxk8WCIIfkvVEKVy32SbT8n68gzgaslpaiO2zIGIyuSb7RNf9HSuN26y/7OC1tgEmpiyA6aD4qcgTOiLThwGG0eB694FI8NHLLN6OBlRVaMxNAFS4JdXUG6mW8PwpKuYLCLXKGbu8iwYNdgO06Sn3Th+/vyZAxs8Ro30DjHe9gy8Fywi24OMm7Qyzh3MTZVOMYhLBnoC+J79lpTUyQmorjhnMwlcQ5uPEYGpDjsOkkH49BjQLQBqs3jFtFdJNlksYmoQFDArLh8Xh+Qd6Ghcsb6FUuehDi+U/lqD71K/qiegeV1imcwjl7ExwiSrf4BZyCujV6cVcFo6VX+G9IcPyFjJnUufbU/jzrL1X99as36reXl8K32nFaOr+E8jWJEcJ55DpMVfSMe95/AJaOsGBH2GJCNpiRQbK4C8BjdmQA22QY2j03Em13i2YHqtNLU1NI04Yj2HJgA6fQc6VPNpA/D+Ryks554NnVy2mB72uRUfPLsqR4N0LOBQKArwJYO+5W2fgZX8oC1HR6HjNaQTVIG2FPwnTcXXGZZfNB7TE6pTKZUwaw91XWLAoFFGcnB5PHjsckgBjbWutrL+0h5Y1xw3DRGDumsnXb3MJwXrJIN5U7m0rgJ3yG5w4he5ckFG4pmNEkOm0/xOO4r4yL87wqtQM+hiJIVp+6iG2wPBKD35ElGkDx+UfC2v1mFG1o+M3AjNFty8biKMXwzyxnZLds8wYD2BxmCPHAldPOeLsy/0BugftYhVYFAhO8SqQ0j3oK7dHJZnI/jxmUS4onlxskSF8thmvNZjIrRZwEPxr0lBuLRuz3oy/FOHCsxwOPYh2M+e9u3J5pgPYz9gp6G7C9m0A11F9ddqKMfV+4sbq45/YspOysXvT+3pdFdYNg2fHbW8Dz301MqDVuGrz0Fuh0YMW8mddrpqzST7rV9BcvqPoNvadRndWp0p8HvbiqrFj5yFQ/vNFSXDpxpLEFWp+DcrF3FT1afWshFcmCfeAMjEvO65i0Y6XijQfSRPWx3TV/Df7Km3E1l+kLt56s/rwVzuRusNMhudznkwdLaS+QNdeal2jDPP4l9qHc98vTYZOSkxzD+njBWVWjFPKgipx6DkWvXQiW8OYcewVHE5yukinDMcfGgc0opDltYKDxIGBedkzc6jSfE7tlvESCDFUw0Hx0opS+U0lHCxNottbNWSxX9zZVvEhKWUSyBpaXwBc2a98M6UqPeXAs/GDon8Ax7hsthO8cM5HU7Ad0UvRR9lHmtyQKZ4MAe814X5h9MSUkQmhf96eVJ6p90OjIiqSIjvykvr2l5U55O/fPQKD+jIomYpNyGJQ25uQ2kIikRfAmuBHCPsWqkSDEqgZ5KDI2sifS/R43MbZg0idFHbCPNxXxZws1ACVE6hAhOdJwRkJLFBLPZpRGYJ50pko6XzMkgmSx40ljik6AQcKhFnLcQE6rF7PXFe1Ocoj0T3AXgSgJTDIhHRfHlYZKuSzc6uievOJGXY+i5GJkkTp7UM3y0LqATDbtFcbdBxO7o4T25JYlEjoH0uynUh8rapkxp62QN70svSF+hT4gGPlovlmcm/ComLi7mV4kTykV9NFWjE/QrwgQ4uIcAP0rQF4VZYRP2o3PhHHzfPMJj9Ir+uzKUlrH49ntT18AVvj1sc3YGjUT/Mt2Dxawa8ArcA7bCQIpvfwAYu22vEG/No/5RvPdA7g+AelLrPwzy+LtkLPhnpIxH14m4EYq8eeMHbPEPNm6G7Nv9B4jcFPZ8bJj0SEjP3MPgQdKTqqEoy2v6G32P/Y6dxOv04AxnoAeq+GILvUavtYCBXm+BaIhuodcfrN5B/V2EYMCPh+SxavjGyPwV0x4CJgUPGT0mQaODGBACIJZGsMXwAD0LGXx7l3CdAcKMIKI+f5CepWeD0BvyU/GcdBxPF8SwejC6LGZmAURFdsSWKR5HyHld2kbdIZO1Ixx+bnnzU7n5+blPNV9jnUDWhP2tC68tbN3PVIldsQPxSAcSpjOav7Q05uXn5zW2LLvDXn9B6syscPy9iDLEMmSrJz6nYuWMipukjM0AH8JkGS+XFyMRkzSCH7KD/hwm172SAyZYumHlefr5AddrtA0O0TnwaVZxcRY9Bfukn9Gf05N1r9DV9MoBsJ1f+ZrqUvtPHizJAntWybv7hmqLt6QLuK6ZS9Fqi1jO5rDoWPZXXII5Tgajg53cIXCjDCGIcYrRIY2n6+mXOa/W0bdhau3ryiEYe2FV/5oeaIYK/5w5frCyll6/cYO8DiNhw6t1MBWmznt91QX62UF1N7l0eHBZTRGpKaqpKVIPF9UcIzmReud9TSY75+K899GHbBu6wjoR7RKKZVYiYxSPf5/2wJT5e3NAhmUbVn5KLx1Ujg0+BGvpAIh0DezInTkzF37KVocxrKU3r1+XLtAe2lO3l66kfQfB/unKY+q8N375Ru8bc4pJXfEcESU95q+p8ZNZRTWH1d9FzvUdYXk5rLkcdkEisoKKVHQW/b3GEx6tPaYcoJfOr9wAbSBnv1IHpep0OExr4LPMkpJM+j7sly7UHkOzXjoAZljHCGiyegtNlwljM0v+c19ET9Pvst09a2Mtgcf5/ZSzYO5h1156+eyydfAsxGa9XAuF6vzjh6CssLq6ECysperXX0sX5h5ZdpZe3guxsGIPEtHk/aqXX1hVqP5HYVVVISkrrNqvXorIc+5Ou91Hnr/LcD2afi6eX7UBloOcs7cOpqgGaNfs1g7bNbs9z6wASaylN69d0/TFTIz6Ws8+oGV3mE2612wRTHKcVUbhjKadebloMc+dyXgMVtVK6BwMB/+mVW09igdRBWaRtNQX59d/VD//xdQ0TCiYNj1KT9sq6Wdu5WTbqk3qDXyDaLa1fv621LS01G3z61sD6lH8lAxDLicV921s6Bf92JOYvzNYCL1khbqBXEFUzC521N5NyzNaQIWhjyFyDoBIVrAjmv2UEaLlI+c6zw1jmVIPLLLZZUTj6GxGHW+mq1tgHXR2D85p4Q934+jLbtjVLcyCdS10NVzpHqxp4Q/hK7WopY/NRGx9HGsPGdFjOjcpjBnGYMVqY/4eqT5khWEHWUup2A/pTw7pdWgsWft7ETUERL96nRg0HNFPmCYba6pylECaExX89A9WLUOVB4oKLu/o1oqSYHCgLzBUlAz8hNFDRpeSU1XT+LRmDUgPaKbYdHDn9suF/tu13nHJij0N97LfS0QmqONuyONk7zvUI6Qa0pF9f2+oABL92AT6e0U//z9YqAiWtJLU1JK0gS+1aacwamiNqK067u9ZQ8f1d4qLodMzz3uL89Z68V/Hnr++hXWUuHgw8dfi972PeTyPefu3aNNucemQ74qFuIaJnVkOu4Q+yjuwmmC1FqZpl1i4uzoPxjkpPf3Xv545tl26Rr+dOvUd+omqJzch9dOeU7f10Y64nMcKK137DccIZq2WdXtdZjbEoLSzHwiMtrjYLDxpHQW8gjMX6XFYAE2zSWVD04EGYSs9MbO6sEo20BMEAB4mpvSypsKjZ4Stgzb+c3A9/MQT2+vrBy+qvyFxLUtLlSRF/Ri2wjfZ2dus2Q8lXx4608/jnqK5OOap6NY2PSjYYnECCjiEeLJll/pbmqfeIK+ps3+MxrlEhqmTPipVP7kqlF4VhpEb6r+Q7YOJg38kJ9SHBf3NBl6+9YchfbUjb5ahLSzUM3kPHmwFAsZ5rpai0S7E5xWzZ1j+fW7zsUWP2g5NXTw52ySCTrgG0+lbw60l2Y/CB185CoA8NK+tbRKxfjy6pm5hzQRRR+cMqv1Jbiw6STivtEvt3DRcy0QEh92JlUGo2PG4tSKHl00YD6xc8CK+YPYyy3io2lN8BcSjKRzrIV6ypOAobqxViJPaT9M9Hy5szY33mp7OX/Zu89L/7Ww5vqY2Y8b0pKgoiUhG5cPDPzq8qTV/WkzUOIvXVVA96kmjcBrr3HrYC/Wn+fYP6Z7T1rqy3zknbvqma/FvVk96fNXGkuaXrdHW5JGSxZT/2I/O73v+yNWafMdzc5NdxYurHs6h86e01sLKLz9EBrg+x36rxAaED7hRnAMx7Vzu+9wabh3zG8XLQjx0ablUJzmxdErxYT3kzQSd0SSafVqF5PXgpp0OyYJ1EyNHpGUZmvK575ySzd85JSqF7IBzSAbMM04+MbE58xF3/njXOGecSaermlw2y9PsSQdytLJVr8t+wg+rR8cZYoeNxVIzNdk3Bngi8U5LAlgTFoQnzJCa5EsCgYhCaGL+qPj7TdhG31p9tej3R04N//PXxNwJvyUqwaJqRPJY98TJ5TPndmflRAkAhBfe46sfKW5wizSge08Xb7Ca/GUVs55trngkKkrUS2WPzKttaaqq+idmahugkY+W6fN0I6i3gPt/x88U4wAAeJxjYGRgYADiGU9YXsXz23xl4GZnAIFH7fO+IdMc/WBxDgYmEAUASbMKwAB4nGNgZGBgZwABjj4Ghv//OfoZGBlQgT4ARicDZAAAAHicY2BgYGAfxJijD8Fmu4EqBwCSpgKpAAAAAAAADgBoAH4AzADgAQIBQgFsAZgB7gIuAooC0AL8A2IDjAOoA+AEMASwBNoFCAVaBcAGCAYuBnAGrAb2B04HigfSCCoIcAiGCJwIyAkkCVYJiAmsCfIKIApWCsQLknicY2BkYGDQZ2hmYGcAASYg5gJCBob/YD4DABqrAdAAeJxdkE1qg0AYhl8Tk9AIoVDaVSmzahcF87PMARLIMoFAl0ZHY1BHdBJIT9AT9AQ9RQ9Qeqy+yteNMzDzfM+88w0K4BY/cNAMB6N2bUaPPBLukybCLvleeAAPj8JD+hfhMV7hC3u4wxs7OO4NzQSZcI/8Ltwnfwi75E/hAR7wJTyk/xYeY49fYQ/PztM+jbTZ7LY6OWdBJdX/pqs6NYWa+zMxa13oKrA6Uoerqi/JwtpYxZXJ1coUVmeZUWVlTjq0/tHacjmdxuL90OR8O0UEDYMNdtiSEpz5XQGqzlm30kzUdAYFFOb8R7NOZk0q2lwAyz1i7oAr1xoXvrOgtYhZx8wY5KRV269JZ5yGpmzPTjQhvY9je6vEElPOuJP3mWKnP5M3V+YAAAB4nG2ReVPbMBDF/ULi2EkDBFqO3gdHLxUzDB9IkdexBllydRD49ihO3Ckz7B/a31utZnafkkGyiXnyclxhgB0MMUKKMTLkmGCKV5hhF3vYxxwHOMRrvMERjnGCU7zFO7zHB3zEJ3zGF3zFN5zhHBe4xHf8wE/8wm8w/MEVimTYKv44XR9MSCsUjVoeHE3vjQoNsSZ4mmxZmVWPjSz7jlou6/0qKOWEJdKMtCe793/hQfqxa6XWZHMXFl56RS4TvPXSaDeoy0zUUZB109KstDK8lHo5q6Qi1hcOnqkImubPS6aqRq7mlnaEWabub4iYblba3SRmgldS0+FWdhNtt04F14JUaqkl7tcpOpJtErvNt3Bd9HRT5JWxK25Ldjvp6br4hzfFiIdSmlzTg2fSUzNrLd1LE1ynxq4OVaVoKLjzJ60UPtj1RKzHzsbjly6inVnFBS2MucviPncU7Rr7lfTxRepDs1A2j3ZHRc7PuzFYSfE3ZOd4kjwBy227hA==) format("woff");font-weight:400;font-style:normal}.vjs-icon-play,.video-js .vjs-play-control .vjs-icon-placeholder,.video-js .vjs-big-play-button .vjs-icon-placeholder:before{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-play:before,.video-js .vjs-play-control .vjs-icon-placeholder:before,.video-js .vjs-big-play-button .vjs-icon-placeholder:before{content:""}.vjs-icon-play-circle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-play-circle:before{content:""}.vjs-icon-pause,.video-js .vjs-play-control.vjs-playing .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-pause:before,.video-js .vjs-play-control.vjs-playing .vjs-icon-placeholder:before{content:""}.vjs-icon-volume-mute,.video-js .vjs-mute-control.vjs-vol-0 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-volume-mute:before,.video-js .vjs-mute-control.vjs-vol-0 .vjs-icon-placeholder:before{content:""}.vjs-icon-volume-low,.video-js .vjs-mute-control.vjs-vol-1 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-volume-low:before,.video-js .vjs-mute-control.vjs-vol-1 .vjs-icon-placeholder:before{content:""}.vjs-icon-volume-mid,.video-js .vjs-mute-control.vjs-vol-2 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-volume-mid:before,.video-js .vjs-mute-control.vjs-vol-2 .vjs-icon-placeholder:before{content:""}.vjs-icon-volume-high,.video-js .vjs-mute-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-volume-high:before,.video-js .vjs-mute-control .vjs-icon-placeholder:before{content:""}.vjs-icon-fullscreen-enter,.video-js .vjs-fullscreen-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-fullscreen-enter:before,.video-js .vjs-fullscreen-control .vjs-icon-placeholder:before{content:""}.vjs-icon-fullscreen-exit,.video-js.vjs-fullscreen .vjs-fullscreen-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-fullscreen-exit:before,.video-js.vjs-fullscreen .vjs-fullscreen-control .vjs-icon-placeholder:before{content:""}.vjs-icon-spinner{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-spinner:before{content:""}.vjs-icon-subtitles,.video-js .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-GB) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-IE) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-AU) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-NZ) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js .vjs-subtitles-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-subtitles:before,.video-js .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-GB) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-IE) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-AU) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-NZ) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js .vjs-subtitles-button .vjs-icon-placeholder:before{content:""}.vjs-icon-captions,.video-js:lang(en) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js:lang(fr-CA) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js .vjs-captions-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-captions:before,.video-js:lang(en) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js:lang(fr-CA) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js .vjs-captions-button .vjs-icon-placeholder:before{content:""}.vjs-icon-hd{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-hd:before{content:""}.vjs-icon-chapters,.video-js .vjs-chapters-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-chapters:before,.video-js .vjs-chapters-button .vjs-icon-placeholder:before{content:""}.vjs-icon-downloading{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-downloading:before{content:""}.vjs-icon-file-download{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download:before{content:""}.vjs-icon-file-download-done{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download-done:before{content:""}.vjs-icon-file-download-off{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download-off:before{content:""}.vjs-icon-share{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-share:before{content:""}.vjs-icon-cog{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-cog:before{content:""}.vjs-icon-square{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-square:before{content:""}.vjs-icon-circle,.vjs-seek-to-live-control .vjs-icon-placeholder,.video-js .vjs-volume-level,.video-js .vjs-play-progress{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-circle:before,.vjs-seek-to-live-control .vjs-icon-placeholder:before,.video-js .vjs-volume-level:before,.video-js .vjs-play-progress:before{content:""}.vjs-icon-circle-outline{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-circle-outline:before{content:""}.vjs-icon-circle-inner-circle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-circle-inner-circle:before{content:""}.vjs-icon-cancel,.video-js .vjs-control.vjs-close-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-cancel:before,.video-js .vjs-control.vjs-close-button .vjs-icon-placeholder:before{content:""}.vjs-icon-repeat{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-repeat:before{content:""}.vjs-icon-replay,.video-js .vjs-play-control.vjs-ended .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-replay:before,.video-js .vjs-play-control.vjs-ended .vjs-icon-placeholder:before{content:""}.vjs-icon-replay-5,.video-js .vjs-skip-backward-5 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-replay-5:before,.video-js .vjs-skip-backward-5 .vjs-icon-placeholder:before{content:""}.vjs-icon-replay-10,.video-js .vjs-skip-backward-10 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-replay-10:before,.video-js .vjs-skip-backward-10 .vjs-icon-placeholder:before{content:""}.vjs-icon-replay-30,.video-js .vjs-skip-backward-30 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-replay-30:before,.video-js .vjs-skip-backward-30 .vjs-icon-placeholder:before{content:""}.vjs-icon-forward-5,.video-js .vjs-skip-forward-5 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-forward-5:before,.video-js .vjs-skip-forward-5 .vjs-icon-placeholder:before{content:""}.vjs-icon-forward-10,.video-js .vjs-skip-forward-10 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-forward-10:before,.video-js .vjs-skip-forward-10 .vjs-icon-placeholder:before{content:""}.vjs-icon-forward-30,.video-js .vjs-skip-forward-30 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-forward-30:before,.video-js .vjs-skip-forward-30 .vjs-icon-placeholder:before{content:""}.vjs-icon-audio,.video-js .vjs-audio-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-audio:before,.video-js .vjs-audio-button .vjs-icon-placeholder:before{content:""}.vjs-icon-next-item{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-next-item:before{content:""}.vjs-icon-previous-item{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-previous-item:before{content:""}.vjs-icon-shuffle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-shuffle:before{content:""}.vjs-icon-cast{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-cast:before{content:""}.vjs-icon-picture-in-picture-enter,.video-js .vjs-picture-in-picture-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-picture-in-picture-enter:before,.video-js .vjs-picture-in-picture-control .vjs-icon-placeholder:before{content:""}.vjs-icon-picture-in-picture-exit,.video-js.vjs-picture-in-picture .vjs-picture-in-picture-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-picture-in-picture-exit:before,.video-js.vjs-picture-in-picture .vjs-picture-in-picture-control .vjs-icon-placeholder:before{content:""}.vjs-icon-facebook{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-facebook:before{content:""}.vjs-icon-linkedin{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-linkedin:before{content:""}.vjs-icon-twitter{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-twitter:before{content:""}.vjs-icon-tumblr{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-tumblr:before{content:""}.vjs-icon-pinterest{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-pinterest:before{content:""}.vjs-icon-audio-description,.video-js .vjs-descriptions-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-audio-description:before,.video-js .vjs-descriptions-button .vjs-icon-placeholder:before{content:""}.video-js{display:inline-block;vertical-align:top;box-sizing:border-box;color:#fff;background-color:#000;position:relative;padding:0;font-size:10px;line-height:1;font-weight:400;font-style:normal;font-family:Arial,Helvetica,sans-serif;word-break:initial}.video-js:-moz-full-screen{position:absolute}.video-js:-webkit-full-screen{width:100%!important;height:100%!important}.video-js[tabindex="-1"]{outline:none}.video-js *,.video-js *:before,.video-js *:after{box-sizing:inherit}.video-js ul{font-family:inherit;font-size:inherit;line-height:inherit;list-style-position:outside;margin:0}.video-js.vjs-fluid,.video-js.vjs-16-9,.video-js.vjs-4-3,.video-js.vjs-9-16,.video-js.vjs-1-1{width:100%;max-width:100%}.video-js.vjs-fluid:not(.vjs-audio-only-mode),.video-js.vjs-16-9:not(.vjs-audio-only-mode),.video-js.vjs-4-3:not(.vjs-audio-only-mode),.video-js.vjs-9-16:not(.vjs-audio-only-mode),.video-js.vjs-1-1:not(.vjs-audio-only-mode){height:0}.video-js.vjs-16-9:not(.vjs-audio-only-mode){padding-top:56.25%}.video-js.vjs-4-3:not(.vjs-audio-only-mode){padding-top:75%}.video-js.vjs-9-16:not(.vjs-audio-only-mode){padding-top:177.7777777778%}.video-js.vjs-1-1:not(.vjs-audio-only-mode){padding-top:100%}.video-js.vjs-fill:not(.vjs-audio-only-mode){width:100%;height:100%}.video-js .vjs-tech{position:absolute;top:0;left:0;width:100%;height:100%}.video-js.vjs-audio-only-mode .vjs-tech{display:none}body.vjs-full-window,body.vjs-pip-window{padding:0;margin:0;height:100%}.vjs-full-window .video-js.vjs-fullscreen,body.vjs-pip-window .video-js{position:fixed;overflow:hidden;z-index:1000;inset:0}.video-js.vjs-fullscreen:not(.vjs-ios-native-fs),body.vjs-pip-window .video-js{width:100%!important;height:100%!important;padding-top:0!important;display:block}.video-js.vjs-fullscreen.vjs-user-inactive{cursor:none}.vjs-pip-container .vjs-pip-text{position:absolute;bottom:10%;font-size:2em;background-color:#000000b3;padding:.5em;text-align:center;width:100%}.vjs-layout-tiny.vjs-pip-container .vjs-pip-text,.vjs-layout-x-small.vjs-pip-container .vjs-pip-text,.vjs-layout-small.vjs-pip-container .vjs-pip-text{bottom:0;font-size:1.4em}.vjs-hidden{display:none!important}.vjs-disabled{opacity:.5;cursor:default}.video-js .vjs-offscreen{height:1px;left:-9999px;position:absolute;top:0;width:1px}.vjs-lock-showing{display:block!important;opacity:1!important;visibility:visible!important}.vjs-no-js{padding:20px;color:#fff;background-color:#000;font-size:18px;font-family:Arial,Helvetica,sans-serif;text-align:center;width:300px;height:150px;margin:0 auto}.vjs-no-js a,.vjs-no-js a:visited{color:#66a8cc}.video-js .vjs-big-play-button{font-size:3em;line-height:1.5em;height:1.63332em;width:3em;display:block;position:absolute;top:50%;left:50%;padding:0;margin-top:-.81666em;margin-left:-1.5em;cursor:pointer;opacity:1;border:.06666em solid #fff;background-color:#2b333f;background-color:#2b333fb3;border-radius:.3em;transition:all .4s}.vjs-big-play-button .vjs-svg-icon{width:1em;height:1em;position:absolute;top:50%;left:50%;line-height:1;transform:translate(-50%,-50%)}.video-js:hover .vjs-big-play-button,.video-js .vjs-big-play-button:focus{border-color:#fff;background-color:#73859f;background-color:#73859f80;transition:all 0s}.vjs-controls-disabled .vjs-big-play-button,.vjs-has-started .vjs-big-play-button,.vjs-using-native-controls .vjs-big-play-button,.vjs-error .vjs-big-play-button{display:none}.vjs-has-started.vjs-paused.vjs-show-big-play-button-on-pause:not(.vjs-seeking,.vjs-scrubbing,.vjs-error) .vjs-big-play-button{display:block}.video-js button{background:none;border:none;color:inherit;display:inline-block;font-size:inherit;line-height:inherit;text-transform:none;text-decoration:none;transition:none;-webkit-appearance:none;-moz-appearance:none;appearance:none}.video-js.vjs-spatial-navigation-enabled .vjs-button:focus{outline:.0625em solid white;box-shadow:none}.vjs-control .vjs-button{width:100%;height:100%}.video-js .vjs-control.vjs-close-button{cursor:pointer;height:3em;position:absolute;right:0;top:.5em;z-index:2}.video-js .vjs-modal-dialog{background:#000c;background:linear-gradient(180deg,#000c,#fff0);overflow:auto}.video-js .vjs-modal-dialog>*{box-sizing:border-box}.vjs-modal-dialog .vjs-modal-dialog-content{font-size:1.2em;line-height:1.5;padding:20px 24px;z-index:1}.vjs-menu-button{cursor:pointer}.vjs-menu-button.vjs-disabled{cursor:default}.vjs-workinghover .vjs-menu-button.vjs-disabled:hover .vjs-menu{display:none}.vjs-menu .vjs-menu-content{display:block;padding:0;margin:0;font-family:Arial,Helvetica,sans-serif;overflow:auto}.vjs-menu .vjs-menu-content>*{box-sizing:border-box}.vjs-scrubbing .vjs-control.vjs-menu-button:hover .vjs-menu{display:none}.vjs-menu li{display:flex;justify-content:center;list-style:none;margin:0;padding:.2em 0;line-height:1.4em;font-size:1.2em;text-align:center;text-transform:lowercase}.vjs-menu li.vjs-menu-item:focus,.vjs-menu li.vjs-menu-item:hover,.js-focus-visible .vjs-menu li.vjs-menu-item:hover{background-color:#73859f;background-color:#73859f80}.vjs-menu li.vjs-selected,.vjs-menu li.vjs-selected:focus,.vjs-menu li.vjs-selected:hover,.js-focus-visible .vjs-menu li.vjs-selected:hover{background-color:#fff;color:#2b333f}.vjs-menu li.vjs-selected .vjs-svg-icon,.vjs-menu li.vjs-selected:focus .vjs-svg-icon,.vjs-menu li.vjs-selected:hover .vjs-svg-icon,.js-focus-visible .vjs-menu li.vjs-selected:hover .vjs-svg-icon{fill:#000}.video-js .vjs-menu *:not(.vjs-selected):focus:not(:focus-visible),.js-focus-visible .vjs-menu *:not(.vjs-selected):focus:not(.focus-visible){background:none}.vjs-menu li.vjs-menu-title{text-align:center;text-transform:uppercase;font-size:1em;line-height:2em;padding:0;margin:0 0 .3em;font-weight:700;cursor:default}.vjs-menu-button-popup .vjs-menu{display:none;position:absolute;bottom:0;width:10em;left:-3em;height:0em;margin-bottom:1.5em;border-top-color:#2b333fb3}.vjs-pip-window .vjs-menu-button-popup .vjs-menu{left:unset;right:1em}.vjs-menu-button-popup .vjs-menu .vjs-menu-content{background-color:#2b333f;background-color:#2b333fb3;position:absolute;width:100%;bottom:1.5em;max-height:15em}.vjs-layout-tiny .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-x-small .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:5em}.vjs-layout-small .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:10em}.vjs-layout-medium .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:14em}.vjs-layout-large .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-x-large .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-huge .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:25em}.vjs-workinghover .vjs-menu-button-popup.vjs-hover .vjs-menu,.vjs-menu-button-popup .vjs-menu.vjs-lock-showing{display:block}.video-js .vjs-menu-button-inline{transition:all .4s;overflow:hidden}.video-js .vjs-menu-button-inline:before{width:2.222222222em}.video-js .vjs-menu-button-inline:hover,.video-js .vjs-menu-button-inline:focus,.video-js .vjs-menu-button-inline.vjs-slider-active{width:12em}.vjs-menu-button-inline .vjs-menu{opacity:0;height:100%;width:auto;position:absolute;left:4em;top:0;padding:0;margin:0;transition:all .4s}.vjs-menu-button-inline:hover .vjs-menu,.vjs-menu-button-inline:focus .vjs-menu,.vjs-menu-button-inline.vjs-slider-active .vjs-menu{display:block;opacity:1}.vjs-menu-button-inline .vjs-menu-content{width:auto;height:100%;margin:0;overflow:hidden}.video-js .vjs-control-bar{display:none;width:100%;position:absolute;bottom:0;left:0;right:0;height:3em;background-color:#2b333f;background-color:#2b333fb3}.video-js.vjs-spatial-navigation-enabled .vjs-control-bar{gap:1px}.video-js:not(.vjs-controls-disabled,.vjs-using-native-controls,.vjs-error) .vjs-control-bar.vjs-lock-showing{display:flex!important}.vjs-has-started .vjs-control-bar,.vjs-audio-only-mode .vjs-control-bar{display:flex;visibility:visible;opacity:1;transition:visibility .1s,opacity .1s}.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar{visibility:visible;opacity:0;pointer-events:none;transition:visibility 1s,opacity 1s}.vjs-controls-disabled .vjs-control-bar,.vjs-using-native-controls .vjs-control-bar,.vjs-error .vjs-control-bar{display:none!important}.vjs-audio.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar,.vjs-audio-only-mode.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar{opacity:1;visibility:visible;pointer-events:auto}.video-js .vjs-control{position:relative;text-align:center;margin:0;padding:0;height:100%;width:4em;flex:none}.video-js .vjs-control.vjs-visible-text{width:auto;padding-left:1em;padding-right:1em}.vjs-button>.vjs-icon-placeholder:before{font-size:1.8em;line-height:1.67}.vjs-button>.vjs-icon-placeholder{display:block}.vjs-button>.vjs-svg-icon{display:inline-block}.video-js .vjs-control:focus:before,.video-js .vjs-control:hover:before,.video-js .vjs-control:focus{text-shadow:0em 0em 1em white}.video-js *:not(.vjs-visible-text)>.vjs-control-text{border:0;clip:rect(0 0 0 0);height:1px;overflow:hidden;padding:0;position:absolute;width:1px}.video-js .vjs-custom-control-spacer{display:none}.video-js .vjs-progress-control{cursor:pointer;flex:auto;display:flex;align-items:center;min-width:4em;touch-action:none}.video-js .vjs-progress-control.disabled{cursor:default}.vjs-live .vjs-progress-control{display:none}.vjs-liveui .vjs-progress-control{display:flex;align-items:center}.video-js .vjs-progress-holder{flex:auto;transition:all .2s;height:.3em}.video-js .vjs-progress-control .vjs-progress-holder{margin:0 10px}.video-js .vjs-progress-control:hover .vjs-progress-holder,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-progress-holder{font-size:1.6666666667em}.video-js .vjs-progress-control:hover .vjs-progress-holder.disabled{font-size:1em}.video-js .vjs-progress-holder .vjs-play-progress,.video-js .vjs-progress-holder .vjs-load-progress,.video-js .vjs-progress-holder .vjs-load-progress div{position:absolute;display:block;height:100%;margin:0;padding:0;width:0}.video-js .vjs-play-progress{background-color:#fff}.video-js .vjs-play-progress:before{font-size:.9em;position:absolute;right:-.5em;line-height:.35em;z-index:1}.vjs-svg-icons-enabled .vjs-play-progress:before{content:none!important}.vjs-play-progress .vjs-svg-icon{position:absolute;top:-.35em;right:-.4em;width:.9em;height:.9em;pointer-events:none;line-height:.15em;z-index:1}.video-js .vjs-load-progress{background:#73859f80}.video-js .vjs-load-progress div{background:#73859fbf}.video-js .vjs-time-tooltip{background-color:#fff;background-color:#fffc;border-radius:.3em;color:#000;float:right;font-family:Arial,Helvetica,sans-serif;font-size:1em;padding:6px 8px 8px;pointer-events:none;position:absolute;top:-3.4em;visibility:hidden;z-index:1}.video-js .vjs-progress-holder:focus .vjs-time-tooltip{display:none}.video-js .vjs-progress-control:hover .vjs-time-tooltip,.video-js .vjs-progress-control:hover .vjs-progress-holder:focus .vjs-time-tooltip,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-time-tooltip{display:block;font-size:.6em;visibility:visible}.video-js .vjs-progress-control.disabled:hover .vjs-time-tooltip{font-size:1em}.video-js .vjs-progress-control .vjs-mouse-display{display:none;position:absolute;width:1px;height:100%;background-color:#000;z-index:1}.video-js .vjs-progress-control:hover .vjs-mouse-display,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-mouse-display{display:block}.video-js.vjs-user-inactive .vjs-progress-control .vjs-mouse-display,.video-js.vjs-touch-enabled:not(.vjs-scrubbing) .vjs-progress-control .vjs-mouse-display{visibility:hidden;opacity:0;transition:visibility 1s,opacity 1s}.vjs-mouse-display .vjs-time-tooltip{color:#fff;background-color:#000;background-color:#000c}.video-js .vjs-slider{position:relative;cursor:pointer;padding:0;margin:0 .45em;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;background-color:#73859f;background-color:#73859f80}.video-js .vjs-slider.disabled{cursor:default}.video-js .vjs-slider:focus{text-shadow:0em 0em 1em white;box-shadow:0 0 1em #fff}.video-js.vjs-spatial-navigation-enabled .vjs-slider:focus{outline:.0625em solid white}.video-js .vjs-mute-control{cursor:pointer;flex:none}.video-js .vjs-volume-control{cursor:pointer;margin-right:1em;display:flex}.video-js .vjs-volume-control.vjs-volume-horizontal{width:5em}.video-js .vjs-volume-panel .vjs-volume-control{visibility:visible;opacity:0;width:1px;height:1px;margin-left:-1px}.video-js .vjs-volume-panel{transition:width 1s}.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control,.video-js .vjs-volume-panel:active .vjs-volume-control,.video-js .vjs-volume-panel:focus .vjs-volume-control,.video-js .vjs-volume-panel .vjs-volume-control:active,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control,.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active{visibility:visible;opacity:1;position:relative;transition:visibility .1s,opacity .1s,height .1s,width .1s,left 0s,top 0s}.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel:active .vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel:focus .vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel .vjs-volume-control:active.vjs-volume-horizontal,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active.vjs-volume-horizontal{width:5em;height:3em;margin-right:0}.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel:active .vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel:focus .vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel .vjs-volume-control:active.vjs-volume-vertical,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active.vjs-volume-vertical{left:-3.5em;transition:left 0s}.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active{width:10em;transition:width .1s}.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-mute-toggle-only{width:4em}.video-js .vjs-volume-panel .vjs-volume-control.vjs-volume-vertical{height:8em;width:3em;left:-3000em;transition:visibility 1s,opacity 1s,height 1s 1s,width 1s 1s,left 1s 1s,top 1s 1s}.video-js .vjs-volume-panel .vjs-volume-control.vjs-volume-horizontal{transition:visibility 1s,opacity 1s,height 1s 1s,width 1s,left 1s 1s,top 1s 1s}.video-js .vjs-volume-panel{display:flex}.video-js .vjs-volume-bar{margin:1.35em .45em}.vjs-volume-bar.vjs-slider-horizontal{width:5em;height:.3em}.vjs-volume-bar.vjs-slider-vertical{width:.3em;height:5em;margin:1.35em auto}.video-js .vjs-volume-level{position:absolute;bottom:0;left:0;background-color:#fff}.video-js .vjs-volume-level:before{position:absolute;font-size:.9em;z-index:1}.vjs-slider-vertical .vjs-volume-level{width:.3em}.vjs-slider-vertical .vjs-volume-level:before{top:-.5em;left:-.3em;z-index:1}.vjs-svg-icons-enabled .vjs-volume-level:before{content:none}.vjs-volume-level .vjs-svg-icon{position:absolute;width:.9em;height:.9em;pointer-events:none;z-index:1}.vjs-slider-horizontal .vjs-volume-level{height:.3em}.vjs-slider-horizontal .vjs-volume-level:before{line-height:.35em;right:-.5em}.vjs-slider-horizontal .vjs-volume-level .vjs-svg-icon{right:-.3em;transform:translateY(-50%)}.vjs-slider-vertical .vjs-volume-level .vjs-svg-icon{top:-.55em;transform:translate(-50%)}.video-js .vjs-volume-panel.vjs-volume-panel-vertical{width:4em}.vjs-volume-bar.vjs-slider-vertical .vjs-volume-level{height:100%}.vjs-volume-bar.vjs-slider-horizontal .vjs-volume-level{width:100%}.video-js .vjs-volume-vertical{width:3em;height:8em;bottom:8em;background-color:#2b333f;background-color:#2b333fb3}.video-js .vjs-volume-horizontal .vjs-menu{left:-2em}.video-js .vjs-volume-tooltip{background-color:#fff;background-color:#fffc;border-radius:.3em;color:#000;float:right;font-family:Arial,Helvetica,sans-serif;font-size:1em;padding:6px 8px 8px;pointer-events:none;position:absolute;top:-3.4em;visibility:hidden;z-index:1}.video-js .vjs-volume-control:hover .vjs-volume-tooltip,.video-js .vjs-volume-control:hover .vjs-progress-holder:focus .vjs-volume-tooltip{display:block;font-size:1em;visibility:visible}.video-js .vjs-volume-vertical:hover .vjs-volume-tooltip,.video-js .vjs-volume-vertical:hover .vjs-progress-holder:focus .vjs-volume-tooltip{left:1em;top:-12px}.video-js .vjs-volume-control.disabled:hover .vjs-volume-tooltip{font-size:1em}.video-js .vjs-volume-control .vjs-mouse-display{display:none;position:absolute;width:100%;height:1px;background-color:#000;z-index:1}.video-js .vjs-volume-horizontal .vjs-mouse-display{width:1px;height:100%}.video-js .vjs-volume-control:hover .vjs-mouse-display{display:block}.video-js.vjs-user-inactive .vjs-volume-control .vjs-mouse-display{visibility:hidden;opacity:0;transition:visibility 1s,opacity 1s}.vjs-mouse-display .vjs-volume-tooltip{color:#fff;background-color:#000;background-color:#000c}.vjs-poster{display:inline-block;vertical-align:middle;cursor:pointer;margin:0;padding:0;position:absolute;inset:0;height:100%}.vjs-has-started .vjs-poster,.vjs-using-native-controls .vjs-poster{display:none}.vjs-audio.vjs-has-started .vjs-poster,.vjs-has-started.vjs-audio-poster-mode .vjs-poster,.vjs-pip-container.vjs-has-started .vjs-poster{display:block}.vjs-poster img{width:100%;height:100%;object-fit:contain}.video-js .vjs-live-control{display:flex;align-items:flex-start;flex:auto;font-size:1em;line-height:3em}.video-js:not(.vjs-live) .vjs-live-control,.video-js.vjs-liveui .vjs-live-control{display:none}.video-js .vjs-seek-to-live-control{align-items:center;cursor:pointer;flex:none;display:inline-flex;height:100%;padding-left:.5em;padding-right:.5em;font-size:1em;line-height:3em;width:auto;min-width:4em}.video-js.vjs-live:not(.vjs-liveui) .vjs-seek-to-live-control,.video-js:not(.vjs-live) .vjs-seek-to-live-control{display:none}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge{cursor:auto}.vjs-seek-to-live-control .vjs-icon-placeholder{margin-right:.5em;color:#888}.vjs-svg-icons-enabled .vjs-seek-to-live-control{line-height:0}.vjs-seek-to-live-control .vjs-svg-icon{width:1em;height:1em;pointer-events:none;fill:#888}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge .vjs-icon-placeholder{color:red}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge .vjs-svg-icon{fill:red}.video-js .vjs-time-control{flex:none;font-size:1em;line-height:3em;min-width:2em;width:auto;padding-left:1em;padding-right:1em}.vjs-live .vjs-time-control,.vjs-live .vjs-time-divider,.video-js .vjs-current-time,.video-js .vjs-duration{display:none}.vjs-time-divider{display:none;line-height:3em}.vjs-normalise-time-controls:not(.vjs-live) .vjs-time-control{display:flex}.video-js .vjs-play-control{cursor:pointer}.video-js .vjs-play-control .vjs-icon-placeholder{flex:none}.vjs-text-track-display{position:absolute;inset:0 0 3em;pointer-events:none}.vjs-error .vjs-text-track-display{display:none}.video-js.vjs-controls-disabled .vjs-text-track-display,.video-js.vjs-user-inactive.vjs-playing .vjs-text-track-display{bottom:1em}.video-js .vjs-text-track{font-size:1.4em;text-align:center;margin-bottom:.1em}.vjs-subtitles{color:#fff}.vjs-captions{color:#fc6}.vjs-tt-cue{display:block}video::-webkit-media-text-track-display{transform:translateY(-3em)}.video-js.vjs-controls-disabled video::-webkit-media-text-track-display,.video-js.vjs-user-inactive.vjs-playing video::-webkit-media-text-track-display{transform:translateY(-1.5em)}.video-js.vjs-force-center-align-cues .vjs-text-track-cue{text-align:center!important;width:80%!important}@supports not (inset: 10px){.video-js .vjs-text-track-display>div{inset:0}}.video-js .vjs-picture-in-picture-control{cursor:pointer;flex:none}.video-js.vjs-audio-only-mode .vjs-picture-in-picture-control,.vjs-pip-window .vjs-picture-in-picture-control{display:none}.video-js .vjs-fullscreen-control{cursor:pointer;flex:none}.video-js.vjs-audio-only-mode .vjs-fullscreen-control,.vjs-pip-window .vjs-fullscreen-control{display:none}.vjs-playback-rate>.vjs-menu-button,.vjs-playback-rate .vjs-playback-rate-value{position:absolute;top:0;left:0;width:100%;height:100%}.vjs-playback-rate .vjs-playback-rate-value{pointer-events:none;font-size:1.5em;line-height:2;text-align:center}.vjs-playback-rate .vjs-menu{width:4em;left:0}.vjs-error .vjs-error-display .vjs-modal-dialog-content{font-size:1.4em;text-align:center}.vjs-loading-spinner{display:none;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);opacity:.85;text-align:left;border:.6em solid rgba(43,51,63,.7);box-sizing:border-box;background-clip:padding-box;width:5em;height:5em;border-radius:50%;visibility:hidden}.vjs-seeking .vjs-loading-spinner,.vjs-waiting .vjs-loading-spinner{display:flex;justify-content:center;align-items:center;animation:vjs-spinner-show 0s linear .3s forwards}.vjs-error .vjs-loading-spinner{display:none}.vjs-loading-spinner:before,.vjs-loading-spinner:after{content:"";position:absolute;box-sizing:inherit;width:inherit;height:inherit;border-radius:inherit;opacity:1;border:inherit;border-color:transparent;border-top-color:#fff}.vjs-seeking .vjs-loading-spinner:before,.vjs-seeking .vjs-loading-spinner:after,.vjs-waiting .vjs-loading-spinner:before,.vjs-waiting .vjs-loading-spinner:after{animation:vjs-spinner-spin 1.1s cubic-bezier(.6,.2,0,.8) infinite,vjs-spinner-fade 1.1s linear infinite}.vjs-seeking .vjs-loading-spinner:before,.vjs-waiting .vjs-loading-spinner:before{border-top-color:#fff}.vjs-seeking .vjs-loading-spinner:after,.vjs-waiting .vjs-loading-spinner:after{border-top-color:#fff;animation-delay:.44s}@keyframes vjs-spinner-show{to{visibility:visible}}@keyframes vjs-spinner-spin{to{transform:rotate(360deg)}}@keyframes vjs-spinner-fade{0%{border-top-color:#73859f}20%{border-top-color:#73859f}35%{border-top-color:#fff}60%{border-top-color:#73859f}to{border-top-color:#73859f}}.video-js.vjs-audio-only-mode .vjs-captions-button{display:none}.vjs-chapters-button .vjs-menu ul{width:24em}.video-js.vjs-audio-only-mode .vjs-descriptions-button{display:none}.vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-svg-icon{width:1.5em;height:1.5em}.video-js .vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-menu-item-text .vjs-icon-placeholder{vertical-align:middle;display:inline-block;margin-bottom:-.1em}.video-js .vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before{font-family:VideoJS;content:"";font-size:1.5em;line-height:inherit}.video-js.vjs-audio-only-mode .vjs-subs-caps-button{display:none}.video-js .vjs-audio-button+.vjs-menu .vjs-descriptions-menu-item .vjs-menu-item-text .vjs-icon-placeholder,.video-js .vjs-audio-button+.vjs-menu .vjs-main-desc-menu-item .vjs-menu-item-text .vjs-icon-placeholder{vertical-align:middle;display:inline-block;margin-bottom:-.1em}.video-js .vjs-audio-button+.vjs-menu .vjs-descriptions-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before,.video-js .vjs-audio-button+.vjs-menu .vjs-main-desc-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before{font-family:VideoJS;content:" ";font-size:1.5em;line-height:inherit}.video-js.vjs-layout-small .vjs-current-time,.video-js.vjs-layout-small .vjs-time-divider,.video-js.vjs-layout-small .vjs-duration,.video-js.vjs-layout-small .vjs-remaining-time,.video-js.vjs-layout-small .vjs-playback-rate,.video-js.vjs-layout-small .vjs-volume-control,.video-js.vjs-layout-x-small .vjs-current-time,.video-js.vjs-layout-x-small .vjs-time-divider,.video-js.vjs-layout-x-small .vjs-duration,.video-js.vjs-layout-x-small .vjs-remaining-time,.video-js.vjs-layout-x-small .vjs-playback-rate,.video-js.vjs-layout-x-small .vjs-volume-control,.video-js.vjs-layout-tiny .vjs-current-time,.video-js.vjs-layout-tiny .vjs-time-divider,.video-js.vjs-layout-tiny .vjs-duration,.video-js.vjs-layout-tiny .vjs-remaining-time,.video-js.vjs-layout-tiny .vjs-playback-rate,.video-js.vjs-layout-tiny .vjs-volume-control{display:none}.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal:hover,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal:hover,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal:hover,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover{width:auto;width:initial}.video-js.vjs-layout-x-small .vjs-progress-control,.video-js.vjs-layout-tiny .vjs-progress-control{display:none}.video-js.vjs-layout-x-small .vjs-custom-control-spacer{flex:auto;display:block}.vjs-modal-dialog.vjs-text-track-settings{background-color:#2b333f;background-color:#2b333fbf;color:#fff;height:70%}.vjs-spatial-navigation-enabled .vjs-modal-dialog.vjs-text-track-settings{height:80%}.vjs-error .vjs-text-track-settings{display:none}.vjs-text-track-settings .vjs-modal-dialog-content{display:table}.vjs-text-track-settings .vjs-track-settings-colors,.vjs-text-track-settings .vjs-track-settings-font,.vjs-text-track-settings .vjs-track-settings-controls{display:table-cell}.vjs-text-track-settings .vjs-track-settings-controls{text-align:right;vertical-align:bottom}@supports (display: grid){.vjs-text-track-settings .vjs-modal-dialog-content{display:grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr;padding:20px 24px 0}.vjs-track-settings-controls .vjs-default-button{margin-bottom:20px}.vjs-text-track-settings .vjs-track-settings-controls{grid-column:1/-1}.vjs-layout-small .vjs-text-track-settings .vjs-modal-dialog-content,.vjs-layout-x-small .vjs-text-track-settings .vjs-modal-dialog-content,.vjs-layout-tiny .vjs-text-track-settings .vjs-modal-dialog-content{grid-template-columns:1fr}}.vjs-text-track-settings select{font-size:inherit}.vjs-track-setting>select{margin-right:1em;margin-bottom:.5em}.vjs-text-track-settings fieldset{margin:10px;border:none}.vjs-text-track-settings fieldset span{display:inline-block;padding:0 .6em .8em}.vjs-text-track-settings fieldset span>select{max-width:7.3em}.vjs-text-track-settings legend{color:#fff;font-weight:700;font-size:1.2em}.vjs-text-track-settings .vjs-label{margin:0 .5em .5em 0}.vjs-track-settings-controls button:focus,.vjs-track-settings-controls button:active{outline-style:solid;outline-width:medium;background-image:linear-gradient(0deg,#fff 88%,#73859f)}.vjs-track-settings-controls button:hover{color:#2b333fbf}.vjs-track-settings-controls button{background-color:#fff;background-image:linear-gradient(-180deg,#fff 88%,#73859f);color:#2b333f;cursor:pointer;border-radius:2px}.vjs-track-settings-controls .vjs-default-button{margin-right:1em}.vjs-title-bar{background:#000000e6;background:linear-gradient(180deg,#000000e6,#000000b3 60%,#0000);font-size:1.2em;line-height:1.5;transition:opacity .1s;padding:.666em 1.333em 4em;pointer-events:none;position:absolute;top:0;width:100%}.vjs-error .vjs-title-bar{display:none}.vjs-title-bar-title,.vjs-title-bar-description{margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vjs-title-bar-title{font-weight:700;margin-bottom:.333em}.vjs-playing.vjs-user-inactive .vjs-title-bar{opacity:0;transition:opacity 1s}.video-js .vjs-skip-forward-5,.video-js .vjs-skip-forward-10,.video-js .vjs-skip-forward-30,.video-js .vjs-skip-backward-5,.video-js .vjs-skip-backward-10,.video-js .vjs-skip-backward-30{cursor:pointer}.video-js .vjs-transient-button{position:absolute;height:3em;display:flex;align-items:center;justify-content:center;background-color:#32323280;cursor:pointer;opacity:1;transition:opacity 1s}.video-js:not(.vjs-has-started) .vjs-transient-button{display:none}.video-js.not-hover .vjs-transient-button:not(.force-display),.video-js.vjs-user-inactive .vjs-transient-button:not(.force-display){opacity:0}.video-js .vjs-transient-button span{padding:0 .5em}.video-js .vjs-transient-button.vjs-left{left:1em}.video-js .vjs-transient-button.vjs-right{right:1em}.video-js .vjs-transient-button.vjs-top{top:1em}.video-js .vjs-transient-button.vjs-near-top{top:4em}.video-js .vjs-transient-button.vjs-bottom{bottom:4em}.video-js .vjs-transient-button:hover{background-color:#323232e6}@media print{.video-js>*:not(.vjs-tech):not(.vjs-poster){visibility:hidden}}.vjs-resize-manager{position:absolute;top:0;left:0;width:100%;height:100%;border:none;z-index:-1000}.js-focus-visible .video-js *:focus:not(.focus-visible){outline:none}.video-js *:focus:not(:focus-visible){outline:none} diff --git a/backend/web/dist/assets/index-ie8TR6qH.css b/backend/web/dist/assets/index-ie8TR6qH.css new file mode 100644 index 0000000..23557b0 --- /dev/null +++ b/backend/web/dist/assets/index-ie8TR6qH.css @@ -0,0 +1 @@ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-200:oklch(88.5% .062 18.334);--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-red-900:oklch(39.6% .141 25.723);--color-orange-200:oklch(90.1% .076 70.697);--color-orange-400:oklch(75% .183 55.934);--color-orange-500:oklch(70.5% .213 47.604);--color-orange-900:oklch(40.8% .123 38.172);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-900:oklch(41.4% .112 45.904);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-200:oklch(92.5% .084 155.995);--color-green-500:oklch(72.3% .219 149.579);--color-green-700:oklch(52.7% .154 150.069);--color-emerald-50:oklch(97.9% .021 166.113);--color-emerald-100:oklch(95% .052 163.051);--color-emerald-200:oklch(90.5% .093 164.15);--color-emerald-300:oklch(84.5% .143 164.978);--color-emerald-400:oklch(76.5% .177 163.223);--color-emerald-500:oklch(69.6% .17 162.48);--color-emerald-600:oklch(59.6% .145 163.225);--color-emerald-700:oklch(50.8% .118 165.612);--color-emerald-800:oklch(43.2% .095 166.913);--color-emerald-900:oklch(37.8% .077 168.94);--color-sky-50:oklch(97.7% .013 236.62);--color-sky-100:oklch(95.1% .026 236.824);--color-sky-200:oklch(90.1% .058 230.902);--color-sky-300:oklch(82.8% .111 230.318);--color-sky-400:oklch(74.6% .16 232.661);--color-sky-500:oklch(68.5% .169 237.323);--color-sky-600:oklch(58.8% .158 241.966);--color-sky-700:oklch(50% .134 242.749);--color-sky-800:oklch(44.3% .11 240.79);--color-sky-900:oklch(39.1% .09 240.876);--color-blue-50:oklch(97% .014 254.604);--color-blue-100:oklch(93.2% .032 255.585);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-indigo-50:oklch(96.2% .018 272.314);--color-indigo-100:oklch(93% .034 272.788);--color-indigo-200:oklch(87% .065 274.039);--color-indigo-300:oklch(78.5% .115 274.713);--color-indigo-400:oklch(67.3% .182 276.935);--color-indigo-500:oklch(58.5% .233 277.117);--color-indigo-600:oklch(51.1% .262 276.966);--color-indigo-700:oklch(45.7% .24 277.023);--color-indigo-800:oklch(39.8% .195 277.366);--color-indigo-900:oklch(35.9% .144 278.697);--color-rose-50:oklch(96.9% .015 12.422);--color-rose-200:oklch(89.2% .058 10.001);--color-rose-300:oklch(81% .117 11.638);--color-rose-400:oklch(71.2% .194 13.428);--color-rose-500:oklch(64.5% .246 16.439);--color-rose-600:oklch(58.6% .253 17.585);--color-rose-900:oklch(41% .159 10.272);--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-800:oklch(27.8% .033 256.848);--color-gray-900:oklch(21% .034 264.665);--color-gray-950:oklch(13% .028 261.692);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-lg:32rem;--container-2xl:42rem;--container-4xl:56rem;--container-5xl:64rem;--container-6xl:72rem;--container-7xl:80rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--font-weight-medium:500;--font-weight-semibold:600;--tracking-tight:-.025em;--tracking-wide:.025em;--leading-tight:1.25;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--ease-in:cubic-bezier(.4,0,1,1);--ease-out:cubic-bezier(0,0,.2,1);--ease-in-out:cubic-bezier(.4,0,.2,1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4,0,.6,1)infinite;--blur-sm:8px;--blur-md:12px;--blur-xl:24px;--blur-2xl:40px;--blur-3xl:64px;--aspect-video:16/9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.sticky{position:sticky}.-inset-10{inset:calc(var(--spacing)*-10)}.inset-0{inset:calc(var(--spacing)*0)}.inset-x-0{inset-inline:calc(var(--spacing)*0)}.inset-x-2{inset-inline:calc(var(--spacing)*2)}.-top-1{top:calc(var(--spacing)*-1)}.-top-28{top:calc(var(--spacing)*-28)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.top-3{top:calc(var(--spacing)*3)}.top-5{top:calc(var(--spacing)*5)}.top-\[56px\]{top:56px}.top-auto{top:auto}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.right-3{right:calc(var(--spacing)*3)}.right-4{right:calc(var(--spacing)*4)}.right-\[-6rem\]{right:-6rem}.-bottom-1{bottom:calc(var(--spacing)*-1)}.-bottom-28{bottom:calc(var(--spacing)*-28)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-2{bottom:calc(var(--spacing)*2)}.bottom-3{bottom:calc(var(--spacing)*3)}.bottom-4{bottom:calc(var(--spacing)*4)}.bottom-7{bottom:calc(var(--spacing)*7)}.bottom-8{bottom:calc(var(--spacing)*8)}.bottom-auto{bottom:auto}.-left-1{left:calc(var(--spacing)*-1)}.left-0{left:calc(var(--spacing)*0)}.left-1\/2{left:50%}.left-2{left:calc(var(--spacing)*2)}.left-3{left:calc(var(--spacing)*3)}.isolate{isolation:isolate}.z-0{z-index:0}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-50{z-index:50}.z-\[80\]{z-index:80}.z-\[9999\]{z-index:9999}.col-span-1{grid-column:span 1/span 1}.col-start-1{grid-column-start:1}.row-start-1{grid-row-start:1}.mx-1{margin-inline:calc(var(--spacing)*1)}.mx-auto{margin-inline:auto}.-my-1{margin-block:calc(var(--spacing)*-1)}.mt-0\.5{margin-top:calc(var(--spacing)*.5)}.mt-1{margin-top:calc(var(--spacing)*1)}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mt-4{margin-top:calc(var(--spacing)*4)}.mt-6{margin-top:calc(var(--spacing)*6)}.mt-8{margin-top:calc(var(--spacing)*8)}.-mr-0\.5{margin-right:calc(var(--spacing)*-.5)}.mr-2{margin-right:calc(var(--spacing)*2)}.-mb-px{margin-bottom:-1px}.mb-3{margin-bottom:calc(var(--spacing)*3)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.-ml-0\.5{margin-left:calc(var(--spacing)*-.5)}.-ml-px{margin-left:-1px}.ml-1{margin-left:calc(var(--spacing)*1)}.ml-1\.5{margin-left:calc(var(--spacing)*1.5)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-3{margin-left:calc(var(--spacing)*3)}.ml-auto{margin-left:auto}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-4{-webkit-line-clamp:4;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-6{-webkit-line-clamp:6;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.flex{display:flex}.flow-root{display:flow-root}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.aspect-\[16\/9\]{aspect-ratio:16/9}.aspect-video{aspect-ratio:var(--aspect-video)}.size-1\.5{width:calc(var(--spacing)*1.5);height:calc(var(--spacing)*1.5)}.size-3{width:calc(var(--spacing)*3);height:calc(var(--spacing)*3)}.size-4{width:calc(var(--spacing)*4);height:calc(var(--spacing)*4)}.size-5{width:calc(var(--spacing)*5);height:calc(var(--spacing)*5)}.size-6{width:calc(var(--spacing)*6);height:calc(var(--spacing)*6)}.size-9{width:calc(var(--spacing)*9);height:calc(var(--spacing)*9)}.size-full{width:100%;height:100%}.h-0\.5{height:calc(var(--spacing)*.5)}.h-1\.5{height:calc(var(--spacing)*1.5)}.h-2{height:calc(var(--spacing)*2)}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-7{height:calc(var(--spacing)*7)}.h-9{height:calc(var(--spacing)*9)}.h-10{height:calc(var(--spacing)*10)}.h-12{height:calc(var(--spacing)*12)}.h-16{height:calc(var(--spacing)*16)}.h-20{height:calc(var(--spacing)*20)}.h-24{height:calc(var(--spacing)*24)}.h-28{height:calc(var(--spacing)*28)}.h-52{height:calc(var(--spacing)*52)}.h-80{height:calc(var(--spacing)*80)}.h-\[60px\]{height:60px}.h-\[64px\]{height:64px}.h-full{height:100%}.max-h-48{max-height:calc(var(--spacing)*48)}.max-h-\[80vh\]{max-height:80vh}.max-h-\[calc\(100vh-3rem\)\]{max-height:calc(100vh - 3rem)}.min-h-0{min-height:calc(var(--spacing)*0)}.min-h-full{min-height:100%}.min-h-screen{min-height:100vh}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-6{width:calc(var(--spacing)*6)}.w-8{width:calc(var(--spacing)*8)}.w-9{width:calc(var(--spacing)*9)}.w-10{width:calc(var(--spacing)*10)}.w-11{width:calc(var(--spacing)*11)}.w-12{width:calc(var(--spacing)*12)}.w-14{width:calc(var(--spacing)*14)}.w-16{width:calc(var(--spacing)*16)}.w-20{width:calc(var(--spacing)*20)}.w-28{width:calc(var(--spacing)*28)}.w-52{width:calc(var(--spacing)*52)}.w-56{width:calc(var(--spacing)*56)}.w-72{width:calc(var(--spacing)*72)}.w-\[46rem\]{width:46rem}.w-\[52rem\]{width:52rem}.w-\[90px\]{width:90px}.w-\[96px\]{width:96px}.w-\[110px\]{width:110px}.w-\[112px\]{width:112px}.w-\[140px\]{width:140px}.w-\[150px\]{width:150px}.w-\[170px\]{width:170px}.w-\[260px\]{width:260px}.w-\[320px\]{width:320px}.w-\[420px\]{width:420px}.w-auto{width:auto}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-5xl{max-width:var(--container-5xl)}.max-w-6xl{max-width:var(--container-6xl)}.max-w-7xl{max-width:var(--container-7xl)}.max-w-\[11rem\]{max-width:11rem}.max-w-\[170px\]{max-width:170px}.max-w-\[220px\]{max-width:220px}.max-w-\[240px\]{max-width:240px}.max-w-\[260px\]{max-width:260px}.max-w-\[520px\]{max-width:520px}.max-w-\[calc\(100vw-1\.5rem\)\]{max-width:calc(100vw - 1.5rem)}.max-w-\[calc\(100vw-2rem\)\]{max-width:calc(100vw - 2rem)}.max-w-\[calc\(100vw-16px\)\]{max-width:calc(100vw - 16px)}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.max-w-sm{max-width:var(--container-sm)}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-\[220px\]{min-width:220px}.min-w-\[240px\]{min-width:240px}.min-w-\[300px\]{min-width:300px}.min-w-full{min-width:100%}.flex-1{flex:1}.flex-none{flex:none}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.-translate-x-1\/2{--tw-translate-x: -50% ;translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-x-5{--tw-translate-x:calc(var(--spacing)*5);translate:var(--tw-translate-x)var(--tw-translate-y)}.-translate-y-2{--tw-translate-y:calc(var(--spacing)*-2);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-0{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-2{--tw-translate-y:calc(var(--spacing)*2);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-4{--tw-translate-y:calc(var(--spacing)*4);translate:var(--tw-translate-x)var(--tw-translate-y)}.scale-75{--tw-scale-x:75%;--tw-scale-y:75%;--tw-scale-z:75%;scale:var(--tw-scale-x)var(--tw-scale-y)}.scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x)var(--tw-scale-y)}.scale-110{--tw-scale-x:110%;--tw-scale-y:110%;--tw-scale-z:110%;scale:var(--tw-scale-x)var(--tw-scale-y)}.scale-\[0\.98\]{scale:.98}.scale-\[1\.03\]{scale:1.03}.-rotate-12{rotate:-12deg}.rotate-0{rotate:none}.rotate-12{rotate:12deg}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-ew-resize{cursor:ew-resize}.cursor-move{cursor:move}.cursor-nesw-resize{cursor:nesw-resize}.cursor-not-allowed{cursor:not-allowed}.cursor-ns-resize{cursor:ns-resize}.cursor-nwse-resize{cursor:nwse-resize}.cursor-pointer{cursor:pointer}.cursor-zoom-in{cursor:zoom-in}.resize{resize:both}.appearance-none{appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-nowrap{flex-wrap:nowrap}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-1{gap:calc(var(--spacing)*1)}.gap-1\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.gap-5{gap:calc(var(--spacing)*5)}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*4)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*6)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*6)*calc(1 - var(--tw-space-y-reverse)))}.gap-x-1\.5{column-gap:calc(var(--spacing)*1.5)}.gap-x-3{column-gap:calc(var(--spacing)*3)}.gap-x-4{column-gap:calc(var(--spacing)*4)}.gap-x-8{column-gap:calc(var(--spacing)*8)}:where(.-space-x-px>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(-1px*var(--tw-space-x-reverse));margin-inline-end:calc(-1px*calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-4>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*4)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-8>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*8)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*8)*calc(1 - var(--tw-space-x-reverse)))}.gap-y-1{row-gap:calc(var(--spacing)*1)}.gap-y-2{row-gap:calc(var(--spacing)*2)}:where(.divide-x>:not(:last-child)){--tw-divide-x-reverse:0;border-inline-style:var(--tw-border-style);border-inline-start-width:calc(1px*var(--tw-divide-x-reverse));border-inline-end-width:calc(1px*calc(1 - var(--tw-divide-x-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-gray-200>:not(:last-child)){border-color:var(--color-gray-200)}.self-center{align-self:center}.justify-self-end{justify-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-none{border-radius:0}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-t-lg{border-top-left-radius:var(--radius-lg);border-top-right-radius:var(--radius-lg)}.rounded-l-lg{border-top-left-radius:var(--radius-lg);border-bottom-left-radius:var(--radius-lg)}.rounded-l-md{border-top-left-radius:var(--radius-md);border-bottom-left-radius:var(--radius-md)}.rounded-r-lg{border-top-right-radius:var(--radius-lg);border-bottom-right-radius:var(--radius-lg)}.rounded-r-md{border-top-right-radius:var(--radius-md);border-bottom-right-radius:var(--radius-md)}.rounded-b-lg{border-bottom-right-radius:var(--radius-lg);border-bottom-left-radius:var(--radius-lg)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-amber-200{border-color:var(--color-amber-200)}.border-amber-200\/60{border-color:#fee68599}@supports (color:color-mix(in lab,red,red)){.border-amber-200\/60{border-color:color-mix(in oklab,var(--color-amber-200)60%,transparent)}}.border-amber-200\/70{border-color:#fee685b3}@supports (color:color-mix(in lab,red,red)){.border-amber-200\/70{border-color:color-mix(in oklab,var(--color-amber-200)70%,transparent)}}.border-emerald-200\/70{border-color:#a4f4cfb3}@supports (color:color-mix(in lab,red,red)){.border-emerald-200\/70{border-color:color-mix(in oklab,var(--color-emerald-200)70%,transparent)}}.border-gray-200{border-color:var(--color-gray-200)}.border-gray-200\/60{border-color:#e5e7eb99}@supports (color:color-mix(in lab,red,red)){.border-gray-200\/60{border-color:color-mix(in oklab,var(--color-gray-200)60%,transparent)}}.border-gray-200\/70{border-color:#e5e7ebb3}@supports (color:color-mix(in lab,red,red)){.border-gray-200\/70{border-color:color-mix(in oklab,var(--color-gray-200)70%,transparent)}}.border-gray-300{border-color:var(--color-gray-300)}.border-green-200{border-color:var(--color-green-200)}.border-indigo-500{border-color:var(--color-indigo-500)}.border-red-200{border-color:var(--color-red-200)}.border-rose-200\/60{border-color:#ffccd399}@supports (color:color-mix(in lab,red,red)){.border-rose-200\/60{border-color:color-mix(in oklab,var(--color-rose-200)60%,transparent)}}.border-rose-200\/70{border-color:#ffccd3b3}@supports (color:color-mix(in lab,red,red)){.border-rose-200\/70{border-color:color-mix(in oklab,var(--color-rose-200)70%,transparent)}}.border-sky-200\/70{border-color:#b8e6feb3}@supports (color:color-mix(in lab,red,red)){.border-sky-200\/70{border-color:color-mix(in oklab,var(--color-sky-200)70%,transparent)}}.border-transparent{border-color:#0000}.border-white\/30{border-color:#ffffff4d}@supports (color:color-mix(in lab,red,red)){.border-white\/30{border-color:color-mix(in oklab,var(--color-white)30%,transparent)}}.border-white\/40{border-color:#fff6}@supports (color:color-mix(in lab,red,red)){.border-white\/40{border-color:color-mix(in oklab,var(--color-white)40%,transparent)}}.\!bg-amber-500{background-color:var(--color-amber-500)!important}.\!bg-blue-600{background-color:var(--color-blue-600)!important}.\!bg-emerald-600{background-color:var(--color-emerald-600)!important}.\!bg-indigo-600{background-color:var(--color-indigo-600)!important}.\!bg-red-600{background-color:var(--color-red-600)!important}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-50\/70{background-color:#fffbebb3}@supports (color:color-mix(in lab,red,red)){.bg-amber-50\/70{background-color:color-mix(in oklab,var(--color-amber-50)70%,transparent)}}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500)10%,transparent)}}.bg-amber-500\/15{background-color:#f99c0026}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/15{background-color:color-mix(in oklab,var(--color-amber-500)15%,transparent)}}.bg-amber-500\/25{background-color:#f99c0040}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/25{background-color:color-mix(in oklab,var(--color-amber-500)25%,transparent)}}.bg-amber-500\/35{background-color:#f99c0059}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/35{background-color:color-mix(in oklab,var(--color-amber-500)35%,transparent)}}.bg-amber-600\/70{background-color:#dd7400b3}@supports (color:color-mix(in lab,red,red)){.bg-amber-600\/70{background-color:color-mix(in oklab,var(--color-amber-600)70%,transparent)}}.bg-black{background-color:var(--color-black)}.bg-black\/5{background-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.bg-black\/5{background-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.bg-black\/10{background-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.bg-black\/10{background-color:color-mix(in oklab,var(--color-black)10%,transparent)}}.bg-black\/20{background-color:#0003}@supports (color:color-mix(in lab,red,red)){.bg-black\/20{background-color:color-mix(in oklab,var(--color-black)20%,transparent)}}.bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab,red,red)){.bg-black\/40{background-color:color-mix(in oklab,var(--color-black)40%,transparent)}}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black)50%,transparent)}}.bg-blue-50{background-color:var(--color-blue-50)}.bg-emerald-50{background-color:var(--color-emerald-50)}.bg-emerald-50\/60{background-color:#ecfdf599}@supports (color:color-mix(in lab,red,red)){.bg-emerald-50\/60{background-color:color-mix(in oklab,var(--color-emerald-50)60%,transparent)}}.bg-emerald-500{background-color:var(--color-emerald-500)}.bg-emerald-500\/10{background-color:#00bb7f1a}@supports (color:color-mix(in lab,red,red)){.bg-emerald-500\/10{background-color:color-mix(in oklab,var(--color-emerald-500)10%,transparent)}}.bg-emerald-500\/15{background-color:#00bb7f26}@supports (color:color-mix(in lab,red,red)){.bg-emerald-500\/15{background-color:color-mix(in oklab,var(--color-emerald-500)15%,transparent)}}.bg-emerald-500\/20{background-color:#00bb7f33}@supports (color:color-mix(in lab,red,red)){.bg-emerald-500\/20{background-color:color-mix(in oklab,var(--color-emerald-500)20%,transparent)}}.bg-emerald-500\/35{background-color:#00bb7f59}@supports (color:color-mix(in lab,red,red)){.bg-emerald-500\/35{background-color:color-mix(in oklab,var(--color-emerald-500)35%,transparent)}}.bg-emerald-600\/70{background-color:#009767b3}@supports (color:color-mix(in lab,red,red)){.bg-emerald-600\/70{background-color:color-mix(in oklab,var(--color-emerald-600)70%,transparent)}}.bg-gray-50{background-color:var(--color-gray-50)}.bg-gray-50\/90{background-color:#f9fafbe6}@supports (color:color-mix(in lab,red,red)){.bg-gray-50\/90{background-color:color-mix(in oklab,var(--color-gray-50)90%,transparent)}}.bg-gray-100{background-color:var(--color-gray-100)}.bg-gray-100\/80{background-color:#f3f4f6cc}@supports (color:color-mix(in lab,red,red)){.bg-gray-100\/80{background-color:color-mix(in oklab,var(--color-gray-100)80%,transparent)}}.bg-gray-200{background-color:var(--color-gray-200)}.bg-gray-200\/70{background-color:#e5e7ebb3}@supports (color:color-mix(in lab,red,red)){.bg-gray-200\/70{background-color:color-mix(in oklab,var(--color-gray-200)70%,transparent)}}.bg-gray-500\/10{background-color:#6a72821a}@supports (color:color-mix(in lab,red,red)){.bg-gray-500\/10{background-color:color-mix(in oklab,var(--color-gray-500)10%,transparent)}}.bg-gray-500\/75{background-color:#6a7282bf}@supports (color:color-mix(in lab,red,red)){.bg-gray-500\/75{background-color:color-mix(in oklab,var(--color-gray-500)75%,transparent)}}.bg-gray-900\/5{background-color:#1018280d}@supports (color:color-mix(in lab,red,red)){.bg-gray-900\/5{background-color:color-mix(in oklab,var(--color-gray-900)5%,transparent)}}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-indigo-50{background-color:var(--color-indigo-50)}.bg-indigo-100{background-color:var(--color-indigo-100)}.bg-indigo-500{background-color:var(--color-indigo-500)}.bg-indigo-500\/10{background-color:#625fff1a}@supports (color:color-mix(in lab,red,red)){.bg-indigo-500\/10{background-color:color-mix(in oklab,var(--color-indigo-500)10%,transparent)}}.bg-indigo-600{background-color:var(--color-indigo-600)}.bg-indigo-600\/70{background-color:#4f39f6b3}@supports (color:color-mix(in lab,red,red)){.bg-indigo-600\/70{background-color:color-mix(in oklab,var(--color-indigo-600)70%,transparent)}}.bg-orange-500\/10{background-color:#fe6e001a}@supports (color:color-mix(in lab,red,red)){.bg-orange-500\/10{background-color:color-mix(in oklab,var(--color-orange-500)10%,transparent)}}.bg-red-50{background-color:var(--color-red-50)}.bg-red-50\/60{background-color:#fef2f299}@supports (color:color-mix(in lab,red,red)){.bg-red-50\/60{background-color:color-mix(in oklab,var(--color-red-50)60%,transparent)}}.bg-red-500{background-color:var(--color-red-500)}.bg-red-500\/15{background-color:#fb2c3626}@supports (color:color-mix(in lab,red,red)){.bg-red-500\/15{background-color:color-mix(in oklab,var(--color-red-500)15%,transparent)}}.bg-red-500\/20{background-color:#fb2c3633}@supports (color:color-mix(in lab,red,red)){.bg-red-500\/20{background-color:color-mix(in oklab,var(--color-red-500)20%,transparent)}}.bg-red-500\/35{background-color:#fb2c3659}@supports (color:color-mix(in lab,red,red)){.bg-red-500\/35{background-color:color-mix(in oklab,var(--color-red-500)35%,transparent)}}.bg-red-600\/70{background-color:#e40014b3}@supports (color:color-mix(in lab,red,red)){.bg-red-600\/70{background-color:color-mix(in oklab,var(--color-red-600)70%,transparent)}}.bg-red-600\/90{background-color:#e40014e6}@supports (color:color-mix(in lab,red,red)){.bg-red-600\/90{background-color:color-mix(in oklab,var(--color-red-600)90%,transparent)}}.bg-rose-50\/70{background-color:#fff1f2b3}@supports (color:color-mix(in lab,red,red)){.bg-rose-50\/70{background-color:color-mix(in oklab,var(--color-rose-50)70%,transparent)}}.bg-rose-500\/25{background-color:#ff235740}@supports (color:color-mix(in lab,red,red)){.bg-rose-500\/25{background-color:color-mix(in oklab,var(--color-rose-500)25%,transparent)}}.bg-sky-50{background-color:var(--color-sky-50)}.bg-sky-100{background-color:var(--color-sky-100)}.bg-sky-500\/10{background-color:#00a5ef1a}@supports (color:color-mix(in lab,red,red)){.bg-sky-500\/10{background-color:color-mix(in oklab,var(--color-sky-500)10%,transparent)}}.bg-sky-500\/25{background-color:#00a5ef40}@supports (color:color-mix(in lab,red,red)){.bg-sky-500\/25{background-color:color-mix(in oklab,var(--color-sky-500)25%,transparent)}}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.bg-white\/35{background-color:#ffffff59}@supports (color:color-mix(in lab,red,red)){.bg-white\/35{background-color:color-mix(in oklab,var(--color-white)35%,transparent)}}.bg-white\/40{background-color:#fff6}@supports (color:color-mix(in lab,red,red)){.bg-white\/40{background-color:color-mix(in oklab,var(--color-white)40%,transparent)}}.bg-white\/60{background-color:#fff9}@supports (color:color-mix(in lab,red,red)){.bg-white\/60{background-color:color-mix(in oklab,var(--color-white)60%,transparent)}}.bg-white\/70{background-color:#ffffffb3}@supports (color:color-mix(in lab,red,red)){.bg-white\/70{background-color:color-mix(in oklab,var(--color-white)70%,transparent)}}.bg-white\/75{background-color:#ffffffbf}@supports (color:color-mix(in lab,red,red)){.bg-white\/75{background-color:color-mix(in oklab,var(--color-white)75%,transparent)}}.bg-white\/80{background-color:#fffc}@supports (color:color-mix(in lab,red,red)){.bg-white\/80{background-color:color-mix(in oklab,var(--color-white)80%,transparent)}}.bg-white\/90{background-color:#ffffffe6}@supports (color:color-mix(in lab,red,red)){.bg-white\/90{background-color:color-mix(in oklab,var(--color-white)90%,transparent)}}.bg-white\/95{background-color:#fffffff2}@supports (color:color-mix(in lab,red,red)){.bg-white\/95{background-color:color-mix(in oklab,var(--color-white)95%,transparent)}}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-t{--tw-gradient-position:to top in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-black\/40{--tw-gradient-from:#0006}@supports (color:color-mix(in lab,red,red)){.from-black\/40{--tw-gradient-from:color-mix(in oklab,var(--color-black)40%,transparent)}}.from-black\/40{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-black\/65{--tw-gradient-from:#000000a6}@supports (color:color-mix(in lab,red,red)){.from-black\/65{--tw-gradient-from:color-mix(in oklab,var(--color-black)65%,transparent)}}.from-black\/65{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-black\/70{--tw-gradient-from:#000000b3}@supports (color:color-mix(in lab,red,red)){.from-black\/70{--tw-gradient-from:color-mix(in oklab,var(--color-black)70%,transparent)}}.from-black\/70{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-indigo-500\/10{--tw-gradient-from:#625fff1a}@supports (color:color-mix(in lab,red,red)){.from-indigo-500\/10{--tw-gradient-from:color-mix(in oklab,var(--color-indigo-500)10%,transparent)}}.from-indigo-500\/10{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-white\/70{--tw-gradient-from:#ffffffb3}@supports (color:color-mix(in lab,red,red)){.from-white\/70{--tw-gradient-from:color-mix(in oklab,var(--color-white)70%,transparent)}}.from-white\/70{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.via-black\/0{--tw-gradient-via:#0000}@supports (color:color-mix(in lab,red,red)){.via-black\/0{--tw-gradient-via:color-mix(in oklab,var(--color-black)0%,transparent)}}.via-black\/0{--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-transparent{--tw-gradient-via:transparent;--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-white\/20{--tw-gradient-via:#fff3}@supports (color:color-mix(in lab,red,red)){.via-white\/20{--tw-gradient-via:color-mix(in oklab,var(--color-white)20%,transparent)}}.via-white\/20{--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-black\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-black\/0{--tw-gradient-to:color-mix(in oklab,var(--color-black)0%,transparent)}}.to-black\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-sky-500\/10{--tw-gradient-to:#00a5ef1a}@supports (color:color-mix(in lab,red,red)){.to-sky-500\/10{--tw-gradient-to:color-mix(in oklab,var(--color-sky-500)10%,transparent)}}.to-sky-500\/10{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-transparent{--tw-gradient-to:transparent;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-white\/60{--tw-gradient-to:#fff9}@supports (color:color-mix(in lab,red,red)){.to-white\/60{--tw-gradient-to:color-mix(in oklab,var(--color-white)60%,transparent)}}.to-white\/60{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.fill-gray-500{fill:var(--color-gray-500)}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.object-center{object-position:center}.p-0{padding:calc(var(--spacing)*0)}.p-0\.5{padding:calc(var(--spacing)*.5)}.p-1{padding:calc(var(--spacing)*1)}.p-1\.5{padding:calc(var(--spacing)*1.5)}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.p-6{padding:calc(var(--spacing)*6)}.px-1{padding-inline:calc(var(--spacing)*1)}.px-1\.5{padding-inline:calc(var(--spacing)*1.5)}.px-2{padding-inline:calc(var(--spacing)*2)}.px-2\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-3\.5{padding-inline:calc(var(--spacing)*3.5)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-6{padding-inline:calc(var(--spacing)*6)}.py-0\.5{padding-block:calc(var(--spacing)*.5)}.py-1{padding-block:calc(var(--spacing)*1)}.py-1\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-2\.5{padding-block:calc(var(--spacing)*2.5)}.py-3{padding-block:calc(var(--spacing)*3)}.py-3\.5{padding-block:calc(var(--spacing)*3.5)}.py-4{padding-block:calc(var(--spacing)*4)}.py-5{padding-block:calc(var(--spacing)*5)}.py-6{padding-block:calc(var(--spacing)*6)}.pt-1{padding-top:calc(var(--spacing)*1)}.pt-2{padding-top:calc(var(--spacing)*2)}.pt-3{padding-top:calc(var(--spacing)*3)}.pt-4{padding-top:calc(var(--spacing)*4)}.pt-6{padding-top:calc(var(--spacing)*6)}.pr-2{padding-right:calc(var(--spacing)*2)}.pr-8{padding-right:calc(var(--spacing)*8)}.pb-6{padding-bottom:calc(var(--spacing)*6)}.pb-\[env\(safe-area-inset-bottom\)\]{padding-bottom:env(safe-area-inset-bottom)}.pl-3{padding-left:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-sm\/6{font-size:var(--text-sm);line-height:calc(var(--spacing)*6)}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.break-words{overflow-wrap:break-word}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.\!text-white{color:var(--color-white)!important}.text-amber-200{color:var(--color-amber-200)}.text-amber-500{color:var(--color-amber-500)}.text-amber-600{color:var(--color-amber-600)}.text-amber-700{color:var(--color-amber-700)}.text-amber-800{color:var(--color-amber-800)}.text-amber-900{color:var(--color-amber-900)}.text-blue-600{color:var(--color-blue-600)}.text-emerald-500{color:var(--color-emerald-500)}.text-emerald-600{color:var(--color-emerald-600)}.text-emerald-700{color:var(--color-emerald-700)}.text-emerald-800{color:var(--color-emerald-800)}.text-emerald-900{color:var(--color-emerald-900)}.text-gray-400{color:var(--color-gray-400)}.text-gray-500{color:var(--color-gray-500)}.text-gray-600{color:var(--color-gray-600)}.text-gray-700{color:var(--color-gray-700)}.text-gray-800{color:var(--color-gray-800)}.text-gray-800\/90{color:#1e2939e6}@supports (color:color-mix(in lab,red,red)){.text-gray-800\/90{color:color-mix(in oklab,var(--color-gray-800)90%,transparent)}}.text-gray-900{color:var(--color-gray-900)}.text-green-700{color:var(--color-green-700)}.text-indigo-500{color:var(--color-indigo-500)}.text-indigo-600{color:var(--color-indigo-600)}.text-indigo-700{color:var(--color-indigo-700)}.text-indigo-800{color:var(--color-indigo-800)}.text-indigo-900{color:var(--color-indigo-900)}.text-orange-900{color:var(--color-orange-900)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-red-800{color:var(--color-red-800)}.text-red-900{color:var(--color-red-900)}.text-rose-200{color:var(--color-rose-200)}.text-rose-500{color:var(--color-rose-500)}.text-rose-600{color:var(--color-rose-600)}.text-rose-900{color:var(--color-rose-900)}.text-sky-200{color:var(--color-sky-200)}.text-sky-500{color:var(--color-sky-500)}.text-sky-600{color:var(--color-sky-600)}.text-sky-700{color:var(--color-sky-700)}.text-sky-800{color:var(--color-sky-800)}.text-sky-900{color:var(--color-sky-900)}.text-white{color:var(--color-white)}.text-white\/70{color:#ffffffb3}@supports (color:color-mix(in lab,red,red)){.text-white\/70{color:color-mix(in oklab,var(--color-white)70%,transparent)}}.text-white\/80{color:#fffc}@supports (color:color-mix(in lab,red,red)){.text-white\/80{color:color-mix(in oklab,var(--color-white)80%,transparent)}}.text-white\/85{color:#ffffffd9}@supports (color:color-mix(in lab,red,red)){.text-white\/85{color:color-mix(in oklab,var(--color-white)85%,transparent)}}.uppercase{text-transform:uppercase}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-80{opacity:.8}.opacity-90{opacity:.9}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a),0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow:0 1px 2px 0 var(--tw-shadow-color,#0000000d);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-1{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(1px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.inset-ring,.inset-ring-1{--tw-inset-ring-shadow:inset 0 0 0 1px var(--tw-inset-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-amber-200{--tw-ring-color:var(--color-amber-200)}.ring-amber-200\/30{--tw-ring-color:#fee6854d}@supports (color:color-mix(in lab,red,red)){.ring-amber-200\/30{--tw-ring-color:color-mix(in oklab,var(--color-amber-200)30%,transparent)}}.ring-amber-500\/30{--tw-ring-color:#f99c004d}@supports (color:color-mix(in lab,red,red)){.ring-amber-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-amber-500)30%,transparent)}}.ring-black\/5{--tw-ring-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.ring-black\/5{--tw-ring-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.ring-black\/10{--tw-ring-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.ring-black\/10{--tw-ring-color:color-mix(in oklab,var(--color-black)10%,transparent)}}.ring-emerald-200{--tw-ring-color:var(--color-emerald-200)}.ring-emerald-300{--tw-ring-color:var(--color-emerald-300)}.ring-emerald-500\/25{--tw-ring-color:#00bb7f40}@supports (color:color-mix(in lab,red,red)){.ring-emerald-500\/25{--tw-ring-color:color-mix(in oklab,var(--color-emerald-500)25%,transparent)}}.ring-emerald-500\/30{--tw-ring-color:#00bb7f4d}@supports (color:color-mix(in lab,red,red)){.ring-emerald-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-emerald-500)30%,transparent)}}.ring-gray-200{--tw-ring-color:var(--color-gray-200)}.ring-gray-200\/60{--tw-ring-color:#e5e7eb99}@supports (color:color-mix(in lab,red,red)){.ring-gray-200\/60{--tw-ring-color:color-mix(in oklab,var(--color-gray-200)60%,transparent)}}.ring-gray-900\/5{--tw-ring-color:#1018280d}@supports (color:color-mix(in lab,red,red)){.ring-gray-900\/5{--tw-ring-color:color-mix(in oklab,var(--color-gray-900)5%,transparent)}}.ring-gray-900\/10{--tw-ring-color:#1018281a}@supports (color:color-mix(in lab,red,red)){.ring-gray-900\/10{--tw-ring-color:color-mix(in oklab,var(--color-gray-900)10%,transparent)}}.ring-indigo-200{--tw-ring-color:var(--color-indigo-200)}.ring-orange-200{--tw-ring-color:var(--color-orange-200)}.ring-red-200{--tw-ring-color:var(--color-red-200)}.ring-red-300{--tw-ring-color:var(--color-red-300)}.ring-red-500\/30{--tw-ring-color:#fb2c364d}@supports (color:color-mix(in lab,red,red)){.ring-red-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-red-500)30%,transparent)}}.ring-rose-200\/30{--tw-ring-color:#ffccd34d}@supports (color:color-mix(in lab,red,red)){.ring-rose-200\/30{--tw-ring-color:color-mix(in oklab,var(--color-rose-200)30%,transparent)}}.ring-sky-200{--tw-ring-color:var(--color-sky-200)}.ring-sky-200\/30{--tw-ring-color:#b8e6fe4d}@supports (color:color-mix(in lab,red,red)){.ring-sky-200\/30{--tw-ring-color:color-mix(in oklab,var(--color-sky-200)30%,transparent)}}.ring-white\/15{--tw-ring-color:#ffffff26}@supports (color:color-mix(in lab,red,red)){.ring-white\/15{--tw-ring-color:color-mix(in oklab,var(--color-white)15%,transparent)}}.inset-ring-gray-300{--tw-inset-ring-color:var(--color-gray-300)}.inset-ring-gray-900\/5{--tw-inset-ring-color:#1018280d}@supports (color:color-mix(in lab,red,red)){.inset-ring-gray-900\/5{--tw-inset-ring-color:color-mix(in oklab,var(--color-gray-900)5%,transparent)}}.inset-ring-indigo-300{--tw-inset-ring-color:var(--color-indigo-300)}.outline-1{outline-style:var(--tw-outline-style);outline-width:1px}.-outline-offset-1{outline-offset:-1px}.outline-offset-2{outline-offset:2px}.outline-black\/5{outline-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.outline-black\/5{outline-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.outline-gray-300{outline-color:var(--color-gray-300)}.outline-indigo-600{outline-color:var(--color-indigo-600)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.blur-2xl{--tw-blur:blur(var(--blur-2xl));filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.blur-3xl{--tw-blur:blur(var(--blur-3xl));filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.blur-md{--tw-blur:blur(var(--blur-md));filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.brightness-90{--tw-brightness:brightness(90%);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.drop-shadow{--tw-drop-shadow-size:drop-shadow(0 1px 2px var(--tw-drop-shadow-color,#0000001a))drop-shadow(0 1px 1px var(--tw-drop-shadow-color,#0000000f));--tw-drop-shadow:drop-shadow(0 1px 2px #0000001a)drop-shadow(0 1px 1px #0000000f);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xl{--tw-backdrop-blur:blur(var(--blur-xl));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[left\,top\,width\,height\]{transition-property:left,top,width,height;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[opacity\,transform\]{transition-property:opacity,transform;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[top\]{transition-property:top;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[width\]{transition-property:width;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-100{--tw-duration:.1s;transition-duration:.1s}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-\[cubic-bezier\(\.2\,\.9\,\.2\,1\)\]{--tw-ease:cubic-bezier(.2,.9,.2,1);transition-timing-function:cubic-bezier(.2,.9,.2,1)}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.select-none{-webkit-user-select:none;user-select:none}.ring-inset{--tw-ring-inset:inset}.group-focus-within\:opacity-0:is(:where(.group):focus-within *){opacity:0}@media(hover:hover){.group-hover\:pointer-events-auto:is(:where(.group):hover *){pointer-events:auto}.group-hover\:visible:is(:where(.group):hover *){visibility:visible}.group-hover\:text-gray-500:is(:where(.group):hover *){color:var(--color-gray-500)}.group-hover\:text-indigo-500:is(:where(.group):hover *){color:var(--color-indigo-500)}.group-hover\:opacity-0:is(:where(.group):hover *){opacity:0}.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.group-focus-visible\:visible:is(:where(.group):focus-visible *){visibility:visible}.file\:mr-4::file-selector-button{margin-right:calc(var(--spacing)*4)}.file\:rounded-md::file-selector-button{border-radius:var(--radius-md)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-gray-100::file-selector-button{background-color:var(--color-gray-100)}.file\:px-3::file-selector-button{padding-inline:calc(var(--spacing)*3)}.file\:py-2::file-selector-button{padding-block:calc(var(--spacing)*2)}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-semibold::file-selector-button{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.file\:text-gray-900::file-selector-button{color:var(--color-gray-900)}.even\:bg-gray-50:nth-child(2n){background-color:var(--color-gray-50)}@media(hover:hover){.hover\:-translate-y-0\.5:hover{--tw-translate-y:calc(var(--spacing)*-.5);translate:var(--tw-translate-x)var(--tw-translate-y)}.hover\:border-gray-300:hover{border-color:var(--color-gray-300)}.hover\:border-indigo-200:hover{border-color:var(--color-indigo-200)}.hover\:border-transparent:hover{border-color:#0000}.hover\:\!bg-amber-600:hover{background-color:var(--color-amber-600)!important}.hover\:\!bg-blue-700:hover{background-color:var(--color-blue-700)!important}.hover\:\!bg-emerald-700:hover{background-color:var(--color-emerald-700)!important}.hover\:\!bg-indigo-700:hover{background-color:var(--color-indigo-700)!important}.hover\:\!bg-red-700:hover{background-color:var(--color-red-700)!important}.hover\:bg-amber-100:hover{background-color:var(--color-amber-100)}.hover\:bg-black\/5:hover{background-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/5:hover{background-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.hover\:bg-black\/60:hover{background-color:#0009}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/60:hover{background-color:color-mix(in oklab,var(--color-black)60%,transparent)}}.hover\:bg-blue-100:hover{background-color:var(--color-blue-100)}.hover\:bg-emerald-100:hover{background-color:var(--color-emerald-100)}.hover\:bg-gray-50:hover{background-color:var(--color-gray-50)}.hover\:bg-gray-50\/80:hover{background-color:#f9fafbcc}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-50\/80:hover{background-color:color-mix(in oklab,var(--color-gray-50)80%,transparent)}}.hover\:bg-gray-100:hover{background-color:var(--color-gray-100)}.hover\:bg-gray-100\/70:hover{background-color:#f3f4f6b3}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-100\/70:hover{background-color:color-mix(in oklab,var(--color-gray-100)70%,transparent)}}.hover\:bg-gray-200\/70:hover{background-color:#e5e7ebb3}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-200\/70:hover{background-color:color-mix(in oklab,var(--color-gray-200)70%,transparent)}}.hover\:bg-indigo-100:hover{background-color:var(--color-indigo-100)}.hover\:bg-indigo-200:hover{background-color:var(--color-indigo-200)}.hover\:bg-red-100:hover{background-color:var(--color-red-100)}.hover\:bg-sky-100:hover{background-color:var(--color-sky-100)}.hover\:bg-transparent:hover{background-color:#0000}.hover\:bg-white:hover{background-color:var(--color-white)}.hover\:bg-white\/90:hover{background-color:#ffffffe6}@supports (color:color-mix(in lab,red,red)){.hover\:bg-white\/90:hover{background-color:color-mix(in oklab,var(--color-white)90%,transparent)}}.hover\:text-gray-500:hover{color:var(--color-gray-500)}.hover\:text-gray-600:hover{color:var(--color-gray-600)}.hover\:text-gray-700:hover{color:var(--color-gray-700)}.hover\:text-gray-800:hover{color:var(--color-gray-800)}.hover\:text-gray-900:hover{color:var(--color-gray-900)}.hover\:text-inherit:hover{color:inherit}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-md:hover{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a),0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\:file\:bg-gray-200:hover::file-selector-button{background-color:var(--color-gray-200)}}.focus\:z-10:focus{z-index:10}.focus\:z-20:focus{z-index:20}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-indigo-500:focus{--tw-ring-color:var(--color-indigo-500)}.focus\:outline-hidden:focus{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline-offset:2px;outline:2px solid #0000}}.focus\:outline-2:focus{outline-style:var(--tw-outline-style);outline-width:2px}.focus\:-outline-offset-2:focus{outline-offset:-2px}.focus\:outline-offset-0:focus{outline-offset:0px}.focus\:outline-offset-2:focus{outline-offset:2px}.focus\:outline-indigo-600:focus{outline-color:var(--color-indigo-600)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-blue-500\/60:focus-visible{--tw-ring-color:#3080ff99}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-blue-500\/60:focus-visible{--tw-ring-color:color-mix(in oklab,var(--color-blue-500)60%,transparent)}}.focus-visible\:ring-indigo-500\/60:focus-visible{--tw-ring-color:#625fff99}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-indigo-500\/60:focus-visible{--tw-ring-color:color-mix(in oklab,var(--color-indigo-500)60%,transparent)}}.focus-visible\:ring-indigo-500\/70:focus-visible{--tw-ring-color:#625fffb3}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-indigo-500\/70:focus-visible{--tw-ring-color:color-mix(in oklab,var(--color-indigo-500)70%,transparent)}}.focus-visible\:outline:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\:outline-amber-500:focus-visible{outline-color:var(--color-amber-500)}.focus-visible\:outline-blue-600:focus-visible{outline-color:var(--color-blue-600)}.focus-visible\:outline-emerald-600:focus-visible{outline-color:var(--color-emerald-600)}.focus-visible\:outline-indigo-500:focus-visible{outline-color:var(--color-indigo-500)}.focus-visible\:outline-indigo-600:focus-visible{outline-color:var(--color-indigo-600)}.focus-visible\:outline-red-600:focus-visible{outline-color:var(--color-red-600)}.focus-visible\:outline-white\/70:focus-visible{outline-color:#ffffffb3}@supports (color:color-mix(in lab,red,red)){.focus-visible\:outline-white\/70:focus-visible{outline-color:color-mix(in oklab,var(--color-white)70%,transparent)}}.active\:translate-y-0:active{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.active\:scale-95:active{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x)var(--tw-scale-y)}.active\:cursor-grabbing:active{cursor:grabbing}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.has-focus-visible\:outline-2:has(:focus-visible){outline-style:var(--tw-outline-style);outline-width:2px}.data-closed\:opacity-0[data-closed]{opacity:0}.data-enter\:transform[data-enter]{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.data-enter\:duration-200[data-enter]{--tw-duration:.2s;transition-duration:.2s}.data-enter\:ease-out[data-enter]{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.data-closed\:data-enter\:translate-y-2[data-closed][data-enter]{--tw-translate-y:calc(var(--spacing)*2);translate:var(--tw-translate-x)var(--tw-translate-y)}@supports ((-webkit-backdrop-filter:var(--tw)) or (backdrop-filter:var(--tw))){.supports-\[backdrop-filter\]\:bg-white\/25{background-color:#ffffff40}@supports (color:color-mix(in lab,red,red)){.supports-\[backdrop-filter\]\:bg-white\/25{background-color:color-mix(in oklab,var(--color-white)25%,transparent)}}.supports-\[backdrop-filter\]\:bg-white\/60{background-color:#fff9}@supports (color:color-mix(in lab,red,red)){.supports-\[backdrop-filter\]\:bg-white\/60{background-color:color-mix(in oklab,var(--color-white)60%,transparent)}}}@media(prefers-reduced-motion:reduce){.motion-reduce\:transition-none{transition-property:none}}@media(min-width:40rem){.sm\:sticky{position:sticky}.sm\:top-0{top:calc(var(--spacing)*0)}.sm\:col-span-2{grid-column:span 2/span 2}.sm\:col-span-3{grid-column:span 3/span 3}.sm\:col-span-4{grid-column:span 4/span 4}.sm\:col-span-8{grid-column:span 8/span 8}.sm\:col-span-9{grid-column:span 9/span 9}.sm\:mt-0{margin-top:calc(var(--spacing)*0)}.sm\:ml-16{margin-left:calc(var(--spacing)*16)}.sm\:block{display:block}.sm\:flex{display:flex}.sm\:grid{display:grid}.sm\:hidden{display:none}.sm\:inline{display:inline}.sm\:inline-flex{display:inline-flex}.sm\:max-h-\[calc\(100vh-4rem\)\]{max-height:calc(100vh - 4rem)}.sm\:w-16{width:calc(var(--spacing)*16)}.sm\:w-\[260px\]{width:260px}.sm\:w-auto{width:auto}.sm\:min-w-\[220px\]{min-width:220px}.sm\:flex-1{flex:1}.sm\:flex-auto{flex:auto}.sm\:flex-none{flex:none}.sm\:translate-y-0{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.sm\:scale-95{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x)var(--tw-scale-y)}.sm\:scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x)var(--tw-scale-y)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-12{grid-template-columns:repeat(12,minmax(0,1fr))}.sm\:grid-cols-\[1fr_auto\]{grid-template-columns:1fr auto}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:items-end{align-items:flex-end}.sm\:items-start{align-items:flex-start}.sm\:items-stretch{align-items:stretch}.sm\:justify-between{justify-content:space-between}.sm\:justify-end{justify-content:flex-end}.sm\:justify-start{justify-content:flex-start}.sm\:gap-3{gap:calc(var(--spacing)*3)}.sm\:gap-4{gap:calc(var(--spacing)*4)}:where(.sm\:space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}.sm\:rounded-lg{border-radius:var(--radius-lg)}.sm\:border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.sm\:border-gray-200\/70{border-color:#e5e7ebb3}@supports (color:color-mix(in lab,red,red)){.sm\:border-gray-200\/70{border-color:color-mix(in oklab,var(--color-gray-200)70%,transparent)}}.sm\:p-6{padding:calc(var(--spacing)*6)}.sm\:px-6{padding-inline:calc(var(--spacing)*6)}.sm\:py-4{padding-block:calc(var(--spacing)*4)}.sm\:data-closed\:data-enter\:-translate-x-2[data-closed][data-enter]{--tw-translate-x:calc(var(--spacing)*-2);translate:var(--tw-translate-x)var(--tw-translate-y)}.sm\:data-closed\:data-enter\:translate-x-2[data-closed][data-enter]{--tw-translate-x:calc(var(--spacing)*2);translate:var(--tw-translate-x)var(--tw-translate-y)}.sm\:data-closed\:data-enter\:translate-y-0[data-closed][data-enter]{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}}@media(min-width:48rem){.md\:inline-block{display:inline-block}.md\:w-72{width:calc(var(--spacing)*72)}}@media(min-width:64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-\[320px_1fr\]{grid-template-columns:320px 1fr}.lg\:px-8{padding-inline:calc(var(--spacing)*8)}}@media(prefers-color-scheme:dark){:where(.dark\:divide-white\/10>:not(:last-child)){border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){:where(.dark\:divide-white\/10>:not(:last-child)){border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:border-amber-400\/20{border-color:#fcbb0033}@supports (color:color-mix(in lab,red,red)){.dark\:border-amber-400\/20{border-color:color-mix(in oklab,var(--color-amber-400)20%,transparent)}}.dark\:border-amber-500\/30{border-color:#f99c004d}@supports (color:color-mix(in lab,red,red)){.dark\:border-amber-500\/30{border-color:color-mix(in oklab,var(--color-amber-500)30%,transparent)}}.dark\:border-emerald-400\/20{border-color:#00d29433}@supports (color:color-mix(in lab,red,red)){.dark\:border-emerald-400\/20{border-color:color-mix(in oklab,var(--color-emerald-400)20%,transparent)}}.dark\:border-green-500\/30{border-color:#00c7584d}@supports (color:color-mix(in lab,red,red)){.dark\:border-green-500\/30{border-color:color-mix(in oklab,var(--color-green-500)30%,transparent)}}.dark\:border-indigo-400{border-color:var(--color-indigo-400)}.dark\:border-red-500\/30{border-color:#fb2c364d}@supports (color:color-mix(in lab,red,red)){.dark\:border-red-500\/30{border-color:color-mix(in oklab,var(--color-red-500)30%,transparent)}}.dark\:border-rose-400\/20{border-color:#ff667f33}@supports (color:color-mix(in lab,red,red)){.dark\:border-rose-400\/20{border-color:color-mix(in oklab,var(--color-rose-400)20%,transparent)}}.dark\:border-sky-400\/20{border-color:#00bcfe33}@supports (color:color-mix(in lab,red,red)){.dark\:border-sky-400\/20{border-color:color-mix(in oklab,var(--color-sky-400)20%,transparent)}}.dark\:border-white\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:border-white\/10{border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:\!bg-amber-500{background-color:var(--color-amber-500)!important}.dark\:\!bg-blue-500{background-color:var(--color-blue-500)!important}.dark\:\!bg-emerald-500{background-color:var(--color-emerald-500)!important}.dark\:\!bg-indigo-500{background-color:var(--color-indigo-500)!important}.dark\:\!bg-red-500{background-color:var(--color-red-500)!important}.dark\:bg-amber-400\/10{background-color:#fcbb001a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-amber-400\/10{background-color:color-mix(in oklab,var(--color-amber-400)10%,transparent)}}.dark\:bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500)10%,transparent)}}.dark\:bg-amber-500\/20{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.dark\:bg-amber-500\/20{background-color:color-mix(in oklab,var(--color-amber-500)20%,transparent)}}.dark\:bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab,red,red)){.dark\:bg-black\/40{background-color:color-mix(in oklab,var(--color-black)40%,transparent)}}.dark\:bg-blue-500\/20{background-color:#3080ff33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-blue-500\/20{background-color:color-mix(in oklab,var(--color-blue-500)20%,transparent)}}.dark\:bg-emerald-400\/10{background-color:#00d2941a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-emerald-400\/10{background-color:color-mix(in oklab,var(--color-emerald-400)10%,transparent)}}.dark\:bg-emerald-500\/10{background-color:#00bb7f1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-emerald-500\/10{background-color:color-mix(in oklab,var(--color-emerald-500)10%,transparent)}}.dark\:bg-emerald-500\/15{background-color:#00bb7f26}@supports (color:color-mix(in lab,red,red)){.dark\:bg-emerald-500\/15{background-color:color-mix(in oklab,var(--color-emerald-500)15%,transparent)}}.dark\:bg-emerald-500\/20{background-color:#00bb7f33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-emerald-500\/20{background-color:color-mix(in oklab,var(--color-emerald-500)20%,transparent)}}.dark\:bg-gray-700\/50{background-color:#36415380}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-700\/50{background-color:color-mix(in oklab,var(--color-gray-700)50%,transparent)}}.dark\:bg-gray-800{background-color:var(--color-gray-800)}.dark\:bg-gray-800\/50{background-color:#1e293980}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-800\/50{background-color:color-mix(in oklab,var(--color-gray-800)50%,transparent)}}.dark\:bg-gray-800\/70{background-color:#1e2939b3}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-800\/70{background-color:color-mix(in oklab,var(--color-gray-800)70%,transparent)}}.dark\:bg-gray-900{background-color:var(--color-gray-900)}.dark\:bg-gray-900\/40{background-color:#10182866}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-900\/40{background-color:color-mix(in oklab,var(--color-gray-900)40%,transparent)}}.dark\:bg-gray-900\/50{background-color:#10182880}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-900\/50{background-color:color-mix(in oklab,var(--color-gray-900)50%,transparent)}}.dark\:bg-gray-900\/95{background-color:#101828f2}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-900\/95{background-color:color-mix(in oklab,var(--color-gray-900)95%,transparent)}}.dark\:bg-gray-950{background-color:var(--color-gray-950)}.dark\:bg-gray-950\/35{background-color:#03071259}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-950\/35{background-color:color-mix(in oklab,var(--color-gray-950)35%,transparent)}}.dark\:bg-gray-950\/40{background-color:#03071266}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-950\/40{background-color:color-mix(in oklab,var(--color-gray-950)40%,transparent)}}.dark\:bg-gray-950\/50{background-color:#03071280}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-950\/50{background-color:color-mix(in oklab,var(--color-gray-950)50%,transparent)}}.dark\:bg-gray-950\/60{background-color:#03071299}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-950\/60{background-color:color-mix(in oklab,var(--color-gray-950)60%,transparent)}}.dark\:bg-gray-950\/70{background-color:#030712b3}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-950\/70{background-color:color-mix(in oklab,var(--color-gray-950)70%,transparent)}}.dark\:bg-gray-950\/90{background-color:#030712e6}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-950\/90{background-color:color-mix(in oklab,var(--color-gray-950)90%,transparent)}}.dark\:bg-green-500\/10{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-green-500\/10{background-color:color-mix(in oklab,var(--color-green-500)10%,transparent)}}.dark\:bg-indigo-400{background-color:var(--color-indigo-400)}.dark\:bg-indigo-400\/10{background-color:#7d87ff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-400\/10{background-color:color-mix(in oklab,var(--color-indigo-400)10%,transparent)}}.dark\:bg-indigo-500{background-color:var(--color-indigo-500)}.dark\:bg-indigo-500\/10{background-color:#625fff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-500\/10{background-color:color-mix(in oklab,var(--color-indigo-500)10%,transparent)}}.dark\:bg-indigo-500\/20{background-color:#625fff33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-500\/20{background-color:color-mix(in oklab,var(--color-indigo-500)20%,transparent)}}.dark\:bg-indigo-500\/40{background-color:#625fff66}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-500\/40{background-color:color-mix(in oklab,var(--color-indigo-500)40%,transparent)}}.dark\:bg-indigo-500\/70{background-color:#625fffb3}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-500\/70{background-color:color-mix(in oklab,var(--color-indigo-500)70%,transparent)}}.dark\:bg-red-400\/10{background-color:#ff65681a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-400\/10{background-color:color-mix(in oklab,var(--color-red-400)10%,transparent)}}.dark\:bg-red-500\/10{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-500\/10{background-color:color-mix(in oklab,var(--color-red-500)10%,transparent)}}.dark\:bg-red-500\/15{background-color:#fb2c3626}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-500\/15{background-color:color-mix(in oklab,var(--color-red-500)15%,transparent)}}.dark\:bg-red-500\/20{background-color:#fb2c3633}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-500\/20{background-color:color-mix(in oklab,var(--color-red-500)20%,transparent)}}.dark\:bg-rose-400\/10{background-color:#ff667f1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-rose-400\/10{background-color:color-mix(in oklab,var(--color-rose-400)10%,transparent)}}.dark\:bg-sky-400\/10{background-color:#00bcfe1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-sky-400\/10{background-color:color-mix(in oklab,var(--color-sky-400)10%,transparent)}}.dark\:bg-sky-400\/20{background-color:#00bcfe33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-sky-400\/20{background-color:color-mix(in oklab,var(--color-sky-400)20%,transparent)}}.dark\:bg-sky-500\/10{background-color:#00a5ef1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-sky-500\/10{background-color:color-mix(in oklab,var(--color-sky-500)10%,transparent)}}.dark\:bg-transparent{background-color:#0000}.dark\:bg-white\/5{background-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/5{background-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:bg-white\/10{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/10{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:from-white\/10{--tw-gradient-from:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:from-white\/10{--tw-gradient-from:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:from-white\/10{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.dark\:via-transparent{--tw-gradient-via:transparent;--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.dark\:to-white\/5{--tw-gradient-to:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:to-white\/5{--tw-gradient-to:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:to-white\/5{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.dark\:fill-gray-400{fill:var(--color-gray-400)}.dark\:text-amber-200{color:var(--color-amber-200)}.dark\:text-amber-300{color:var(--color-amber-300)}.dark\:text-blue-400{color:var(--color-blue-400)}.dark\:text-emerald-200{color:var(--color-emerald-200)}.dark\:text-emerald-300{color:var(--color-emerald-300)}.dark\:text-emerald-400{color:var(--color-emerald-400)}.dark\:text-gray-100{color:var(--color-gray-100)}.dark\:text-gray-200{color:var(--color-gray-200)}.dark\:text-gray-300{color:var(--color-gray-300)}.dark\:text-gray-400{color:var(--color-gray-400)}.dark\:text-gray-500{color:var(--color-gray-500)}.dark\:text-gray-600{color:var(--color-gray-600)}.dark\:text-green-200{color:var(--color-green-200)}.dark\:text-indigo-100{color:var(--color-indigo-100)}.dark\:text-indigo-200{color:var(--color-indigo-200)}.dark\:text-indigo-300{color:var(--color-indigo-300)}.dark\:text-indigo-400{color:var(--color-indigo-400)}.dark\:text-indigo-500{color:var(--color-indigo-500)}.dark\:text-orange-200{color:var(--color-orange-200)}.dark\:text-red-200{color:var(--color-red-200)}.dark\:text-red-300{color:var(--color-red-300)}.dark\:text-red-400{color:var(--color-red-400)}.dark\:text-rose-200{color:var(--color-rose-200)}.dark\:text-rose-300{color:var(--color-rose-300)}.dark\:text-sky-100{color:var(--color-sky-100)}.dark\:text-sky-200{color:var(--color-sky-200)}.dark\:text-sky-300{color:var(--color-sky-300)}.dark\:text-white{color:var(--color-white)}.dark\:text-white\/70{color:#ffffffb3}@supports (color:color-mix(in lab,red,red)){.dark\:text-white\/70{color:color-mix(in oklab,var(--color-white)70%,transparent)}}.dark\:text-white\/90{color:#ffffffe6}@supports (color:color-mix(in lab,red,red)){.dark\:text-white\/90{color:color-mix(in oklab,var(--color-white)90%,transparent)}}.dark\:\[color-scheme\:dark\]{color-scheme:dark}.dark\:shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.dark\:ring-amber-400\/20{--tw-ring-color:#fcbb0033}@supports (color:color-mix(in lab,red,red)){.dark\:ring-amber-400\/20{--tw-ring-color:color-mix(in oklab,var(--color-amber-400)20%,transparent)}}.dark\:ring-amber-400\/25{--tw-ring-color:#fcbb0040}@supports (color:color-mix(in lab,red,red)){.dark\:ring-amber-400\/25{--tw-ring-color:color-mix(in oklab,var(--color-amber-400)25%,transparent)}}.dark\:ring-amber-500\/30{--tw-ring-color:#f99c004d}@supports (color:color-mix(in lab,red,red)){.dark\:ring-amber-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-amber-500)30%,transparent)}}.dark\:ring-emerald-400\/20{--tw-ring-color:#00d29433}@supports (color:color-mix(in lab,red,red)){.dark\:ring-emerald-400\/20{--tw-ring-color:color-mix(in oklab,var(--color-emerald-400)20%,transparent)}}.dark\:ring-emerald-400\/25{--tw-ring-color:#00d29440}@supports (color:color-mix(in lab,red,red)){.dark\:ring-emerald-400\/25{--tw-ring-color:color-mix(in oklab,var(--color-emerald-400)25%,transparent)}}.dark\:ring-emerald-500\/30{--tw-ring-color:#00bb7f4d}@supports (color:color-mix(in lab,red,red)){.dark\:ring-emerald-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-emerald-500)30%,transparent)}}.dark\:ring-indigo-400\/20{--tw-ring-color:#7d87ff33}@supports (color:color-mix(in lab,red,red)){.dark\:ring-indigo-400\/20{--tw-ring-color:color-mix(in oklab,var(--color-indigo-400)20%,transparent)}}.dark\:ring-indigo-400\/30{--tw-ring-color:#7d87ff4d}@supports (color:color-mix(in lab,red,red)){.dark\:ring-indigo-400\/30{--tw-ring-color:color-mix(in oklab,var(--color-indigo-400)30%,transparent)}}.dark\:ring-orange-400\/20{--tw-ring-color:#ff8b1a33}@supports (color:color-mix(in lab,red,red)){.dark\:ring-orange-400\/20{--tw-ring-color:color-mix(in oklab,var(--color-orange-400)20%,transparent)}}.dark\:ring-red-400\/25{--tw-ring-color:#ff656840}@supports (color:color-mix(in lab,red,red)){.dark\:ring-red-400\/25{--tw-ring-color:color-mix(in oklab,var(--color-red-400)25%,transparent)}}.dark\:ring-red-500\/30{--tw-ring-color:#fb2c364d}@supports (color:color-mix(in lab,red,red)){.dark\:ring-red-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-red-500)30%,transparent)}}.dark\:ring-sky-400\/20{--tw-ring-color:#00bcfe33}@supports (color:color-mix(in lab,red,red)){.dark\:ring-sky-400\/20{--tw-ring-color:color-mix(in oklab,var(--color-sky-400)20%,transparent)}}.dark\:ring-white\/10{--tw-ring-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:ring-white\/10{--tw-ring-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:ring-white\/15{--tw-ring-color:#ffffff26}@supports (color:color-mix(in lab,red,red)){.dark\:ring-white\/15{--tw-ring-color:color-mix(in oklab,var(--color-white)15%,transparent)}}.dark\:inset-ring-gray-700{--tw-inset-ring-color:var(--color-gray-700)}.dark\:inset-ring-indigo-400\/50{--tw-inset-ring-color:#7d87ff80}@supports (color:color-mix(in lab,red,red)){.dark\:inset-ring-indigo-400\/50{--tw-inset-ring-color:color-mix(in oklab,var(--color-indigo-400)50%,transparent)}}.dark\:inset-ring-white\/5{--tw-inset-ring-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:inset-ring-white\/5{--tw-inset-ring-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:inset-ring-white\/10{--tw-inset-ring-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:inset-ring-white\/10{--tw-inset-ring-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:outline{outline-style:var(--tw-outline-style);outline-width:1px}.dark\:-outline-offset-1{outline-offset:-1px}.dark\:outline-indigo-500{outline-color:var(--color-indigo-500)}.dark\:outline-white\/10{outline-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:outline-white\/10{outline-color:color-mix(in oklab,var(--color-white)10%,transparent)}}:is(.dark\:\*\:bg-gray-800>*){background-color:var(--color-gray-800)}@media(hover:hover){.dark\:group-hover\:text-gray-400:is(:where(.group):hover *){color:var(--color-gray-400)}.dark\:group-hover\:text-indigo-400:is(:where(.group):hover *){color:var(--color-indigo-400)}}.dark\:file\:bg-white\/10::file-selector-button{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:file\:bg-white\/10::file-selector-button{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:file\:text-white::file-selector-button{color:var(--color-white)}.dark\:even\:bg-gray-800\/50:nth-child(2n){background-color:#1e293980}@supports (color:color-mix(in lab,red,red)){.dark\:even\:bg-gray-800\/50:nth-child(2n){background-color:color-mix(in oklab,var(--color-gray-800)50%,transparent)}}@media(hover:hover){.dark\:hover\:border-indigo-400\/30:hover{border-color:#7d87ff4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:border-indigo-400\/30:hover{border-color:color-mix(in oklab,var(--color-indigo-400)30%,transparent)}}.dark\:hover\:border-white\/20:hover{border-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:border-white\/20:hover{border-color:color-mix(in oklab,var(--color-white)20%,transparent)}}.dark\:hover\:\!bg-amber-400:hover{background-color:var(--color-amber-400)!important}.dark\:hover\:\!bg-blue-400:hover{background-color:var(--color-blue-400)!important}.dark\:hover\:\!bg-emerald-400:hover{background-color:var(--color-emerald-400)!important}.dark\:hover\:\!bg-indigo-400:hover{background-color:var(--color-indigo-400)!important}.dark\:hover\:\!bg-red-400:hover{background-color:var(--color-red-400)!important}.dark\:hover\:bg-amber-500\/30:hover{background-color:#f99c004d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-amber-500\/30:hover{background-color:color-mix(in oklab,var(--color-amber-500)30%,transparent)}}.dark\:hover\:bg-black\/55:hover{background-color:#0000008c}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-black\/55:hover{background-color:color-mix(in oklab,var(--color-black)55%,transparent)}}.dark\:hover\:bg-black\/60:hover{background-color:#0009}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-black\/60:hover{background-color:color-mix(in oklab,var(--color-black)60%,transparent)}}.dark\:hover\:bg-blue-500\/30:hover{background-color:#3080ff4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-blue-500\/30:hover{background-color:color-mix(in oklab,var(--color-blue-500)30%,transparent)}}.dark\:hover\:bg-emerald-500\/30:hover{background-color:#00bb7f4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-emerald-500\/30:hover{background-color:color-mix(in oklab,var(--color-emerald-500)30%,transparent)}}.dark\:hover\:bg-indigo-500\/30:hover{background-color:#625fff4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-indigo-500\/30:hover{background-color:color-mix(in oklab,var(--color-indigo-500)30%,transparent)}}.dark\:hover\:bg-indigo-500\/50:hover{background-color:#625fff80}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-indigo-500\/50:hover{background-color:color-mix(in oklab,var(--color-indigo-500)50%,transparent)}}.dark\:hover\:bg-red-500\/30:hover{background-color:#fb2c364d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-red-500\/30:hover{background-color:color-mix(in oklab,var(--color-red-500)30%,transparent)}}.dark\:hover\:bg-sky-400\/20:hover{background-color:#00bcfe33}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-sky-400\/20:hover{background-color:color-mix(in oklab,var(--color-sky-400)20%,transparent)}}.dark\:hover\:bg-white\/5:hover{background-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/5:hover{background-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:hover\:bg-white\/10:hover{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/10:hover{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:hover\:bg-white\/20:hover{background-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/20:hover{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}}.dark\:hover\:text-gray-200:hover{color:var(--color-gray-200)}.dark\:hover\:text-gray-300:hover{color:var(--color-gray-300)}.dark\:hover\:text-gray-400:hover{color:var(--color-gray-400)}.dark\:hover\:text-white:hover{color:var(--color-white)}.dark\:hover\:shadow-none:hover{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.dark\:hover\:file\:bg-white\/20:hover::file-selector-button{background-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:file\:bg-white\/20:hover::file-selector-button{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}}}.dark\:focus\:outline-indigo-500:focus{outline-color:var(--color-indigo-500)}.dark\:focus-visible\:ring-white\/40:focus-visible{--tw-ring-color:#fff6}@supports (color:color-mix(in lab,red,red)){.dark\:focus-visible\:ring-white\/40:focus-visible{--tw-ring-color:color-mix(in oklab,var(--color-white)40%,transparent)}}.dark\:focus-visible\:outline-amber-500:focus-visible{outline-color:var(--color-amber-500)}.dark\:focus-visible\:outline-blue-500:focus-visible{outline-color:var(--color-blue-500)}.dark\:focus-visible\:outline-emerald-500:focus-visible{outline-color:var(--color-emerald-500)}.dark\:focus-visible\:outline-indigo-500:focus-visible{outline-color:var(--color-indigo-500)}.dark\:focus-visible\:outline-red-500:focus-visible{outline-color:var(--color-red-500)}@supports ((-webkit-backdrop-filter:var(--tw)) or (backdrop-filter:var(--tw))){.dark\:supports-\[backdrop-filter\]\:bg-gray-950\/25{background-color:#03071240}@supports (color:color-mix(in lab,red,red)){.dark\:supports-\[backdrop-filter\]\:bg-gray-950\/25{background-color:color-mix(in oklab,var(--color-gray-950)25%,transparent)}}.dark\:supports-\[backdrop-filter\]\:bg-gray-950\/35{background-color:#03071259}@supports (color:color-mix(in lab,red,red)){.dark\:supports-\[backdrop-filter\]\:bg-gray-950\/35{background-color:color-mix(in oklab,var(--color-gray-950)35%,transparent)}}.dark\:supports-\[backdrop-filter\]\:bg-gray-950\/40{background-color:#03071266}@supports (color:color-mix(in lab,red,red)){.dark\:supports-\[backdrop-filter\]\:bg-gray-950\/40{background-color:color-mix(in oklab,var(--color-gray-950)40%,transparent)}}}}@media(min-width:40rem){@media(prefers-color-scheme:dark){.sm\:dark\:border-white\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.sm\:dark\:border-white\/10{border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}}}}:root{color-scheme:light dark;color:#ffffffde;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background-color:#242424;font-family:system-ui,Avenir,Helvetica,Arial,sans-serif;font-weight:400;line-height:1.5}@media(prefers-color-scheme:light){:root{color:#213547;background-color:#fff}a:hover{color:#747bff}button{background-color:#f9f9f9}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}}.vjs-svg-icon{display:inline-block;background-repeat:no-repeat;background-position:center;fill:currentColor;height:1.8em;width:1.8em}.vjs-svg-icon:before{content:none!important}.vjs-svg-icon:hover,.vjs-control:focus .vjs-svg-icon{filter:drop-shadow(0 0 .25em #fff)}.vjs-modal-dialog .vjs-modal-dialog-content,.video-js .vjs-modal-dialog,.vjs-button>.vjs-icon-placeholder:before,.video-js .vjs-big-play-button .vjs-icon-placeholder:before{position:absolute;top:0;left:0;width:100%;height:100%}.vjs-button>.vjs-icon-placeholder:before,.video-js .vjs-big-play-button .vjs-icon-placeholder:before{text-align:center}@font-face{font-family:VideoJS;src:url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABTsAAsAAAAAIpAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAADsAAABUIIslek9TLzIAAAFEAAAAPgAAAFZRiV32Y21hcAAAAYQAAAEJAAAD5p42+VxnbHlmAAACkAAADtIAABckI4l972hlYWQAABFkAAAAKwAAADYsvIjpaGhlYQAAEZAAAAAdAAAAJA+RCL1obXR4AAARsAAAABcAAAC8Q2YAAGxvY2EAABHIAAAAYAAAAGB7CIGGbWF4cAAAEigAAAAfAAAAIAFAAI9uYW1lAAASSAAAASUAAAIK1cf1oHBvc3QAABNwAAABfAAAAnXdFqh1eJxjYGRgYOBiMGCwY2BycfMJYeDLSSzJY5BiYGGAAJA8MpsxJzM9kYEDxgPKsYBpDiBmg4gCACY7BUgAeJxjYGR7yDiBgZWBgaWQ5RkDA8MvCM0cwxDOeI6BgYmBlZkBKwhIc01hcPjI+FGPHcRdyA4RZgQRADaGCyYAAHic7dPXbcMwAEXRK1vuvffem749XAbKV3bjBA6fXsaIgMMLEWoQJaAEFKNnlELyQ4K27zib5PNF6vl8yld+TKr5kH0+cUw0xv00Hwvx2DResUyFKrV4XoMmLdp06NKjz4AhI8ZMmDJjzoIlK9Zs2LJjz4EjJ85cuHLjziPe/0UWL17mf2tqKLz/9jK9f8tXpGCoRdPKhtS0RqFkWvVQNtSKoVYNtWaoddPXEBqG2jQ9XWgZattQO4baNdSeofYNdWCoQ0MdGerYUCeGOjXUmaHODXVhqEtDXRnq2lA3hro11J2h7g31YKhHQz0Z6tlQL4Z6NdSbod4N9WGoT9MfHF6GmhnZLxyDcRMAAAB4nJ1YC1hU17U+a5/HMA4iA3NmVBDmoQwP5TFnHlFeA4gYiUFRQINoSCBAyK3G2yi+0aipYtFcHYo2xsb4NiY3+VrNxSaX5uvt495ozNdoYoxmem2/L8HGpLc+InB279pnhlGr5mvL4eyz99nrrL32eu1/DQcc/okdYgdHOA6MQKp4r9gx0EcMHMezOalVasW5BM7NcXoSb9fFgE6KtSSBxWz1FYDPG+vMBGcKb9cebu2VS5s2aaTkCvRSf6C7Y+Ppibm5E09v7IDs2/3uZQtbD0zIyppwoHXh/93ukmyYgdePNRp65p5v+3v/9otQl2O7wP34cT88p8Md2YxpYLQZoRcy6FlSBRnwnGAe6BPMSCZo+7NJVqS0cE4uHendzhSnbPH6TDqL1+Nme5LZXkCHnGyoH0kne30WH+gswhm3q+pt/mTas9NLS64GnjmSlTPw0wVQT/ewRaBgxtydy3cuUB9/6SW+vb5yRvr+t0eOfPKJZ/9t3+4tL7xj32Xd3thCxi+ge6ifdsAN+l5+wi5HQ/cCoeull1AszS7CUfEcJzK7sKWJAdJhCd0sPM4+EY7QDm5ov08hXRQXE5bf6PV5Q5+IjW7X7Nku92Ask4l2hCRRD6TPqISiCJeQna3SCFwrhrNzXHzo4yFevBwxpzxk8WCIIfkvVEKVy32SbT8n68gzgaslpaiO2zIGIyuSb7RNf9HSuN26y/7OC1tgEmpiyA6aD4qcgTOiLThwGG0eB694FI8NHLLN6OBlRVaMxNAFS4JdXUG6mW8PwpKuYLCLXKGbu8iwYNdgO06Sn3Th+/vyZAxs8Ro30DjHe9gy8Fywi24OMm7Qyzh3MTZVOMYhLBnoC+J79lpTUyQmorjhnMwlcQ5uPEYGpDjsOkkH49BjQLQBqs3jFtFdJNlksYmoQFDArLh8Xh+Qd6Ghcsb6FUuehDi+U/lqD71K/qiegeV1imcwjl7ExwiSrf4BZyCujV6cVcFo6VX+G9IcPyFjJnUufbU/jzrL1X99as36reXl8K32nFaOr+E8jWJEcJ55DpMVfSMe95/AJaOsGBH2GJCNpiRQbK4C8BjdmQA22QY2j03Em13i2YHqtNLU1NI04Yj2HJgA6fQc6VPNpA/D+Ryks554NnVy2mB72uRUfPLsqR4N0LOBQKArwJYO+5W2fgZX8oC1HR6HjNaQTVIG2FPwnTcXXGZZfNB7TE6pTKZUwaw91XWLAoFFGcnB5PHjsckgBjbWutrL+0h5Y1xw3DRGDumsnXb3MJwXrJIN5U7m0rgJ3yG5w4he5ckFG4pmNEkOm0/xOO4r4yL87wqtQM+hiJIVp+6iG2wPBKD35ElGkDx+UfC2v1mFG1o+M3AjNFty8biKMXwzyxnZLds8wYD2BxmCPHAldPOeLsy/0BugftYhVYFAhO8SqQ0j3oK7dHJZnI/jxmUS4onlxskSF8thmvNZjIrRZwEPxr0lBuLRuz3oy/FOHCsxwOPYh2M+e9u3J5pgPYz9gp6G7C9m0A11F9ddqKMfV+4sbq45/YspOysXvT+3pdFdYNg2fHbW8Dz301MqDVuGrz0Fuh0YMW8mddrpqzST7rV9BcvqPoNvadRndWp0p8HvbiqrFj5yFQ/vNFSXDpxpLEFWp+DcrF3FT1afWshFcmCfeAMjEvO65i0Y6XijQfSRPWx3TV/Df7Km3E1l+kLt56s/rwVzuRusNMhudznkwdLaS+QNdeal2jDPP4l9qHc98vTYZOSkxzD+njBWVWjFPKgipx6DkWvXQiW8OYcewVHE5yukinDMcfGgc0opDltYKDxIGBedkzc6jSfE7tlvESCDFUw0Hx0opS+U0lHCxNottbNWSxX9zZVvEhKWUSyBpaXwBc2a98M6UqPeXAs/GDon8Ax7hsthO8cM5HU7Ad0UvRR9lHmtyQKZ4MAe814X5h9MSUkQmhf96eVJ6p90OjIiqSIjvykvr2l5U55O/fPQKD+jIomYpNyGJQ25uQ2kIikRfAmuBHCPsWqkSDEqgZ5KDI2sifS/R43MbZg0idFHbCPNxXxZws1ACVE6hAhOdJwRkJLFBLPZpRGYJ50pko6XzMkgmSx40ljik6AQcKhFnLcQE6rF7PXFe1Ocoj0T3AXgSgJTDIhHRfHlYZKuSzc6uievOJGXY+i5GJkkTp7UM3y0LqATDbtFcbdBxO7o4T25JYlEjoH0uynUh8rapkxp62QN70svSF+hT4gGPlovlmcm/ComLi7mV4kTykV9NFWjE/QrwgQ4uIcAP0rQF4VZYRP2o3PhHHzfPMJj9Ir+uzKUlrH49ntT18AVvj1sc3YGjUT/Mt2Dxawa8ArcA7bCQIpvfwAYu22vEG/No/5RvPdA7g+AelLrPwzy+LtkLPhnpIxH14m4EYq8eeMHbPEPNm6G7Nv9B4jcFPZ8bJj0SEjP3MPgQdKTqqEoy2v6G32P/Y6dxOv04AxnoAeq+GILvUavtYCBXm+BaIhuodcfrN5B/V2EYMCPh+SxavjGyPwV0x4CJgUPGT0mQaODGBACIJZGsMXwAD0LGXx7l3CdAcKMIKI+f5CepWeD0BvyU/GcdBxPF8SwejC6LGZmAURFdsSWKR5HyHld2kbdIZO1Ixx+bnnzU7n5+blPNV9jnUDWhP2tC68tbN3PVIldsQPxSAcSpjOav7Q05uXn5zW2LLvDXn9B6syscPy9iDLEMmSrJz6nYuWMipukjM0AH8JkGS+XFyMRkzSCH7KD/hwm172SAyZYumHlefr5AddrtA0O0TnwaVZxcRY9Bfukn9Gf05N1r9DV9MoBsJ1f+ZrqUvtPHizJAntWybv7hmqLt6QLuK6ZS9Fqi1jO5rDoWPZXXII5Tgajg53cIXCjDCGIcYrRIY2n6+mXOa/W0bdhau3ryiEYe2FV/5oeaIYK/5w5frCyll6/cYO8DiNhw6t1MBWmznt91QX62UF1N7l0eHBZTRGpKaqpKVIPF9UcIzmReud9TSY75+K899GHbBu6wjoR7RKKZVYiYxSPf5/2wJT5e3NAhmUbVn5KLx1Ujg0+BGvpAIh0DezInTkzF37KVocxrKU3r1+XLtAe2lO3l66kfQfB/unKY+q8N375Ru8bc4pJXfEcESU95q+p8ZNZRTWH1d9FzvUdYXk5rLkcdkEisoKKVHQW/b3GEx6tPaYcoJfOr9wAbSBnv1IHpep0OExr4LPMkpJM+j7sly7UHkOzXjoAZljHCGiyegtNlwljM0v+c19ET9Pvst09a2Mtgcf5/ZSzYO5h1156+eyydfAsxGa9XAuF6vzjh6CssLq6ECysperXX0sX5h5ZdpZe3guxsGIPEtHk/aqXX1hVqP5HYVVVISkrrNqvXorIc+5Ou91Hnr/LcD2afi6eX7UBloOcs7cOpqgGaNfs1g7bNbs9z6wASaylN69d0/TFTIz6Ws8+oGV3mE2612wRTHKcVUbhjKadebloMc+dyXgMVtVK6BwMB/+mVW09igdRBWaRtNQX59d/VD//xdQ0TCiYNj1KT9sq6Wdu5WTbqk3qDXyDaLa1fv621LS01G3z61sD6lH8lAxDLicV921s6Bf92JOYvzNYCL1khbqBXEFUzC521N5NyzNaQIWhjyFyDoBIVrAjmv2UEaLlI+c6zw1jmVIPLLLZZUTj6GxGHW+mq1tgHXR2D85p4Q934+jLbtjVLcyCdS10NVzpHqxp4Q/hK7WopY/NRGx9HGsPGdFjOjcpjBnGYMVqY/4eqT5khWEHWUup2A/pTw7pdWgsWft7ETUERL96nRg0HNFPmCYba6pylECaExX89A9WLUOVB4oKLu/o1oqSYHCgLzBUlAz8hNFDRpeSU1XT+LRmDUgPaKbYdHDn9suF/tu13nHJij0N97LfS0QmqONuyONk7zvUI6Qa0pF9f2+oABL92AT6e0U//z9YqAiWtJLU1JK0gS+1aacwamiNqK067u9ZQ8f1d4qLodMzz3uL89Z68V/Hnr++hXWUuHgw8dfi972PeTyPefu3aNNucemQ74qFuIaJnVkOu4Q+yjuwmmC1FqZpl1i4uzoPxjkpPf3Xv545tl26Rr+dOvUd+omqJzch9dOeU7f10Y64nMcKK137DccIZq2WdXtdZjbEoLSzHwiMtrjYLDxpHQW8gjMX6XFYAE2zSWVD04EGYSs9MbO6sEo20BMEAB4mpvSypsKjZ4Stgzb+c3A9/MQT2+vrBy+qvyFxLUtLlSRF/Ri2wjfZ2dus2Q8lXx4608/jnqK5OOap6NY2PSjYYnECCjiEeLJll/pbmqfeIK+ps3+MxrlEhqmTPipVP7kqlF4VhpEb6r+Q7YOJg38kJ9SHBf3NBl6+9YchfbUjb5ahLSzUM3kPHmwFAsZ5rpai0S7E5xWzZ1j+fW7zsUWP2g5NXTw52ySCTrgG0+lbw60l2Y/CB185CoA8NK+tbRKxfjy6pm5hzQRRR+cMqv1Jbiw6STivtEvt3DRcy0QEh92JlUGo2PG4tSKHl00YD6xc8CK+YPYyy3io2lN8BcSjKRzrIV6ypOAobqxViJPaT9M9Hy5szY33mp7OX/Zu89L/7Ww5vqY2Y8b0pKgoiUhG5cPDPzq8qTV/WkzUOIvXVVA96kmjcBrr3HrYC/Wn+fYP6Z7T1rqy3zknbvqma/FvVk96fNXGkuaXrdHW5JGSxZT/2I/O73v+yNWafMdzc5NdxYurHs6h86e01sLKLz9EBrg+x36rxAaED7hRnAMx7Vzu+9wabh3zG8XLQjx0ablUJzmxdErxYT3kzQSd0SSafVqF5PXgpp0OyYJ1EyNHpGUZmvK575ySzd85JSqF7IBzSAbMM04+MbE58xF3/njXOGecSaermlw2y9PsSQdytLJVr8t+wg+rR8cZYoeNxVIzNdk3Bngi8U5LAlgTFoQnzJCa5EsCgYhCaGL+qPj7TdhG31p9tej3R04N//PXxNwJvyUqwaJqRPJY98TJ5TPndmflRAkAhBfe46sfKW5wizSge08Xb7Ca/GUVs55trngkKkrUS2WPzKttaaqq+idmahugkY+W6fN0I6i3gPt/x88U4wAAeJxjYGRgYADiGU9YXsXz23xl4GZnAIFH7fO+IdMc/WBxDgYmEAUASbMKwAB4nGNgZGBgZwABjj4Ghv//OfoZGBlQgT4ARicDZAAAAHicY2BgYGAfxJijD8Fmu4EqBwCSpgKpAAAAAAAADgBoAH4AzADgAQIBQgFsAZgB7gIuAooC0AL8A2IDjAOoA+AEMASwBNoFCAVaBcAGCAYuBnAGrAb2B04HigfSCCoIcAiGCJwIyAkkCVYJiAmsCfIKIApWCsQLknicY2BkYGDQZ2hmYGcAASYg5gJCBob/YD4DABqrAdAAeJxdkE1qg0AYhl8Tk9AIoVDaVSmzahcF87PMARLIMoFAl0ZHY1BHdBJIT9AT9AQ9RQ9Qeqy+yteNMzDzfM+88w0K4BY/cNAMB6N2bUaPPBLukybCLvleeAAPj8JD+hfhMV7hC3u4wxs7OO4NzQSZcI/8Ltwnfwi75E/hAR7wJTyk/xYeY49fYQ/PztM+jbTZ7LY6OWdBJdX/pqs6NYWa+zMxa13oKrA6Uoerqi/JwtpYxZXJ1coUVmeZUWVlTjq0/tHacjmdxuL90OR8O0UEDYMNdtiSEpz5XQGqzlm30kzUdAYFFOb8R7NOZk0q2lwAyz1i7oAr1xoXvrOgtYhZx8wY5KRV269JZ5yGpmzPTjQhvY9je6vEElPOuJP3mWKnP5M3V+YAAAB4nG2ReVPbMBDF/ULi2EkDBFqO3gdHLxUzDB9IkdexBllydRD49ihO3Ckz7B/a31utZnafkkGyiXnyclxhgB0MMUKKMTLkmGCKV5hhF3vYxxwHOMRrvMERjnGCU7zFO7zHB3zEJ3zGF3zFN5zhHBe4xHf8wE/8wm8w/MEVimTYKv44XR9MSCsUjVoeHE3vjQoNsSZ4mmxZmVWPjSz7jlou6/0qKOWEJdKMtCe793/hQfqxa6XWZHMXFl56RS4TvPXSaDeoy0zUUZB109KstDK8lHo5q6Qi1hcOnqkImubPS6aqRq7mlnaEWabub4iYblba3SRmgldS0+FWdhNtt04F14JUaqkl7tcpOpJtErvNt3Bd9HRT5JWxK25Ldjvp6br4hzfFiIdSmlzTg2fSUzNrLd1LE1ynxq4OVaVoKLjzJ60UPtj1RKzHzsbjly6inVnFBS2MucviPncU7Rr7lfTxRepDs1A2j3ZHRc7PuzFYSfE3ZOd4kjwBy227hA==) format("woff");font-weight:400;font-style:normal}.vjs-icon-play,.video-js .vjs-play-control .vjs-icon-placeholder,.video-js .vjs-big-play-button .vjs-icon-placeholder:before{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-play:before,.video-js .vjs-play-control .vjs-icon-placeholder:before,.video-js .vjs-big-play-button .vjs-icon-placeholder:before{content:""}.vjs-icon-play-circle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-play-circle:before{content:""}.vjs-icon-pause,.video-js .vjs-play-control.vjs-playing .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-pause:before,.video-js .vjs-play-control.vjs-playing .vjs-icon-placeholder:before{content:""}.vjs-icon-volume-mute,.video-js .vjs-mute-control.vjs-vol-0 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-volume-mute:before,.video-js .vjs-mute-control.vjs-vol-0 .vjs-icon-placeholder:before{content:""}.vjs-icon-volume-low,.video-js .vjs-mute-control.vjs-vol-1 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-volume-low:before,.video-js .vjs-mute-control.vjs-vol-1 .vjs-icon-placeholder:before{content:""}.vjs-icon-volume-mid,.video-js .vjs-mute-control.vjs-vol-2 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-volume-mid:before,.video-js .vjs-mute-control.vjs-vol-2 .vjs-icon-placeholder:before{content:""}.vjs-icon-volume-high,.video-js .vjs-mute-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-volume-high:before,.video-js .vjs-mute-control .vjs-icon-placeholder:before{content:""}.vjs-icon-fullscreen-enter,.video-js .vjs-fullscreen-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-fullscreen-enter:before,.video-js .vjs-fullscreen-control .vjs-icon-placeholder:before{content:""}.vjs-icon-fullscreen-exit,.video-js.vjs-fullscreen .vjs-fullscreen-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-fullscreen-exit:before,.video-js.vjs-fullscreen .vjs-fullscreen-control .vjs-icon-placeholder:before{content:""}.vjs-icon-spinner{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-spinner:before{content:""}.vjs-icon-subtitles,.video-js .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-GB) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-IE) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-AU) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-NZ) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js .vjs-subtitles-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-subtitles:before,.video-js .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-GB) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-IE) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-AU) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-NZ) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js .vjs-subtitles-button .vjs-icon-placeholder:before{content:""}.vjs-icon-captions,.video-js:lang(en) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js:lang(fr-CA) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js .vjs-captions-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-captions:before,.video-js:lang(en) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js:lang(fr-CA) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js .vjs-captions-button .vjs-icon-placeholder:before{content:""}.vjs-icon-hd{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-hd:before{content:""}.vjs-icon-chapters,.video-js .vjs-chapters-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-chapters:before,.video-js .vjs-chapters-button .vjs-icon-placeholder:before{content:""}.vjs-icon-downloading{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-downloading:before{content:""}.vjs-icon-file-download{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download:before{content:""}.vjs-icon-file-download-done{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download-done:before{content:""}.vjs-icon-file-download-off{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download-off:before{content:""}.vjs-icon-share{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-share:before{content:""}.vjs-icon-cog{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-cog:before{content:""}.vjs-icon-square{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-square:before{content:""}.vjs-icon-circle,.vjs-seek-to-live-control .vjs-icon-placeholder,.video-js .vjs-volume-level,.video-js .vjs-play-progress{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-circle:before,.vjs-seek-to-live-control .vjs-icon-placeholder:before,.video-js .vjs-volume-level:before,.video-js .vjs-play-progress:before{content:""}.vjs-icon-circle-outline{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-circle-outline:before{content:""}.vjs-icon-circle-inner-circle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-circle-inner-circle:before{content:""}.vjs-icon-cancel,.video-js .vjs-control.vjs-close-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-cancel:before,.video-js .vjs-control.vjs-close-button .vjs-icon-placeholder:before{content:""}.vjs-icon-repeat{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-repeat:before{content:""}.vjs-icon-replay,.video-js .vjs-play-control.vjs-ended .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-replay:before,.video-js .vjs-play-control.vjs-ended .vjs-icon-placeholder:before{content:""}.vjs-icon-replay-5,.video-js .vjs-skip-backward-5 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-replay-5:before,.video-js .vjs-skip-backward-5 .vjs-icon-placeholder:before{content:""}.vjs-icon-replay-10,.video-js .vjs-skip-backward-10 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-replay-10:before,.video-js .vjs-skip-backward-10 .vjs-icon-placeholder:before{content:""}.vjs-icon-replay-30,.video-js .vjs-skip-backward-30 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-replay-30:before,.video-js .vjs-skip-backward-30 .vjs-icon-placeholder:before{content:""}.vjs-icon-forward-5,.video-js .vjs-skip-forward-5 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-forward-5:before,.video-js .vjs-skip-forward-5 .vjs-icon-placeholder:before{content:""}.vjs-icon-forward-10,.video-js .vjs-skip-forward-10 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-forward-10:before,.video-js .vjs-skip-forward-10 .vjs-icon-placeholder:before{content:""}.vjs-icon-forward-30,.video-js .vjs-skip-forward-30 .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-forward-30:before,.video-js .vjs-skip-forward-30 .vjs-icon-placeholder:before{content:""}.vjs-icon-audio,.video-js .vjs-audio-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-audio:before,.video-js .vjs-audio-button .vjs-icon-placeholder:before{content:""}.vjs-icon-next-item{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-next-item:before{content:""}.vjs-icon-previous-item{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-previous-item:before{content:""}.vjs-icon-shuffle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-shuffle:before{content:""}.vjs-icon-cast{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-cast:before{content:""}.vjs-icon-picture-in-picture-enter,.video-js .vjs-picture-in-picture-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-picture-in-picture-enter:before,.video-js .vjs-picture-in-picture-control .vjs-icon-placeholder:before{content:""}.vjs-icon-picture-in-picture-exit,.video-js.vjs-picture-in-picture .vjs-picture-in-picture-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-picture-in-picture-exit:before,.video-js.vjs-picture-in-picture .vjs-picture-in-picture-control .vjs-icon-placeholder:before{content:""}.vjs-icon-facebook{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-facebook:before{content:""}.vjs-icon-linkedin{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-linkedin:before{content:""}.vjs-icon-twitter{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-twitter:before{content:""}.vjs-icon-tumblr{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-tumblr:before{content:""}.vjs-icon-pinterest{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-pinterest:before{content:""}.vjs-icon-audio-description,.video-js .vjs-descriptions-button .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-audio-description:before,.video-js .vjs-descriptions-button .vjs-icon-placeholder:before{content:""}.video-js{display:inline-block;vertical-align:top;box-sizing:border-box;color:#fff;background-color:#000;position:relative;padding:0;font-size:10px;line-height:1;font-weight:400;font-style:normal;font-family:Arial,Helvetica,sans-serif;word-break:initial}.video-js:-moz-full-screen{position:absolute}.video-js:-webkit-full-screen{width:100%!important;height:100%!important}.video-js[tabindex="-1"]{outline:none}.video-js *,.video-js *:before,.video-js *:after{box-sizing:inherit}.video-js ul{font-family:inherit;font-size:inherit;line-height:inherit;list-style-position:outside;margin:0}.video-js.vjs-fluid,.video-js.vjs-16-9,.video-js.vjs-4-3,.video-js.vjs-9-16,.video-js.vjs-1-1{width:100%;max-width:100%}.video-js.vjs-fluid:not(.vjs-audio-only-mode),.video-js.vjs-16-9:not(.vjs-audio-only-mode),.video-js.vjs-4-3:not(.vjs-audio-only-mode),.video-js.vjs-9-16:not(.vjs-audio-only-mode),.video-js.vjs-1-1:not(.vjs-audio-only-mode){height:0}.video-js.vjs-16-9:not(.vjs-audio-only-mode){padding-top:56.25%}.video-js.vjs-4-3:not(.vjs-audio-only-mode){padding-top:75%}.video-js.vjs-9-16:not(.vjs-audio-only-mode){padding-top:177.7777777778%}.video-js.vjs-1-1:not(.vjs-audio-only-mode){padding-top:100%}.video-js.vjs-fill:not(.vjs-audio-only-mode){width:100%;height:100%}.video-js .vjs-tech{position:absolute;top:0;left:0;width:100%;height:100%}.video-js.vjs-audio-only-mode .vjs-tech{display:none}body.vjs-full-window,body.vjs-pip-window{padding:0;margin:0;height:100%}.vjs-full-window .video-js.vjs-fullscreen,body.vjs-pip-window .video-js{position:fixed;overflow:hidden;z-index:1000;inset:0}.video-js.vjs-fullscreen:not(.vjs-ios-native-fs),body.vjs-pip-window .video-js{width:100%!important;height:100%!important;padding-top:0!important;display:block}.video-js.vjs-fullscreen.vjs-user-inactive{cursor:none}.vjs-pip-container .vjs-pip-text{position:absolute;bottom:10%;font-size:2em;background-color:#000000b3;padding:.5em;text-align:center;width:100%}.vjs-layout-tiny.vjs-pip-container .vjs-pip-text,.vjs-layout-x-small.vjs-pip-container .vjs-pip-text,.vjs-layout-small.vjs-pip-container .vjs-pip-text{bottom:0;font-size:1.4em}.vjs-hidden{display:none!important}.vjs-disabled{opacity:.5;cursor:default}.video-js .vjs-offscreen{height:1px;left:-9999px;position:absolute;top:0;width:1px}.vjs-lock-showing{display:block!important;opacity:1!important;visibility:visible!important}.vjs-no-js{padding:20px;color:#fff;background-color:#000;font-size:18px;font-family:Arial,Helvetica,sans-serif;text-align:center;width:300px;height:150px;margin:0 auto}.vjs-no-js a,.vjs-no-js a:visited{color:#66a8cc}.video-js .vjs-big-play-button{font-size:3em;line-height:1.5em;height:1.63332em;width:3em;display:block;position:absolute;top:50%;left:50%;padding:0;margin-top:-.81666em;margin-left:-1.5em;cursor:pointer;opacity:1;border:.06666em solid #fff;background-color:#2b333f;background-color:#2b333fb3;border-radius:.3em;transition:all .4s}.vjs-big-play-button .vjs-svg-icon{width:1em;height:1em;position:absolute;top:50%;left:50%;line-height:1;transform:translate(-50%,-50%)}.video-js:hover .vjs-big-play-button,.video-js .vjs-big-play-button:focus{border-color:#fff;background-color:#73859f;background-color:#73859f80;transition:all 0s}.vjs-controls-disabled .vjs-big-play-button,.vjs-has-started .vjs-big-play-button,.vjs-using-native-controls .vjs-big-play-button,.vjs-error .vjs-big-play-button{display:none}.vjs-has-started.vjs-paused.vjs-show-big-play-button-on-pause:not(.vjs-seeking,.vjs-scrubbing,.vjs-error) .vjs-big-play-button{display:block}.video-js button{background:none;border:none;color:inherit;display:inline-block;font-size:inherit;line-height:inherit;text-transform:none;text-decoration:none;transition:none;-webkit-appearance:none;-moz-appearance:none;appearance:none}.video-js.vjs-spatial-navigation-enabled .vjs-button:focus{outline:.0625em solid white;box-shadow:none}.vjs-control .vjs-button{width:100%;height:100%}.video-js .vjs-control.vjs-close-button{cursor:pointer;height:3em;position:absolute;right:0;top:.5em;z-index:2}.video-js .vjs-modal-dialog{background:#000c;background:linear-gradient(180deg,#000c,#fff0);overflow:auto}.video-js .vjs-modal-dialog>*{box-sizing:border-box}.vjs-modal-dialog .vjs-modal-dialog-content{font-size:1.2em;line-height:1.5;padding:20px 24px;z-index:1}.vjs-menu-button{cursor:pointer}.vjs-menu-button.vjs-disabled{cursor:default}.vjs-workinghover .vjs-menu-button.vjs-disabled:hover .vjs-menu{display:none}.vjs-menu .vjs-menu-content{display:block;padding:0;margin:0;font-family:Arial,Helvetica,sans-serif;overflow:auto}.vjs-menu .vjs-menu-content>*{box-sizing:border-box}.vjs-scrubbing .vjs-control.vjs-menu-button:hover .vjs-menu{display:none}.vjs-menu li{display:flex;justify-content:center;list-style:none;margin:0;padding:.2em 0;line-height:1.4em;font-size:1.2em;text-align:center;text-transform:lowercase}.vjs-menu li.vjs-menu-item:focus,.vjs-menu li.vjs-menu-item:hover,.js-focus-visible .vjs-menu li.vjs-menu-item:hover{background-color:#73859f;background-color:#73859f80}.vjs-menu li.vjs-selected,.vjs-menu li.vjs-selected:focus,.vjs-menu li.vjs-selected:hover,.js-focus-visible .vjs-menu li.vjs-selected:hover{background-color:#fff;color:#2b333f}.vjs-menu li.vjs-selected .vjs-svg-icon,.vjs-menu li.vjs-selected:focus .vjs-svg-icon,.vjs-menu li.vjs-selected:hover .vjs-svg-icon,.js-focus-visible .vjs-menu li.vjs-selected:hover .vjs-svg-icon{fill:#000}.video-js .vjs-menu *:not(.vjs-selected):focus:not(:focus-visible),.js-focus-visible .vjs-menu *:not(.vjs-selected):focus:not(.focus-visible){background:none}.vjs-menu li.vjs-menu-title{text-align:center;text-transform:uppercase;font-size:1em;line-height:2em;padding:0;margin:0 0 .3em;font-weight:700;cursor:default}.vjs-menu-button-popup .vjs-menu{display:none;position:absolute;bottom:0;width:10em;left:-3em;height:0em;margin-bottom:1.5em;border-top-color:#2b333fb3}.vjs-pip-window .vjs-menu-button-popup .vjs-menu{left:unset;right:1em}.vjs-menu-button-popup .vjs-menu .vjs-menu-content{background-color:#2b333f;background-color:#2b333fb3;position:absolute;width:100%;bottom:1.5em;max-height:15em}.vjs-layout-tiny .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-x-small .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:5em}.vjs-layout-small .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:10em}.vjs-layout-medium .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:14em}.vjs-layout-large .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-x-large .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-huge .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:25em}.vjs-workinghover .vjs-menu-button-popup.vjs-hover .vjs-menu,.vjs-menu-button-popup .vjs-menu.vjs-lock-showing{display:block}.video-js .vjs-menu-button-inline{transition:all .4s;overflow:hidden}.video-js .vjs-menu-button-inline:before{width:2.222222222em}.video-js .vjs-menu-button-inline:hover,.video-js .vjs-menu-button-inline:focus,.video-js .vjs-menu-button-inline.vjs-slider-active{width:12em}.vjs-menu-button-inline .vjs-menu{opacity:0;height:100%;width:auto;position:absolute;left:4em;top:0;padding:0;margin:0;transition:all .4s}.vjs-menu-button-inline:hover .vjs-menu,.vjs-menu-button-inline:focus .vjs-menu,.vjs-menu-button-inline.vjs-slider-active .vjs-menu{display:block;opacity:1}.vjs-menu-button-inline .vjs-menu-content{width:auto;height:100%;margin:0;overflow:hidden}.video-js .vjs-control-bar{display:none;width:100%;position:absolute;bottom:0;left:0;right:0;height:3em;background-color:#2b333f;background-color:#2b333fb3}.video-js.vjs-spatial-navigation-enabled .vjs-control-bar{gap:1px}.video-js:not(.vjs-controls-disabled,.vjs-using-native-controls,.vjs-error) .vjs-control-bar.vjs-lock-showing{display:flex!important}.vjs-has-started .vjs-control-bar,.vjs-audio-only-mode .vjs-control-bar{display:flex;visibility:visible;opacity:1;transition:visibility .1s,opacity .1s}.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar{visibility:visible;opacity:0;pointer-events:none;transition:visibility 1s,opacity 1s}.vjs-controls-disabled .vjs-control-bar,.vjs-using-native-controls .vjs-control-bar,.vjs-error .vjs-control-bar{display:none!important}.vjs-audio.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar,.vjs-audio-only-mode.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar{opacity:1;visibility:visible;pointer-events:auto}.video-js .vjs-control{position:relative;text-align:center;margin:0;padding:0;height:100%;width:4em;flex:none}.video-js .vjs-control.vjs-visible-text{width:auto;padding-left:1em;padding-right:1em}.vjs-button>.vjs-icon-placeholder:before{font-size:1.8em;line-height:1.67}.vjs-button>.vjs-icon-placeholder{display:block}.vjs-button>.vjs-svg-icon{display:inline-block}.video-js .vjs-control:focus:before,.video-js .vjs-control:hover:before,.video-js .vjs-control:focus{text-shadow:0em 0em 1em white}.video-js *:not(.vjs-visible-text)>.vjs-control-text{border:0;clip:rect(0 0 0 0);height:1px;overflow:hidden;padding:0;position:absolute;width:1px}.video-js .vjs-custom-control-spacer{display:none}.video-js .vjs-progress-control{cursor:pointer;flex:auto;display:flex;align-items:center;min-width:4em;touch-action:none}.video-js .vjs-progress-control.disabled{cursor:default}.vjs-live .vjs-progress-control{display:none}.vjs-liveui .vjs-progress-control{display:flex;align-items:center}.video-js .vjs-progress-holder{flex:auto;transition:all .2s;height:.3em}.video-js .vjs-progress-control .vjs-progress-holder{margin:0 10px}.video-js .vjs-progress-control:hover .vjs-progress-holder,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-progress-holder{font-size:1.6666666667em}.video-js .vjs-progress-control:hover .vjs-progress-holder.disabled{font-size:1em}.video-js .vjs-progress-holder .vjs-play-progress,.video-js .vjs-progress-holder .vjs-load-progress,.video-js .vjs-progress-holder .vjs-load-progress div{position:absolute;display:block;height:100%;margin:0;padding:0;width:0}.video-js .vjs-play-progress{background-color:#fff}.video-js .vjs-play-progress:before{font-size:.9em;position:absolute;right:-.5em;line-height:.35em;z-index:1}.vjs-svg-icons-enabled .vjs-play-progress:before{content:none!important}.vjs-play-progress .vjs-svg-icon{position:absolute;top:-.35em;right:-.4em;width:.9em;height:.9em;pointer-events:none;line-height:.15em;z-index:1}.video-js .vjs-load-progress{background:#73859f80}.video-js .vjs-load-progress div{background:#73859fbf}.video-js .vjs-time-tooltip{background-color:#fff;background-color:#fffc;border-radius:.3em;color:#000;float:right;font-family:Arial,Helvetica,sans-serif;font-size:1em;padding:6px 8px 8px;pointer-events:none;position:absolute;top:-3.4em;visibility:hidden;z-index:1}.video-js .vjs-progress-holder:focus .vjs-time-tooltip{display:none}.video-js .vjs-progress-control:hover .vjs-time-tooltip,.video-js .vjs-progress-control:hover .vjs-progress-holder:focus .vjs-time-tooltip,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-time-tooltip{display:block;font-size:.6em;visibility:visible}.video-js .vjs-progress-control.disabled:hover .vjs-time-tooltip{font-size:1em}.video-js .vjs-progress-control .vjs-mouse-display{display:none;position:absolute;width:1px;height:100%;background-color:#000;z-index:1}.video-js .vjs-progress-control:hover .vjs-mouse-display,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-mouse-display{display:block}.video-js.vjs-user-inactive .vjs-progress-control .vjs-mouse-display,.video-js.vjs-touch-enabled:not(.vjs-scrubbing) .vjs-progress-control .vjs-mouse-display{visibility:hidden;opacity:0;transition:visibility 1s,opacity 1s}.vjs-mouse-display .vjs-time-tooltip{color:#fff;background-color:#000;background-color:#000c}.video-js .vjs-slider{position:relative;cursor:pointer;padding:0;margin:0 .45em;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;background-color:#73859f;background-color:#73859f80}.video-js .vjs-slider.disabled{cursor:default}.video-js .vjs-slider:focus{text-shadow:0em 0em 1em white;box-shadow:0 0 1em #fff}.video-js.vjs-spatial-navigation-enabled .vjs-slider:focus{outline:.0625em solid white}.video-js .vjs-mute-control{cursor:pointer;flex:none}.video-js .vjs-volume-control{cursor:pointer;margin-right:1em;display:flex}.video-js .vjs-volume-control.vjs-volume-horizontal{width:5em}.video-js .vjs-volume-panel .vjs-volume-control{visibility:visible;opacity:0;width:1px;height:1px;margin-left:-1px}.video-js .vjs-volume-panel{transition:width 1s}.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control,.video-js .vjs-volume-panel:active .vjs-volume-control,.video-js .vjs-volume-panel:focus .vjs-volume-control,.video-js .vjs-volume-panel .vjs-volume-control:active,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control,.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active{visibility:visible;opacity:1;position:relative;transition:visibility .1s,opacity .1s,height .1s,width .1s,left 0s,top 0s}.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel:active .vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel:focus .vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel .vjs-volume-control:active.vjs-volume-horizontal,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active.vjs-volume-horizontal{width:5em;height:3em;margin-right:0}.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel:active .vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel:focus .vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel .vjs-volume-control:active.vjs-volume-vertical,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active.vjs-volume-vertical{left:-3.5em;transition:left 0s}.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active{width:10em;transition:width .1s}.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-mute-toggle-only{width:4em}.video-js .vjs-volume-panel .vjs-volume-control.vjs-volume-vertical{height:8em;width:3em;left:-3000em;transition:visibility 1s,opacity 1s,height 1s 1s,width 1s 1s,left 1s 1s,top 1s 1s}.video-js .vjs-volume-panel .vjs-volume-control.vjs-volume-horizontal{transition:visibility 1s,opacity 1s,height 1s 1s,width 1s,left 1s 1s,top 1s 1s}.video-js .vjs-volume-panel{display:flex}.video-js .vjs-volume-bar{margin:1.35em .45em}.vjs-volume-bar.vjs-slider-horizontal{width:5em;height:.3em}.vjs-volume-bar.vjs-slider-vertical{width:.3em;height:5em;margin:1.35em auto}.video-js .vjs-volume-level{position:absolute;bottom:0;left:0;background-color:#fff}.video-js .vjs-volume-level:before{position:absolute;font-size:.9em;z-index:1}.vjs-slider-vertical .vjs-volume-level{width:.3em}.vjs-slider-vertical .vjs-volume-level:before{top:-.5em;left:-.3em;z-index:1}.vjs-svg-icons-enabled .vjs-volume-level:before{content:none}.vjs-volume-level .vjs-svg-icon{position:absolute;width:.9em;height:.9em;pointer-events:none;z-index:1}.vjs-slider-horizontal .vjs-volume-level{height:.3em}.vjs-slider-horizontal .vjs-volume-level:before{line-height:.35em;right:-.5em}.vjs-slider-horizontal .vjs-volume-level .vjs-svg-icon{right:-.3em;transform:translateY(-50%)}.vjs-slider-vertical .vjs-volume-level .vjs-svg-icon{top:-.55em;transform:translate(-50%)}.video-js .vjs-volume-panel.vjs-volume-panel-vertical{width:4em}.vjs-volume-bar.vjs-slider-vertical .vjs-volume-level{height:100%}.vjs-volume-bar.vjs-slider-horizontal .vjs-volume-level{width:100%}.video-js .vjs-volume-vertical{width:3em;height:8em;bottom:8em;background-color:#2b333f;background-color:#2b333fb3}.video-js .vjs-volume-horizontal .vjs-menu{left:-2em}.video-js .vjs-volume-tooltip{background-color:#fff;background-color:#fffc;border-radius:.3em;color:#000;float:right;font-family:Arial,Helvetica,sans-serif;font-size:1em;padding:6px 8px 8px;pointer-events:none;position:absolute;top:-3.4em;visibility:hidden;z-index:1}.video-js .vjs-volume-control:hover .vjs-volume-tooltip,.video-js .vjs-volume-control:hover .vjs-progress-holder:focus .vjs-volume-tooltip{display:block;font-size:1em;visibility:visible}.video-js .vjs-volume-vertical:hover .vjs-volume-tooltip,.video-js .vjs-volume-vertical:hover .vjs-progress-holder:focus .vjs-volume-tooltip{left:1em;top:-12px}.video-js .vjs-volume-control.disabled:hover .vjs-volume-tooltip{font-size:1em}.video-js .vjs-volume-control .vjs-mouse-display{display:none;position:absolute;width:100%;height:1px;background-color:#000;z-index:1}.video-js .vjs-volume-horizontal .vjs-mouse-display{width:1px;height:100%}.video-js .vjs-volume-control:hover .vjs-mouse-display{display:block}.video-js.vjs-user-inactive .vjs-volume-control .vjs-mouse-display{visibility:hidden;opacity:0;transition:visibility 1s,opacity 1s}.vjs-mouse-display .vjs-volume-tooltip{color:#fff;background-color:#000;background-color:#000c}.vjs-poster{display:inline-block;vertical-align:middle;cursor:pointer;margin:0;padding:0;position:absolute;inset:0;height:100%}.vjs-has-started .vjs-poster,.vjs-using-native-controls .vjs-poster{display:none}.vjs-audio.vjs-has-started .vjs-poster,.vjs-has-started.vjs-audio-poster-mode .vjs-poster,.vjs-pip-container.vjs-has-started .vjs-poster{display:block}.vjs-poster img{width:100%;height:100%;object-fit:contain}.video-js .vjs-live-control{display:flex;align-items:flex-start;flex:auto;font-size:1em;line-height:3em}.video-js:not(.vjs-live) .vjs-live-control,.video-js.vjs-liveui .vjs-live-control{display:none}.video-js .vjs-seek-to-live-control{align-items:center;cursor:pointer;flex:none;display:inline-flex;height:100%;padding-left:.5em;padding-right:.5em;font-size:1em;line-height:3em;width:auto;min-width:4em}.video-js.vjs-live:not(.vjs-liveui) .vjs-seek-to-live-control,.video-js:not(.vjs-live) .vjs-seek-to-live-control{display:none}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge{cursor:auto}.vjs-seek-to-live-control .vjs-icon-placeholder{margin-right:.5em;color:#888}.vjs-svg-icons-enabled .vjs-seek-to-live-control{line-height:0}.vjs-seek-to-live-control .vjs-svg-icon{width:1em;height:1em;pointer-events:none;fill:#888}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge .vjs-icon-placeholder{color:red}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge .vjs-svg-icon{fill:red}.video-js .vjs-time-control{flex:none;font-size:1em;line-height:3em;min-width:2em;width:auto;padding-left:1em;padding-right:1em}.vjs-live .vjs-time-control,.vjs-live .vjs-time-divider,.video-js .vjs-current-time,.video-js .vjs-duration{display:none}.vjs-time-divider{display:none;line-height:3em}.vjs-normalise-time-controls:not(.vjs-live) .vjs-time-control{display:flex}.video-js .vjs-play-control{cursor:pointer}.video-js .vjs-play-control .vjs-icon-placeholder{flex:none}.vjs-text-track-display{position:absolute;inset:0 0 3em;pointer-events:none}.vjs-error .vjs-text-track-display{display:none}.video-js.vjs-controls-disabled .vjs-text-track-display,.video-js.vjs-user-inactive.vjs-playing .vjs-text-track-display{bottom:1em}.video-js .vjs-text-track{font-size:1.4em;text-align:center;margin-bottom:.1em}.vjs-subtitles{color:#fff}.vjs-captions{color:#fc6}.vjs-tt-cue{display:block}video::-webkit-media-text-track-display{transform:translateY(-3em)}.video-js.vjs-controls-disabled video::-webkit-media-text-track-display,.video-js.vjs-user-inactive.vjs-playing video::-webkit-media-text-track-display{transform:translateY(-1.5em)}.video-js.vjs-force-center-align-cues .vjs-text-track-cue{text-align:center!important;width:80%!important}@supports not (inset: 10px){.video-js .vjs-text-track-display>div{inset:0}}.video-js .vjs-picture-in-picture-control{cursor:pointer;flex:none}.video-js.vjs-audio-only-mode .vjs-picture-in-picture-control,.vjs-pip-window .vjs-picture-in-picture-control{display:none}.video-js .vjs-fullscreen-control{cursor:pointer;flex:none}.video-js.vjs-audio-only-mode .vjs-fullscreen-control,.vjs-pip-window .vjs-fullscreen-control{display:none}.vjs-playback-rate>.vjs-menu-button,.vjs-playback-rate .vjs-playback-rate-value{position:absolute;top:0;left:0;width:100%;height:100%}.vjs-playback-rate .vjs-playback-rate-value{pointer-events:none;font-size:1.5em;line-height:2;text-align:center}.vjs-playback-rate .vjs-menu{width:4em;left:0}.vjs-error .vjs-error-display .vjs-modal-dialog-content{font-size:1.4em;text-align:center}.vjs-loading-spinner{display:none;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);opacity:.85;text-align:left;border:.6em solid rgba(43,51,63,.7);box-sizing:border-box;background-clip:padding-box;width:5em;height:5em;border-radius:50%;visibility:hidden}.vjs-seeking .vjs-loading-spinner,.vjs-waiting .vjs-loading-spinner{display:flex;justify-content:center;align-items:center;animation:vjs-spinner-show 0s linear .3s forwards}.vjs-error .vjs-loading-spinner{display:none}.vjs-loading-spinner:before,.vjs-loading-spinner:after{content:"";position:absolute;box-sizing:inherit;width:inherit;height:inherit;border-radius:inherit;opacity:1;border:inherit;border-color:transparent;border-top-color:#fff}.vjs-seeking .vjs-loading-spinner:before,.vjs-seeking .vjs-loading-spinner:after,.vjs-waiting .vjs-loading-spinner:before,.vjs-waiting .vjs-loading-spinner:after{animation:vjs-spinner-spin 1.1s cubic-bezier(.6,.2,0,.8) infinite,vjs-spinner-fade 1.1s linear infinite}.vjs-seeking .vjs-loading-spinner:before,.vjs-waiting .vjs-loading-spinner:before{border-top-color:#fff}.vjs-seeking .vjs-loading-spinner:after,.vjs-waiting .vjs-loading-spinner:after{border-top-color:#fff;animation-delay:.44s}@keyframes vjs-spinner-show{to{visibility:visible}}@keyframes vjs-spinner-spin{to{transform:rotate(360deg)}}@keyframes vjs-spinner-fade{0%{border-top-color:#73859f}20%{border-top-color:#73859f}35%{border-top-color:#fff}60%{border-top-color:#73859f}to{border-top-color:#73859f}}.video-js.vjs-audio-only-mode .vjs-captions-button{display:none}.vjs-chapters-button .vjs-menu ul{width:24em}.video-js.vjs-audio-only-mode .vjs-descriptions-button{display:none}.vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-svg-icon{width:1.5em;height:1.5em}.video-js .vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-menu-item-text .vjs-icon-placeholder{vertical-align:middle;display:inline-block;margin-bottom:-.1em}.video-js .vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before{font-family:VideoJS;content:"";font-size:1.5em;line-height:inherit}.video-js.vjs-audio-only-mode .vjs-subs-caps-button{display:none}.video-js .vjs-audio-button+.vjs-menu .vjs-descriptions-menu-item .vjs-menu-item-text .vjs-icon-placeholder,.video-js .vjs-audio-button+.vjs-menu .vjs-main-desc-menu-item .vjs-menu-item-text .vjs-icon-placeholder{vertical-align:middle;display:inline-block;margin-bottom:-.1em}.video-js .vjs-audio-button+.vjs-menu .vjs-descriptions-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before,.video-js .vjs-audio-button+.vjs-menu .vjs-main-desc-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before{font-family:VideoJS;content:" ";font-size:1.5em;line-height:inherit}.video-js.vjs-layout-small .vjs-current-time,.video-js.vjs-layout-small .vjs-time-divider,.video-js.vjs-layout-small .vjs-duration,.video-js.vjs-layout-small .vjs-remaining-time,.video-js.vjs-layout-small .vjs-playback-rate,.video-js.vjs-layout-small .vjs-volume-control,.video-js.vjs-layout-x-small .vjs-current-time,.video-js.vjs-layout-x-small .vjs-time-divider,.video-js.vjs-layout-x-small .vjs-duration,.video-js.vjs-layout-x-small .vjs-remaining-time,.video-js.vjs-layout-x-small .vjs-playback-rate,.video-js.vjs-layout-x-small .vjs-volume-control,.video-js.vjs-layout-tiny .vjs-current-time,.video-js.vjs-layout-tiny .vjs-time-divider,.video-js.vjs-layout-tiny .vjs-duration,.video-js.vjs-layout-tiny .vjs-remaining-time,.video-js.vjs-layout-tiny .vjs-playback-rate,.video-js.vjs-layout-tiny .vjs-volume-control{display:none}.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal:hover,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal:hover,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal:hover,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover{width:auto;width:initial}.video-js.vjs-layout-x-small .vjs-progress-control,.video-js.vjs-layout-tiny .vjs-progress-control{display:none}.video-js.vjs-layout-x-small .vjs-custom-control-spacer{flex:auto;display:block}.vjs-modal-dialog.vjs-text-track-settings{background-color:#2b333f;background-color:#2b333fbf;color:#fff;height:70%}.vjs-spatial-navigation-enabled .vjs-modal-dialog.vjs-text-track-settings{height:80%}.vjs-error .vjs-text-track-settings{display:none}.vjs-text-track-settings .vjs-modal-dialog-content{display:table}.vjs-text-track-settings .vjs-track-settings-colors,.vjs-text-track-settings .vjs-track-settings-font,.vjs-text-track-settings .vjs-track-settings-controls{display:table-cell}.vjs-text-track-settings .vjs-track-settings-controls{text-align:right;vertical-align:bottom}@supports (display: grid){.vjs-text-track-settings .vjs-modal-dialog-content{display:grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr;padding:20px 24px 0}.vjs-track-settings-controls .vjs-default-button{margin-bottom:20px}.vjs-text-track-settings .vjs-track-settings-controls{grid-column:1/-1}.vjs-layout-small .vjs-text-track-settings .vjs-modal-dialog-content,.vjs-layout-x-small .vjs-text-track-settings .vjs-modal-dialog-content,.vjs-layout-tiny .vjs-text-track-settings .vjs-modal-dialog-content{grid-template-columns:1fr}}.vjs-text-track-settings select{font-size:inherit}.vjs-track-setting>select{margin-right:1em;margin-bottom:.5em}.vjs-text-track-settings fieldset{margin:10px;border:none}.vjs-text-track-settings fieldset span{display:inline-block;padding:0 .6em .8em}.vjs-text-track-settings fieldset span>select{max-width:7.3em}.vjs-text-track-settings legend{color:#fff;font-weight:700;font-size:1.2em}.vjs-text-track-settings .vjs-label{margin:0 .5em .5em 0}.vjs-track-settings-controls button:focus,.vjs-track-settings-controls button:active{outline-style:solid;outline-width:medium;background-image:linear-gradient(0deg,#fff 88%,#73859f)}.vjs-track-settings-controls button:hover{color:#2b333fbf}.vjs-track-settings-controls button{background-color:#fff;background-image:linear-gradient(-180deg,#fff 88%,#73859f);color:#2b333f;cursor:pointer;border-radius:2px}.vjs-track-settings-controls .vjs-default-button{margin-right:1em}.vjs-title-bar{background:#000000e6;background:linear-gradient(180deg,#000000e6,#000000b3 60%,#0000);font-size:1.2em;line-height:1.5;transition:opacity .1s;padding:.666em 1.333em 4em;pointer-events:none;position:absolute;top:0;width:100%}.vjs-error .vjs-title-bar{display:none}.vjs-title-bar-title,.vjs-title-bar-description{margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vjs-title-bar-title{font-weight:700;margin-bottom:.333em}.vjs-playing.vjs-user-inactive .vjs-title-bar{opacity:0;transition:opacity 1s}.video-js .vjs-skip-forward-5,.video-js .vjs-skip-forward-10,.video-js .vjs-skip-forward-30,.video-js .vjs-skip-backward-5,.video-js .vjs-skip-backward-10,.video-js .vjs-skip-backward-30{cursor:pointer}.video-js .vjs-transient-button{position:absolute;height:3em;display:flex;align-items:center;justify-content:center;background-color:#32323280;cursor:pointer;opacity:1;transition:opacity 1s}.video-js:not(.vjs-has-started) .vjs-transient-button{display:none}.video-js.not-hover .vjs-transient-button:not(.force-display),.video-js.vjs-user-inactive .vjs-transient-button:not(.force-display){opacity:0}.video-js .vjs-transient-button span{padding:0 .5em}.video-js .vjs-transient-button.vjs-left{left:1em}.video-js .vjs-transient-button.vjs-right{right:1em}.video-js .vjs-transient-button.vjs-top{top:1em}.video-js .vjs-transient-button.vjs-near-top{top:4em}.video-js .vjs-transient-button.vjs-bottom{bottom:4em}.video-js .vjs-transient-button:hover{background-color:#323232e6}@media print{.video-js>*:not(.vjs-tech):not(.vjs-poster){visibility:hidden}}.vjs-resize-manager{position:absolute;top:0;left:0;width:100%;height:100%;border:none;z-index:-1000}.js-focus-visible .video-js *:focus:not(.focus-visible){outline:none}.video-js *:focus:not(:focus-visible){outline:none} diff --git a/backend/web/dist/assets/index-jMGU1_s9.js b/backend/web/dist/assets/index-jMGU1_s9.js new file mode 100644 index 0000000..922d688 --- /dev/null +++ b/backend/web/dist/assets/index-jMGU1_s9.js @@ -0,0 +1,332 @@ +function aI(s,e){for(var t=0;ti[n]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(n){if(n.ep)return;n.ep=!0;const r=t(n);fetch(n.href,r)}})();var Gm=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Cc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function oI(s){if(Object.prototype.hasOwnProperty.call(s,"__esModule"))return s;var e=s.default;if(typeof e=="function"){var t=function i(){var n=!1;try{n=this instanceof i}catch{}return n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(i){var n=Object.getOwnPropertyDescriptor(s,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return s[i]}})}),t}var ty={exports:{}},Nd={};var z_;function lI(){if(z_)return Nd;z_=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,n,r){var o=null;if(r!==void 0&&(o=""+r),n.key!==void 0&&(o=""+n.key),"key"in n){r={};for(var u in n)u!=="key"&&(r[u]=n[u])}else r=n;return n=r.ref,{$$typeof:s,type:i,key:o,ref:n!==void 0?n:null,props:r}}return Nd.Fragment=e,Nd.jsx=t,Nd.jsxs=t,Nd}var q_;function uI(){return q_||(q_=1,ty.exports=lI()),ty.exports}var v=uI(),iy={exports:{}},Qt={};var K_;function cI(){if(K_)return Qt;K_=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.consumer"),o=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),g=Symbol.iterator;function y($){return $===null||typeof $!="object"?null:($=g&&$[g]||$["@@iterator"],typeof $=="function"?$:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,w={};function D($,ee,le){this.props=$,this.context=ee,this.refs=w,this.updater=le||x}D.prototype.isReactComponent={},D.prototype.setState=function($,ee){if(typeof $!="object"&&typeof $!="function"&&$!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,$,ee,"setState")},D.prototype.forceUpdate=function($){this.updater.enqueueForceUpdate(this,$,"forceUpdate")};function I(){}I.prototype=D.prototype;function L($,ee,le){this.props=$,this.context=ee,this.refs=w,this.updater=le||x}var B=L.prototype=new I;B.constructor=L,_(B,D.prototype),B.isPureReactComponent=!0;var j=Array.isArray;function V(){}var M={H:null,A:null,T:null,S:null},z=Object.prototype.hasOwnProperty;function O($,ee,le){var be=le.ref;return{$$typeof:s,type:$,key:ee,ref:be!==void 0?be:null,props:le}}function N($,ee){return O($.type,ee,$.props)}function q($){return typeof $=="object"&&$!==null&&$.$$typeof===s}function Q($){var ee={"=":"=0",":":"=2"};return"$"+$.replace(/[=:]/g,function(le){return ee[le]})}var Y=/\/+/g;function re($,ee){return typeof $=="object"&&$!==null&&$.key!=null?Q(""+$.key):ee.toString(36)}function Z($){switch($.status){case"fulfilled":return $.value;case"rejected":throw $.reason;default:switch(typeof $.status=="string"?$.then(V,V):($.status="pending",$.then(function(ee){$.status==="pending"&&($.status="fulfilled",$.value=ee)},function(ee){$.status==="pending"&&($.status="rejected",$.reason=ee)})),$.status){case"fulfilled":return $.value;case"rejected":throw $.reason}}throw $}function H($,ee,le,be,fe){var _e=typeof $;(_e==="undefined"||_e==="boolean")&&($=null);var Me=!1;if($===null)Me=!0;else switch(_e){case"bigint":case"string":case"number":Me=!0;break;case"object":switch($.$$typeof){case s:case e:Me=!0;break;case f:return Me=$._init,H(Me($._payload),ee,le,be,fe)}}if(Me)return fe=fe($),Me=be===""?"."+re($,0):be,j(fe)?(le="",Me!=null&&(le=Me.replace(Y,"$&/")+"/"),H(fe,ee,le,"",function(lt){return lt})):fe!=null&&(q(fe)&&(fe=N(fe,le+(fe.key==null||$&&$.key===fe.key?"":(""+fe.key).replace(Y,"$&/")+"/")+Me)),ee.push(fe)),1;Me=0;var et=be===""?".":be+":";if(j($))for(var Ge=0;Ge<$.length;Ge++)be=$[Ge],_e=et+re(be,Ge),Me+=H(be,ee,le,_e,fe);else if(Ge=y($),typeof Ge=="function")for($=Ge.call($),Ge=0;!(be=$.next()).done;)be=be.value,_e=et+re(be,Ge++),Me+=H(be,ee,le,_e,fe);else if(_e==="object"){if(typeof $.then=="function")return H(Z($),ee,le,be,fe);throw ee=String($),Error("Objects are not valid as a React child (found: "+(ee==="[object Object]"?"object with keys {"+Object.keys($).join(", ")+"}":ee)+"). If you meant to render a collection of children, use an array instead.")}return Me}function K($,ee,le){if($==null)return $;var be=[],fe=0;return H($,be,"","",function(_e){return ee.call(le,_e,fe++)}),be}function ie($){if($._status===-1){var ee=$._result;ee=ee(),ee.then(function(le){($._status===0||$._status===-1)&&($._status=1,$._result=le)},function(le){($._status===0||$._status===-1)&&($._status=2,$._result=le)}),$._status===-1&&($._status=0,$._result=ee)}if($._status===1)return $._result.default;throw $._result}var te=typeof reportError=="function"?reportError:function($){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var ee=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof $=="object"&&$!==null&&typeof $.message=="string"?String($.message):String($),error:$});if(!window.dispatchEvent(ee))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",$);return}console.error($)},ne={map:K,forEach:function($,ee,le){K($,function(){ee.apply(this,arguments)},le)},count:function($){var ee=0;return K($,function(){ee++}),ee},toArray:function($){return K($,function(ee){return ee})||[]},only:function($){if(!q($))throw Error("React.Children.only expected to receive a single React element child.");return $}};return Qt.Activity=p,Qt.Children=ne,Qt.Component=D,Qt.Fragment=t,Qt.Profiler=n,Qt.PureComponent=L,Qt.StrictMode=i,Qt.Suspense=c,Qt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=M,Qt.__COMPILER_RUNTIME={__proto__:null,c:function($){return M.H.useMemoCache($)}},Qt.cache=function($){return function(){return $.apply(null,arguments)}},Qt.cacheSignal=function(){return null},Qt.cloneElement=function($,ee,le){if($==null)throw Error("The argument must be a React element, but you passed "+$+".");var be=_({},$.props),fe=$.key;if(ee!=null)for(_e in ee.key!==void 0&&(fe=""+ee.key),ee)!z.call(ee,_e)||_e==="key"||_e==="__self"||_e==="__source"||_e==="ref"&&ee.ref===void 0||(be[_e]=ee[_e]);var _e=arguments.length-2;if(_e===1)be.children=le;else if(1<_e){for(var Me=Array(_e),et=0;et<_e;et++)Me[et]=arguments[et+2];be.children=Me}return O($.type,fe,be)},Qt.createContext=function($){return $={$$typeof:o,_currentValue:$,_currentValue2:$,_threadCount:0,Provider:null,Consumer:null},$.Provider=$,$.Consumer={$$typeof:r,_context:$},$},Qt.createElement=function($,ee,le){var be,fe={},_e=null;if(ee!=null)for(be in ee.key!==void 0&&(_e=""+ee.key),ee)z.call(ee,be)&&be!=="key"&&be!=="__self"&&be!=="__source"&&(fe[be]=ee[be]);var Me=arguments.length-2;if(Me===1)fe.children=le;else if(1>>1,ne=H[te];if(0>>1;te<$;){var ee=2*(te+1)-1,le=H[ee],be=ee+1,fe=H[be];if(0>n(le,ie))ben(fe,le)?(H[te]=fe,H[be]=ie,te=be):(H[te]=le,H[ee]=ie,te=ee);else if(ben(fe,ie))H[te]=fe,H[be]=ie,te=be;else break e}}return K}function n(H,K){var ie=H.sortIndex-K.sortIndex;return ie!==0?ie:H.id-K.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var r=performance;s.unstable_now=function(){return r.now()}}else{var o=Date,u=o.now();s.unstable_now=function(){return o.now()-u}}var c=[],d=[],f=1,p=null,g=3,y=!1,x=!1,_=!1,w=!1,D=typeof setTimeout=="function"?setTimeout:null,I=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;function B(H){for(var K=t(d);K!==null;){if(K.callback===null)i(d);else if(K.startTime<=H)i(d),K.sortIndex=K.expirationTime,e(c,K);else break;K=t(d)}}function j(H){if(_=!1,B(H),!x)if(t(c)!==null)x=!0,V||(V=!0,Q());else{var K=t(d);K!==null&&Z(j,K.startTime-H)}}var V=!1,M=-1,z=5,O=-1;function N(){return w?!0:!(s.unstable_now()-OH&&N());){var te=p.callback;if(typeof te=="function"){p.callback=null,g=p.priorityLevel;var ne=te(p.expirationTime<=H);if(H=s.unstable_now(),typeof ne=="function"){p.callback=ne,B(H),K=!0;break t}p===t(c)&&i(c),B(H)}else i(c);p=t(c)}if(p!==null)K=!0;else{var $=t(d);$!==null&&Z(j,$.startTime-H),K=!1}}break e}finally{p=null,g=ie,y=!1}K=void 0}}finally{K?Q():V=!1}}}var Q;if(typeof L=="function")Q=function(){L(q)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,re=Y.port2;Y.port1.onmessage=q,Q=function(){re.postMessage(null)}}else Q=function(){D(q,0)};function Z(H,K){M=D(function(){H(s.unstable_now())},K)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(H){H.callback=null},s.unstable_forceFrameRate=function(H){0>H||125te?(H.sortIndex=ie,e(d,H),t(c)===null&&H===t(d)&&(_?(I(M),M=-1):_=!0,Z(j,ie-te))):(H.sortIndex=ne,e(c,H),x||y||(x=!0,V||(V=!0,Q()))),H},s.unstable_shouldYield=N,s.unstable_wrapCallback=function(H){var K=g;return function(){var ie=g;g=K;try{return H.apply(this,arguments)}finally{g=ie}}}})(ry)),ry}var Q_;function hI(){return Q_||(Q_=1,ny.exports=dI()),ny.exports}var ay={exports:{}},nn={};var Z_;function fI(){if(Z_)return nn;Z_=1;var s=kp();function e(c){var d="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),ay.exports=fI(),ay.exports}var eS;function mI(){if(eS)return Od;eS=1;var s=hI(),e=kp(),t=Fw();function i(a){var l="https://react.dev/errors/"+a;if(1ne||(a.current=te[ne],te[ne]=null,ne--)}function le(a,l){ne++,te[ne]=a.current,a.current=l}var be=$(null),fe=$(null),_e=$(null),Me=$(null);function et(a,l){switch(le(_e,l),le(fe,a),le(be,null),l.nodeType){case 9:case 11:a=(a=l.documentElement)&&(a=a.namespaceURI)?m_(a):0;break;default:if(a=l.tagName,l=l.namespaceURI)l=m_(l),a=p_(l,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}ee(be),le(be,a)}function Ge(){ee(be),ee(fe),ee(_e)}function lt(a){a.memoizedState!==null&&le(Me,a);var l=be.current,h=p_(l,a.type);l!==h&&(le(fe,a),le(be,h))}function At(a){fe.current===a&&(ee(be),ee(fe)),Me.current===a&&(ee(Me),Dd._currentValue=ie)}var mt,Vt;function Re(a){if(mt===void 0)try{throw Error()}catch(h){var l=h.stack.trim().match(/\n( *(at )?)/);mt=l&&l[1]||"",Vt=-1)":-1T||de[m]!==De[T]){var Ve=` +`+de[m].replace(" at new "," at ");return a.displayName&&Ve.includes("")&&(Ve=Ve.replace("",a.displayName)),Ve}while(1<=m&&0<=T);break}}}finally{dt=!1,Error.prepareStackTrace=h}return(h=a?a.displayName||a.name:"")?Re(h):""}function tt(a,l){switch(a.tag){case 26:case 27:case 5:return Re(a.type);case 16:return Re("Lazy");case 13:return a.child!==l&&l!==null?Re("Suspense Fallback"):Re("Suspense");case 19:return Re("SuspenseList");case 0:case 15:return He(a.type,!1);case 11:return He(a.type.render,!1);case 1:return He(a.type,!0);case 31:return Re("Activity");default:return""}}function nt(a){try{var l="",h=null;do l+=tt(a,h),h=a,a=a.return;while(a);return l}catch(m){return` +Error generating stack: `+m.message+` +`+m.stack}}var ot=Object.prototype.hasOwnProperty,Ke=s.unstable_scheduleCallback,pt=s.unstable_cancelCallback,yt=s.unstable_shouldYield,Gt=s.unstable_requestPaint,Ut=s.unstable_now,ai=s.unstable_getCurrentPriorityLevel,Zt=s.unstable_ImmediatePriority,$e=s.unstable_UserBlockingPriority,ct=s.unstable_NormalPriority,it=s.unstable_LowPriority,Tt=s.unstable_IdlePriority,Wt=s.log,Xe=s.unstable_setDisableYieldValue,Ot=null,kt=null;function Xt(a){if(typeof Wt=="function"&&Xe(a),kt&&typeof kt.setStrictMode=="function")try{kt.setStrictMode(Ot,a)}catch{}}var ni=Math.clz32?Math.clz32:Nt,hi=Math.log,Ai=Math.LN2;function Nt(a){return a>>>=0,a===0?32:31-(hi(a)/Ai|0)|0}var bt=256,xi=262144,bi=4194304;function G(a){var l=a&42;if(l!==0)return l;switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return a&261888;case 262144:case 524288:case 1048576:case 2097152:return a&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return a&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return a}}function W(a,l,h){var m=a.pendingLanes;if(m===0)return 0;var T=0,S=a.suspendedLanes,F=a.pingedLanes;a=a.warmLanes;var X=m&134217727;return X!==0?(m=X&~S,m!==0?T=G(m):(F&=X,F!==0?T=G(F):h||(h=X&~a,h!==0&&(T=G(h))))):(X=m&~S,X!==0?T=G(X):F!==0?T=G(F):h||(h=m&~a,h!==0&&(T=G(h)))),T===0?0:l!==0&&l!==T&&(l&S)===0&&(S=T&-T,h=l&-l,S>=h||S===32&&(h&4194048)!==0)?l:T}function oe(a,l){return(a.pendingLanes&~(a.suspendedLanes&~a.pingedLanes)&l)===0}function Ee(a,l){switch(a){case 1:case 2:case 4:case 8:case 64:return l+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ze(){var a=bi;return bi<<=1,(bi&62914560)===0&&(bi=4194304),a}function Et(a){for(var l=[],h=0;31>h;h++)l.push(a);return l}function Jt(a,l){a.pendingLanes|=l,l!==268435456&&(a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0)}function Li(a,l,h,m,T,S){var F=a.pendingLanes;a.pendingLanes=h,a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0,a.expiredLanes&=h,a.entangledLanes&=h,a.errorRecoveryDisabledLanes&=h,a.shellSuspendCounter=0;var X=a.entanglements,de=a.expirationTimes,De=a.hiddenUpdates;for(h=F&~h;0"u")return null;try{return a.activeElement||a.body}catch{return a.body}}var ms=/[\n"\\]/g;function Bs(a){return a.replace(ms,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function Jo(a,l,h,m,T,S,F,X){a.name="",F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"?a.type=F:a.removeAttribute("type"),l!=null?F==="number"?(l===0&&a.value===""||a.value!=l)&&(a.value=""+ft(l)):a.value!==""+ft(l)&&(a.value=""+ft(l)):F!=="submit"&&F!=="reset"||a.removeAttribute("value"),l!=null?ts(a,F,ft(l)):h!=null?ts(a,F,ft(h)):m!=null&&a.removeAttribute("value"),T==null&&S!=null&&(a.defaultChecked=!!S),T!=null&&(a.checked=T&&typeof T!="function"&&typeof T!="symbol"),X!=null&&typeof X!="function"&&typeof X!="symbol"&&typeof X!="boolean"?a.name=""+ft(X):a.removeAttribute("name")}function Wi(a,l,h,m,T,S,F,X){if(S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(a.type=S),l!=null||h!=null){if(!(S!=="submit"&&S!=="reset"||l!=null)){ti(a);return}h=h!=null?""+ft(h):"",l=l!=null?""+ft(l):h,X||l===a.value||(a.value=l),a.defaultValue=l}m=m??T,m=typeof m!="function"&&typeof m!="symbol"&&!!m,a.checked=X?a.checked:!!m,a.defaultChecked=!!m,F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"&&(a.name=F),ti(a)}function ts(a,l,h){l==="number"&&Js(a.ownerDocument)===a||a.defaultValue===""+h||(a.defaultValue=""+h)}function Xi(a,l,h,m){if(a=a.options,l){l={};for(var T=0;T"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),iu=!1;if(vn)try{var tl={};Object.defineProperty(tl,"passive",{get:function(){iu=!0}}),window.addEventListener("test",tl,tl),window.removeEventListener("test",tl,tl)}catch{iu=!1}var Ir=null,su=null,il=null;function Mh(){if(il)return il;var a,l=su,h=l.length,m,T="value"in Ir?Ir.value:Ir.textContent,S=T.length;for(a=0;a=ll),qh=" ",Uc=!1;function du(a,l){switch(a){case"keyup":return x0.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Kh(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var eo=!1;function b0(a,l){switch(a){case"compositionend":return Kh(l);case"keypress":return l.which!==32?null:(Uc=!0,qh);case"textInput":return a=l.data,a===qh&&Uc?null:a;default:return null}}function jc(a,l){if(eo)return a==="compositionend"||!Ja&&du(a,l)?(a=Mh(),il=su=Ir=null,eo=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1=l)return{node:h,offset:l-a};a=m}e:{for(;h;){if(h.nextSibling){h=h.nextSibling;break e}h=h.parentNode}h=void 0}h=io(h)}}function xa(a,l){return a&&l?a===l?!0:a&&a.nodeType===3?!1:l&&l.nodeType===3?xa(a,l.parentNode):"contains"in a?a.contains(l):a.compareDocumentPosition?!!(a.compareDocumentPosition(l)&16):!1:!1}function hu(a){a=a!=null&&a.ownerDocument!=null&&a.ownerDocument.defaultView!=null?a.ownerDocument.defaultView:window;for(var l=Js(a.document);l instanceof a.HTMLIFrameElement;){try{var h=typeof l.contentWindow.location.href=="string"}catch{h=!1}if(h)a=l.contentWindow;else break;l=Js(a.document)}return l}function qc(a){var l=a&&a.nodeName&&a.nodeName.toLowerCase();return l&&(l==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||l==="textarea"||a.contentEditable==="true")}var A0=vn&&"documentMode"in document&&11>=document.documentMode,so=null,Kc=null,no=null,fu=!1;function Yc(a,l,h){var m=h.window===h?h.document:h.nodeType===9?h:h.ownerDocument;fu||so==null||so!==Js(m)||(m=so,"selectionStart"in m&&qc(m)?m={start:m.selectionStart,end:m.selectionEnd}:(m=(m.ownerDocument&&m.ownerDocument.defaultView||window).getSelection(),m={anchorNode:m.anchorNode,anchorOffset:m.anchorOffset,focusNode:m.focusNode,focusOffset:m.focusOffset}),no&&Or(no,m)||(no=m,m=$f(Kc,"onSelect"),0>=F,T-=F,$n=1<<32-ni(l)+T|h<ri?(vi=Dt,Dt=null):vi=Dt.sibling;var wi=Le(Te,Dt,ke[ri],qe);if(wi===null){Dt===null&&(Dt=vi);break}a&&Dt&&wi.alternate===null&&l(Te,Dt),pe=S(wi,pe,ri),Ei===null?Pt=wi:Ei.sibling=wi,Ei=wi,Dt=vi}if(ri===ke.length)return h(Te,Dt),mi&&li(Te,ri),Pt;if(Dt===null){for(;riri?(vi=Dt,Dt=null):vi=Dt.sibling;var Lo=Le(Te,Dt,wi.value,qe);if(Lo===null){Dt===null&&(Dt=vi);break}a&&Dt&&Lo.alternate===null&&l(Te,Dt),pe=S(Lo,pe,ri),Ei===null?Pt=Lo:Ei.sibling=Lo,Ei=Lo,Dt=vi}if(wi.done)return h(Te,Dt),mi&&li(Te,ri),Pt;if(Dt===null){for(;!wi.done;ri++,wi=ke.next())wi=We(Te,wi.value,qe),wi!==null&&(pe=S(wi,pe,ri),Ei===null?Pt=wi:Ei.sibling=wi,Ei=wi);return mi&&li(Te,ri),Pt}for(Dt=m(Dt);!wi.done;ri++,wi=ke.next())wi=Be(Dt,Te,ri,wi.value,qe),wi!==null&&(a&&wi.alternate!==null&&Dt.delete(wi.key===null?ri:wi.key),pe=S(wi,pe,ri),Ei===null?Pt=wi:Ei.sibling=wi,Ei=wi);return a&&Dt.forEach(function(rI){return l(Te,rI)}),mi&&li(Te,ri),Pt}function Ui(Te,pe,ke,qe){if(typeof ke=="object"&&ke!==null&&ke.type===_&&ke.key===null&&(ke=ke.props.children),typeof ke=="object"&&ke!==null){switch(ke.$$typeof){case y:e:{for(var Pt=ke.key;pe!==null;){if(pe.key===Pt){if(Pt=ke.type,Pt===_){if(pe.tag===7){h(Te,pe.sibling),qe=T(pe,ke.props.children),qe.return=Te,Te=qe;break e}}else if(pe.elementType===Pt||typeof Pt=="object"&&Pt!==null&&Pt.$$typeof===z&&xl(Pt)===pe.type){h(Te,pe.sibling),qe=T(pe,ke.props),ad(qe,ke),qe.return=Te,Te=qe;break e}h(Te,pe);break}else l(Te,pe);pe=pe.sibling}ke.type===_?(qe=Pr(ke.props.children,Te.mode,qe,ke.key),qe.return=Te,Te=qe):(qe=td(ke.type,ke.key,ke.props,null,Te.mode,qe),ad(qe,ke),qe.return=Te,Te=qe)}return F(Te);case x:e:{for(Pt=ke.key;pe!==null;){if(pe.key===Pt)if(pe.tag===4&&pe.stateNode.containerInfo===ke.containerInfo&&pe.stateNode.implementation===ke.implementation){h(Te,pe.sibling),qe=T(pe,ke.children||[]),qe.return=Te,Te=qe;break e}else{h(Te,pe);break}else l(Te,pe);pe=pe.sibling}qe=uo(ke,Te.mode,qe),qe.return=Te,Te=qe}return F(Te);case z:return ke=xl(ke),Ui(Te,pe,ke,qe)}if(Z(ke))return St(Te,pe,ke,qe);if(Q(ke)){if(Pt=Q(ke),typeof Pt!="function")throw Error(i(150));return ke=Pt.call(ke),jt(Te,pe,ke,qe)}if(typeof ke.then=="function")return Ui(Te,pe,df(ke),qe);if(ke.$$typeof===L)return Ui(Te,pe,qt(Te,ke),qe);hf(Te,ke)}return typeof ke=="string"&&ke!==""||typeof ke=="number"||typeof ke=="bigint"?(ke=""+ke,pe!==null&&pe.tag===6?(h(Te,pe.sibling),qe=T(pe,ke),qe.return=Te,Te=qe):(h(Te,pe),qe=ml(ke,Te.mode,qe),qe.return=Te,Te=qe),F(Te)):h(Te,pe)}return function(Te,pe,ke,qe){try{rd=0;var Pt=Ui(Te,pe,ke,qe);return xu=null,Pt}catch(Dt){if(Dt===vu||Dt===uf)throw Dt;var Ei=ps(29,Dt,null,Te.mode);return Ei.lanes=qe,Ei.return=Te,Ei}}}var Tl=rT(!0),aT=rT(!1),fo=!1;function R0(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function I0(a,l){a=a.updateQueue,l.updateQueue===a&&(l.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,callbacks:null})}function mo(a){return{lane:a,tag:0,payload:null,callback:null,next:null}}function po(a,l,h){var m=a.updateQueue;if(m===null)return null;if(m=m.shared,(ki&2)!==0){var T=m.pending;return T===null?l.next=l:(l.next=T.next,T.next=l),m.pending=l,l=gu(a),nf(a,null,h),l}return pu(a,m,l,h),gu(a)}function od(a,l,h){if(l=l.updateQueue,l!==null&&(l=l.shared,(h&4194048)!==0)){var m=l.lanes;m&=a.pendingLanes,h|=m,l.lanes=h,Ci(a,h)}}function N0(a,l){var h=a.updateQueue,m=a.alternate;if(m!==null&&(m=m.updateQueue,h===m)){var T=null,S=null;if(h=h.firstBaseUpdate,h!==null){do{var F={lane:h.lane,tag:h.tag,payload:h.payload,callback:null,next:null};S===null?T=S=F:S=S.next=F,h=h.next}while(h!==null);S===null?T=S=l:S=S.next=l}else T=S=l;h={baseState:m.baseState,firstBaseUpdate:T,lastBaseUpdate:S,shared:m.shared,callbacks:m.callbacks},a.updateQueue=h;return}a=h.lastBaseUpdate,a===null?h.firstBaseUpdate=l:a.next=l,h.lastBaseUpdate=l}var O0=!1;function ld(){if(O0){var a=Fs;if(a!==null)throw a}}function ud(a,l,h,m){O0=!1;var T=a.updateQueue;fo=!1;var S=T.firstBaseUpdate,F=T.lastBaseUpdate,X=T.shared.pending;if(X!==null){T.shared.pending=null;var de=X,De=de.next;de.next=null,F===null?S=De:F.next=De,F=de;var Ve=a.alternate;Ve!==null&&(Ve=Ve.updateQueue,X=Ve.lastBaseUpdate,X!==F&&(X===null?Ve.firstBaseUpdate=De:X.next=De,Ve.lastBaseUpdate=de))}if(S!==null){var We=T.baseState;F=0,Ve=De=de=null,X=S;do{var Le=X.lane&-536870913,Be=Le!==X.lane;if(Be?(yi&Le)===Le:(m&Le)===Le){Le!==0&&Le===nr&&(O0=!0),Ve!==null&&(Ve=Ve.next={lane:0,tag:X.tag,payload:X.payload,callback:null,next:null});e:{var St=a,jt=X;Le=l;var Ui=h;switch(jt.tag){case 1:if(St=jt.payload,typeof St=="function"){We=St.call(Ui,We,Le);break e}We=St;break e;case 3:St.flags=St.flags&-65537|128;case 0:if(St=jt.payload,Le=typeof St=="function"?St.call(Ui,We,Le):St,Le==null)break e;We=p({},We,Le);break e;case 2:fo=!0}}Le=X.callback,Le!==null&&(a.flags|=64,Be&&(a.flags|=8192),Be=T.callbacks,Be===null?T.callbacks=[Le]:Be.push(Le))}else Be={lane:Le,tag:X.tag,payload:X.payload,callback:X.callback,next:null},Ve===null?(De=Ve=Be,de=We):Ve=Ve.next=Be,F|=Le;if(X=X.next,X===null){if(X=T.shared.pending,X===null)break;Be=X,X=Be.next,Be.next=null,T.lastBaseUpdate=Be,T.shared.pending=null}}while(!0);Ve===null&&(de=We),T.baseState=de,T.firstBaseUpdate=De,T.lastBaseUpdate=Ve,S===null&&(T.shared.lanes=0),bo|=F,a.lanes=F,a.memoizedState=We}}function oT(a,l){if(typeof a!="function")throw Error(i(191,a));a.call(l)}function lT(a,l){var h=a.callbacks;if(h!==null)for(a.callbacks=null,a=0;aS?S:8;var F=H.T,X={};H.T=X,J0(a,!1,l,h);try{var de=T(),De=H.S;if(De!==null&&De(X,de),de!==null&&typeof de=="object"&&typeof de.then=="function"){var Ve=YL(de,m);hd(a,l,Ve,qn(a))}else hd(a,l,m,qn(a))}catch(We){hd(a,l,{then:function(){},status:"rejected",reason:We},qn())}finally{K.p=S,F!==null&&X.types!==null&&(F.types=X.types),H.T=F}}function eR(){}function Q0(a,l,h,m){if(a.tag!==5)throw Error(i(476));var T=jT(a).queue;UT(a,T,l,ie,h===null?eR:function(){return $T(a),h(m)})}function jT(a){var l=a.memoizedState;if(l!==null)return l;l={memoizedState:ie,baseState:ie,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ea,lastRenderedState:ie},next:null};var h={};return l.next={memoizedState:h,baseState:h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ea,lastRenderedState:h},next:null},a.memoizedState=l,a=a.alternate,a!==null&&(a.memoizedState=l),l}function $T(a){var l=jT(a);l.next===null&&(l=a.alternate.memoizedState),hd(a,l.next.queue,{},qn())}function Z0(){return vt(Dd)}function HT(){return _s().memoizedState}function VT(){return _s().memoizedState}function tR(a){for(var l=a.return;l!==null;){switch(l.tag){case 24:case 3:var h=qn();a=mo(h);var m=po(l,a,h);m!==null&&(kn(m,l,h),od(m,l,h)),l={cache:_a()},a.payload=l;return}l=l.return}}function iR(a,l,h){var m=qn();h={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null},_f(a)?zT(l,h):(h=Jc(a,l,h,m),h!==null&&(kn(h,a,m),qT(h,l,m)))}function GT(a,l,h){var m=qn();hd(a,l,h,m)}function hd(a,l,h,m){var T={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null};if(_f(a))zT(l,T);else{var S=a.alternate;if(a.lanes===0&&(S===null||S.lanes===0)&&(S=l.lastRenderedReducer,S!==null))try{var F=l.lastRenderedState,X=S(F,h);if(T.hasEagerState=!0,T.eagerState=X,tn(X,F))return pu(a,l,T,0),zi===null&&mu(),!1}catch{}if(h=Jc(a,l,T,m),h!==null)return kn(h,a,m),qT(h,l,m),!0}return!1}function J0(a,l,h,m){if(m={lane:2,revertLane:Rg(),gesture:null,action:m,hasEagerState:!1,eagerState:null,next:null},_f(a)){if(l)throw Error(i(479))}else l=Jc(a,h,m,2),l!==null&&kn(l,a,2)}function _f(a){var l=a.alternate;return a===si||l!==null&&l===si}function zT(a,l){Tu=pf=!0;var h=a.pending;h===null?l.next=l:(l.next=h.next,h.next=l),a.pending=l}function qT(a,l,h){if((h&4194048)!==0){var m=l.lanes;m&=a.pendingLanes,h|=m,l.lanes=h,Ci(a,h)}}var fd={readContext:vt,use:vf,useCallback:gs,useContext:gs,useEffect:gs,useImperativeHandle:gs,useLayoutEffect:gs,useInsertionEffect:gs,useMemo:gs,useReducer:gs,useRef:gs,useState:gs,useDebugValue:gs,useDeferredValue:gs,useTransition:gs,useSyncExternalStore:gs,useId:gs,useHostTransitionStatus:gs,useFormState:gs,useActionState:gs,useOptimistic:gs,useMemoCache:gs,useCacheRefresh:gs};fd.useEffectEvent=gs;var KT={readContext:vt,use:vf,useCallback:function(a,l){return cn().memoizedState=[a,l===void 0?null:l],a},useContext:vt,useEffect:LT,useImperativeHandle:function(a,l,h){h=h!=null?h.concat([a]):null,bf(4194308,4,OT.bind(null,l,a),h)},useLayoutEffect:function(a,l){return bf(4194308,4,a,l)},useInsertionEffect:function(a,l){bf(4,2,a,l)},useMemo:function(a,l){var h=cn();l=l===void 0?null:l;var m=a();if(_l){Xt(!0);try{a()}finally{Xt(!1)}}return h.memoizedState=[m,l],m},useReducer:function(a,l,h){var m=cn();if(h!==void 0){var T=h(l);if(_l){Xt(!0);try{h(l)}finally{Xt(!1)}}}else T=l;return m.memoizedState=m.baseState=T,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:T},m.queue=a,a=a.dispatch=iR.bind(null,si,a),[m.memoizedState,a]},useRef:function(a){var l=cn();return a={current:a},l.memoizedState=a},useState:function(a){a=q0(a);var l=a.queue,h=GT.bind(null,si,l);return l.dispatch=h,[a.memoizedState,h]},useDebugValue:W0,useDeferredValue:function(a,l){var h=cn();return X0(h,a,l)},useTransition:function(){var a=q0(!1);return a=UT.bind(null,si,a.queue,!0,!1),cn().memoizedState=a,[!1,a]},useSyncExternalStore:function(a,l,h){var m=si,T=cn();if(mi){if(h===void 0)throw Error(i(407));h=h()}else{if(h=l(),zi===null)throw Error(i(349));(yi&127)!==0||mT(m,l,h)}T.memoizedState=h;var S={value:h,getSnapshot:l};return T.queue=S,LT(gT.bind(null,m,S,a),[a]),m.flags|=2048,Su(9,{destroy:void 0},pT.bind(null,m,S,h,l),null),h},useId:function(){var a=cn(),l=zi.identifierPrefix;if(mi){var h=Gs,m=$n;h=(m&~(1<<32-ni(m)-1)).toString(32)+h,l="_"+l+"R_"+h,h=gf++,0<\/script>",S=S.removeChild(S.firstChild);break;case"select":S=typeof m.is=="string"?F.createElement("select",{is:m.is}):F.createElement("select"),m.multiple?S.multiple=!0:m.size&&(S.size=m.size);break;default:S=typeof m.is=="string"?F.createElement(T,{is:m.is}):F.createElement(T)}}S[oi]=l,S[ei]=m;e:for(F=l.child;F!==null;){if(F.tag===5||F.tag===6)S.appendChild(F.stateNode);else if(F.tag!==4&&F.tag!==27&&F.child!==null){F.child.return=F,F=F.child;continue}if(F===l)break e;for(;F.sibling===null;){if(F.return===null||F.return===l)break e;F=F.return}F.sibling.return=F.return,F=F.sibling}l.stateNode=S;e:switch(qs(S,T,m),T){case"button":case"input":case"select":case"textarea":m=!!m.autoFocus;break e;case"img":m=!0;break e;default:m=!1}m&&Aa(l)}}return is(l),fg(l,l.type,a===null?null:a.memoizedProps,l.pendingProps,h),null;case 6:if(a&&l.stateNode!=null)a.memoizedProps!==m&&Aa(l);else{if(typeof m!="string"&&l.stateNode===null)throw Error(i(166));if(a=_e.current,b(l)){if(a=l.stateNode,h=l.memoizedProps,m=null,T=ws,T!==null)switch(T.tag){case 27:case 5:m=T.memoizedProps}a[oi]=l,a=!!(a.nodeValue===h||m!==null&&m.suppressHydrationWarning===!0||h_(a.nodeValue,h)),a||jr(l,!0)}else a=Hf(a).createTextNode(m),a[oi]=l,l.stateNode=a}return is(l),null;case 31:if(h=l.memoizedState,a===null||a.memoizedState!==null){if(m=b(l),h!==null){if(a===null){if(!m)throw Error(i(318));if(a=l.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(i(557));a[oi]=l}else E(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;is(l),a=!1}else h=C(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=h),a=!0;if(!a)return l.flags&256?(Vn(l),l):(Vn(l),null);if((l.flags&128)!==0)throw Error(i(558))}return is(l),null;case 13:if(m=l.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(T=b(l),m!==null&&m.dehydrated!==null){if(a===null){if(!T)throw Error(i(318));if(T=l.memoizedState,T=T!==null?T.dehydrated:null,!T)throw Error(i(317));T[oi]=l}else E(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;is(l),T=!1}else T=C(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=T),T=!0;if(!T)return l.flags&256?(Vn(l),l):(Vn(l),null)}return Vn(l),(l.flags&128)!==0?(l.lanes=h,l):(h=m!==null,a=a!==null&&a.memoizedState!==null,h&&(m=l.child,T=null,m.alternate!==null&&m.alternate.memoizedState!==null&&m.alternate.memoizedState.cachePool!==null&&(T=m.alternate.memoizedState.cachePool.pool),S=null,m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(S=m.memoizedState.cachePool.pool),S!==T&&(m.flags|=2048)),h!==a&&h&&(l.child.flags|=8192),Cf(l,l.updateQueue),is(l),null);case 4:return Ge(),a===null&&Mg(l.stateNode.containerInfo),is(l),null;case 10:return ae(l.type),is(l),null;case 19:if(ee(Ts),m=l.memoizedState,m===null)return is(l),null;if(T=(l.flags&128)!==0,S=m.rendering,S===null)if(T)pd(m,!1);else{if(ys!==0||a!==null&&(a.flags&128)!==0)for(a=l.child;a!==null;){if(S=mf(a),S!==null){for(l.flags|=128,pd(m,!1),a=S.updateQueue,l.updateQueue=a,Cf(l,a),l.subtreeFlags=0,a=h,h=l.child;h!==null;)rf(h,a),h=h.sibling;return le(Ts,Ts.current&1|2),mi&&li(l,m.treeForkCount),l.child}a=a.sibling}m.tail!==null&&Ut()>If&&(l.flags|=128,T=!0,pd(m,!1),l.lanes=4194304)}else{if(!T)if(a=mf(S),a!==null){if(l.flags|=128,T=!0,a=a.updateQueue,l.updateQueue=a,Cf(l,a),pd(m,!0),m.tail===null&&m.tailMode==="hidden"&&!S.alternate&&!mi)return is(l),null}else 2*Ut()-m.renderingStartTime>If&&h!==536870912&&(l.flags|=128,T=!0,pd(m,!1),l.lanes=4194304);m.isBackwards?(S.sibling=l.child,l.child=S):(a=m.last,a!==null?a.sibling=S:l.child=S,m.last=S)}return m.tail!==null?(a=m.tail,m.rendering=a,m.tail=a.sibling,m.renderingStartTime=Ut(),a.sibling=null,h=Ts.current,le(Ts,T?h&1|2:h&1),mi&&li(l,m.treeForkCount),a):(is(l),null);case 22:case 23:return Vn(l),P0(),m=l.memoizedState!==null,a!==null?a.memoizedState!==null!==m&&(l.flags|=8192):m&&(l.flags|=8192),m?(h&536870912)!==0&&(l.flags&128)===0&&(is(l),l.subtreeFlags&6&&(l.flags|=8192)):is(l),h=l.updateQueue,h!==null&&Cf(l,h.retryQueue),h=null,a!==null&&a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(h=a.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==h&&(l.flags|=2048),a!==null&&ee(vl),null;case 24:return h=null,a!==null&&(h=a.memoizedState.cache),l.memoizedState.cache!==h&&(l.flags|=2048),ae(Qi),is(l),null;case 25:return null;case 30:return null}throw Error(i(156,l.tag))}function oR(a,l){switch(_n(l),l.tag){case 1:return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 3:return ae(Qi),Ge(),a=l.flags,(a&65536)!==0&&(a&128)===0?(l.flags=a&-65537|128,l):null;case 26:case 27:case 5:return At(l),null;case 31:if(l.memoizedState!==null){if(Vn(l),l.alternate===null)throw Error(i(340));E()}return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 13:if(Vn(l),a=l.memoizedState,a!==null&&a.dehydrated!==null){if(l.alternate===null)throw Error(i(340));E()}return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 19:return ee(Ts),null;case 4:return Ge(),null;case 10:return ae(l.type),null;case 22:case 23:return Vn(l),P0(),a!==null&&ee(vl),a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 24:return ae(Qi),null;case 25:return null;default:return null}}function y1(a,l){switch(_n(l),l.tag){case 3:ae(Qi),Ge();break;case 26:case 27:case 5:At(l);break;case 4:Ge();break;case 31:l.memoizedState!==null&&Vn(l);break;case 13:Vn(l);break;case 19:ee(Ts);break;case 10:ae(l.type);break;case 22:case 23:Vn(l),P0(),a!==null&&ee(vl);break;case 24:ae(Qi)}}function gd(a,l){try{var h=l.updateQueue,m=h!==null?h.lastEffect:null;if(m!==null){var T=m.next;h=T;do{if((h.tag&a)===a){m=void 0;var S=h.create,F=h.inst;m=S(),F.destroy=m}h=h.next}while(h!==T)}}catch(X){Ni(l,l.return,X)}}function vo(a,l,h){try{var m=l.updateQueue,T=m!==null?m.lastEffect:null;if(T!==null){var S=T.next;m=S;do{if((m.tag&a)===a){var F=m.inst,X=F.destroy;if(X!==void 0){F.destroy=void 0,T=l;var de=h,De=X;try{De()}catch(Ve){Ni(T,de,Ve)}}}m=m.next}while(m!==S)}}catch(Ve){Ni(l,l.return,Ve)}}function v1(a){var l=a.updateQueue;if(l!==null){var h=a.stateNode;try{lT(l,h)}catch(m){Ni(a,a.return,m)}}}function x1(a,l,h){h.props=Sl(a.type,a.memoizedProps),h.state=a.memoizedState;try{h.componentWillUnmount()}catch(m){Ni(a,l,m)}}function yd(a,l){try{var h=a.ref;if(h!==null){switch(a.tag){case 26:case 27:case 5:var m=a.stateNode;break;case 30:m=a.stateNode;break;default:m=a.stateNode}typeof h=="function"?a.refCleanup=h(m):h.current=m}}catch(T){Ni(a,l,T)}}function Vr(a,l){var h=a.ref,m=a.refCleanup;if(h!==null)if(typeof m=="function")try{m()}catch(T){Ni(a,l,T)}finally{a.refCleanup=null,a=a.alternate,a!=null&&(a.refCleanup=null)}else if(typeof h=="function")try{h(null)}catch(T){Ni(a,l,T)}else h.current=null}function b1(a){var l=a.type,h=a.memoizedProps,m=a.stateNode;try{e:switch(l){case"button":case"input":case"select":case"textarea":h.autoFocus&&m.focus();break e;case"img":h.src?m.src=h.src:h.srcSet&&(m.srcset=h.srcSet)}}catch(T){Ni(a,a.return,T)}}function mg(a,l,h){try{var m=a.stateNode;DR(m,a.type,h,l),m[ei]=l}catch(T){Ni(a,a.return,T)}}function T1(a){return a.tag===5||a.tag===3||a.tag===26||a.tag===27&&wo(a.type)||a.tag===4}function pg(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||T1(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.tag===27&&wo(a.type)||a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function gg(a,l,h){var m=a.tag;if(m===5||m===6)a=a.stateNode,l?(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h).insertBefore(a,l):(l=h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,l.appendChild(a),h=h._reactRootContainer,h!=null||l.onclick!==null||(l.onclick=yr));else if(m!==4&&(m===27&&wo(a.type)&&(h=a.stateNode,l=null),a=a.child,a!==null))for(gg(a,l,h),a=a.sibling;a!==null;)gg(a,l,h),a=a.sibling}function kf(a,l,h){var m=a.tag;if(m===5||m===6)a=a.stateNode,l?h.insertBefore(a,l):h.appendChild(a);else if(m!==4&&(m===27&&wo(a.type)&&(h=a.stateNode),a=a.child,a!==null))for(kf(a,l,h),a=a.sibling;a!==null;)kf(a,l,h),a=a.sibling}function _1(a){var l=a.stateNode,h=a.memoizedProps;try{for(var m=a.type,T=l.attributes;T.length;)l.removeAttributeNode(T[0]);qs(l,m,h),l[oi]=a,l[ei]=h}catch(S){Ni(a,a.return,S)}}var Ca=!1,ks=!1,yg=!1,S1=typeof WeakSet=="function"?WeakSet:Set,Us=null;function lR(a,l){if(a=a.containerInfo,Fg=Wf,a=hu(a),qc(a)){if("selectionStart"in a)var h={start:a.selectionStart,end:a.selectionEnd};else e:{h=(h=a.ownerDocument)&&h.defaultView||window;var m=h.getSelection&&h.getSelection();if(m&&m.rangeCount!==0){h=m.anchorNode;var T=m.anchorOffset,S=m.focusNode;m=m.focusOffset;try{h.nodeType,S.nodeType}catch{h=null;break e}var F=0,X=-1,de=-1,De=0,Ve=0,We=a,Le=null;t:for(;;){for(var Be;We!==h||T!==0&&We.nodeType!==3||(X=F+T),We!==S||m!==0&&We.nodeType!==3||(de=F+m),We.nodeType===3&&(F+=We.nodeValue.length),(Be=We.firstChild)!==null;)Le=We,We=Be;for(;;){if(We===a)break t;if(Le===h&&++De===T&&(X=F),Le===S&&++Ve===m&&(de=F),(Be=We.nextSibling)!==null)break;We=Le,Le=We.parentNode}We=Be}h=X===-1||de===-1?null:{start:X,end:de}}else h=null}h=h||{start:0,end:0}}else h=null;for(Ug={focusedElem:a,selectionRange:h},Wf=!1,Us=l;Us!==null;)if(l=Us,a=l.child,(l.subtreeFlags&1028)!==0&&a!==null)a.return=l,Us=a;else for(;Us!==null;){switch(l=Us,S=l.alternate,a=l.flags,l.tag){case 0:if((a&4)!==0&&(a=l.updateQueue,a=a!==null?a.events:null,a!==null))for(h=0;h title"))),qs(S,m,h),S[oi]=a,ye(S),m=S;break e;case"link":var F=D_("link","href",T).get(m+(h.href||""));if(F){for(var X=0;XUi&&(F=Ui,Ui=jt,jt=F);var Te=rs(X,jt),pe=rs(X,Ui);if(Te&&pe&&(Be.rangeCount!==1||Be.anchorNode!==Te.node||Be.anchorOffset!==Te.offset||Be.focusNode!==pe.node||Be.focusOffset!==pe.offset)){var ke=We.createRange();ke.setStart(Te.node,Te.offset),Be.removeAllRanges(),jt>Ui?(Be.addRange(ke),Be.extend(pe.node,pe.offset)):(ke.setEnd(pe.node,pe.offset),Be.addRange(ke))}}}}for(We=[],Be=X;Be=Be.parentNode;)Be.nodeType===1&&We.push({element:Be,left:Be.scrollLeft,top:Be.scrollTop});for(typeof X.focus=="function"&&X.focus(),X=0;Xh?32:h,H.T=null,h=Eg,Eg=null;var S=_o,F=Ia;if(Ns=0,ku=_o=null,Ia=0,(ki&6)!==0)throw Error(i(331));var X=ki;if(ki|=4,O1(S.current),R1(S,S.current,F,h),ki=X,Sd(0,!1),kt&&typeof kt.onPostCommitFiberRoot=="function")try{kt.onPostCommitFiberRoot(Ot,S)}catch{}return!0}finally{K.p=T,H.T=m,Z1(a,l)}}function e_(a,l,h){l=bn(h,l),l=sg(a.stateNode,l,2),a=po(a,l,2),a!==null&&(Jt(a,2),Gr(a))}function Ni(a,l,h){if(a.tag===3)e_(a,a,h);else for(;l!==null;){if(l.tag===3){e_(l,a,h);break}else if(l.tag===1){var m=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof m.componentDidCatch=="function"&&(To===null||!To.has(m))){a=bn(h,a),h=t1(2),m=po(l,h,2),m!==null&&(i1(h,m,l,a),Jt(m,2),Gr(m));break}}l=l.return}}function kg(a,l,h){var m=a.pingCache;if(m===null){m=a.pingCache=new dR;var T=new Set;m.set(l,T)}else T=m.get(l),T===void 0&&(T=new Set,m.set(l,T));T.has(h)||(bg=!0,T.add(h),a=gR.bind(null,a,l,h),l.then(a,a))}function gR(a,l,h){var m=a.pingCache;m!==null&&m.delete(l),a.pingedLanes|=a.suspendedLanes&h,a.warmLanes&=~h,zi===a&&(yi&h)===h&&(ys===4||ys===3&&(yi&62914560)===yi&&300>Ut()-Rf?(ki&2)===0&&Du(a,0):Tg|=h,Cu===yi&&(Cu=0)),Gr(a)}function t_(a,l){l===0&&(l=Ze()),a=Ta(a,l),a!==null&&(Jt(a,l),Gr(a))}function yR(a){var l=a.memoizedState,h=0;l!==null&&(h=l.retryLane),t_(a,h)}function vR(a,l){var h=0;switch(a.tag){case 31:case 13:var m=a.stateNode,T=a.memoizedState;T!==null&&(h=T.retryLane);break;case 19:m=a.stateNode;break;case 22:m=a.stateNode._retryCache;break;default:throw Error(i(314))}m!==null&&m.delete(l),t_(a,h)}function xR(a,l){return Ke(a,l)}var Ff=null,Ru=null,Dg=!1,Uf=!1,Lg=!1,Eo=0;function Gr(a){a!==Ru&&a.next===null&&(Ru===null?Ff=Ru=a:Ru=Ru.next=a),Uf=!0,Dg||(Dg=!0,TR())}function Sd(a,l){if(!Lg&&Uf){Lg=!0;do for(var h=!1,m=Ff;m!==null;){if(a!==0){var T=m.pendingLanes;if(T===0)var S=0;else{var F=m.suspendedLanes,X=m.pingedLanes;S=(1<<31-ni(42|a)+1)-1,S&=T&~(F&~X),S=S&201326741?S&201326741|1:S?S|2:0}S!==0&&(h=!0,r_(m,S))}else S=yi,S=W(m,m===zi?S:0,m.cancelPendingCommit!==null||m.timeoutHandle!==-1),(S&3)===0||oe(m,S)||(h=!0,r_(m,S));m=m.next}while(h);Lg=!1}}function bR(){i_()}function i_(){Uf=Dg=!1;var a=0;Eo!==0&&RR()&&(a=Eo);for(var l=Ut(),h=null,m=Ff;m!==null;){var T=m.next,S=s_(m,l);S===0?(m.next=null,h===null?Ff=T:h.next=T,T===null&&(Ru=h)):(h=m,(a!==0||(S&3)!==0)&&(Uf=!0)),m=T}Ns!==0&&Ns!==5||Sd(a),Eo!==0&&(Eo=0)}function s_(a,l){for(var h=a.suspendedLanes,m=a.pingedLanes,T=a.expirationTimes,S=a.pendingLanes&-62914561;0X)break;var Ve=de.transferSize,We=de.initiatorType;Ve&&f_(We)&&(de=de.responseEnd,F+=Ve*(de"u"?null:document;function w_(a,l,h){var m=Iu;if(m&&typeof l=="string"&&l){var T=Bs(l);T='link[rel="'+a+'"][href="'+T+'"]',typeof h=="string"&&(T+='[crossorigin="'+h+'"]'),E_.has(T)||(E_.add(T),a={rel:a,crossOrigin:h,href:l},m.querySelector(T)===null&&(l=m.createElement("link"),qs(l,"link",a),ye(l),m.head.appendChild(l)))}}function jR(a){Na.D(a),w_("dns-prefetch",a,null)}function $R(a,l){Na.C(a,l),w_("preconnect",a,l)}function HR(a,l,h){Na.L(a,l,h);var m=Iu;if(m&&a&&l){var T='link[rel="preload"][as="'+Bs(l)+'"]';l==="image"&&h&&h.imageSrcSet?(T+='[imagesrcset="'+Bs(h.imageSrcSet)+'"]',typeof h.imageSizes=="string"&&(T+='[imagesizes="'+Bs(h.imageSizes)+'"]')):T+='[href="'+Bs(a)+'"]';var S=T;switch(l){case"style":S=Nu(a);break;case"script":S=Ou(a)}or.has(S)||(a=p({rel:"preload",href:l==="image"&&h&&h.imageSrcSet?void 0:a,as:l},h),or.set(S,a),m.querySelector(T)!==null||l==="style"&&m.querySelector(Cd(S))||l==="script"&&m.querySelector(kd(S))||(l=m.createElement("link"),qs(l,"link",a),ye(l),m.head.appendChild(l)))}}function VR(a,l){Na.m(a,l);var h=Iu;if(h&&a){var m=l&&typeof l.as=="string"?l.as:"script",T='link[rel="modulepreload"][as="'+Bs(m)+'"][href="'+Bs(a)+'"]',S=T;switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":S=Ou(a)}if(!or.has(S)&&(a=p({rel:"modulepreload",href:a},l),or.set(S,a),h.querySelector(T)===null)){switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(h.querySelector(kd(S)))return}m=h.createElement("link"),qs(m,"link",a),ye(m),h.head.appendChild(m)}}}function GR(a,l,h){Na.S(a,l,h);var m=Iu;if(m&&a){var T=he(m).hoistableStyles,S=Nu(a);l=l||"default";var F=T.get(S);if(!F){var X={loading:0,preload:null};if(F=m.querySelector(Cd(S)))X.loading=5;else{a=p({rel:"stylesheet",href:a,"data-precedence":l},h),(h=or.get(S))&&qg(a,h);var de=F=m.createElement("link");ye(de),qs(de,"link",a),de._p=new Promise(function(De,Ve){de.onload=De,de.onerror=Ve}),de.addEventListener("load",function(){X.loading|=1}),de.addEventListener("error",function(){X.loading|=2}),X.loading|=4,Gf(F,l,m)}F={type:"stylesheet",instance:F,count:1,state:X},T.set(S,F)}}}function zR(a,l){Na.X(a,l);var h=Iu;if(h&&a){var m=he(h).hoistableScripts,T=Ou(a),S=m.get(T);S||(S=h.querySelector(kd(T)),S||(a=p({src:a,async:!0},l),(l=or.get(T))&&Kg(a,l),S=h.createElement("script"),ye(S),qs(S,"link",a),h.head.appendChild(S)),S={type:"script",instance:S,count:1,state:null},m.set(T,S))}}function qR(a,l){Na.M(a,l);var h=Iu;if(h&&a){var m=he(h).hoistableScripts,T=Ou(a),S=m.get(T);S||(S=h.querySelector(kd(T)),S||(a=p({src:a,async:!0,type:"module"},l),(l=or.get(T))&&Kg(a,l),S=h.createElement("script"),ye(S),qs(S,"link",a),h.head.appendChild(S)),S={type:"script",instance:S,count:1,state:null},m.set(T,S))}}function A_(a,l,h,m){var T=(T=_e.current)?Vf(T):null;if(!T)throw Error(i(446));switch(a){case"meta":case"title":return null;case"style":return typeof h.precedence=="string"&&typeof h.href=="string"?(l=Nu(h.href),h=he(T).hoistableStyles,m=h.get(l),m||(m={type:"style",instance:null,count:0,state:null},h.set(l,m)),m):{type:"void",instance:null,count:0,state:null};case"link":if(h.rel==="stylesheet"&&typeof h.href=="string"&&typeof h.precedence=="string"){a=Nu(h.href);var S=he(T).hoistableStyles,F=S.get(a);if(F||(T=T.ownerDocument||T,F={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},S.set(a,F),(S=T.querySelector(Cd(a)))&&!S._p&&(F.instance=S,F.state.loading=5),or.has(a)||(h={rel:"preload",as:"style",href:h.href,crossOrigin:h.crossOrigin,integrity:h.integrity,media:h.media,hrefLang:h.hrefLang,referrerPolicy:h.referrerPolicy},or.set(a,h),S||KR(T,a,h,F.state))),l&&m===null)throw Error(i(528,""));return F}if(l&&m!==null)throw Error(i(529,""));return null;case"script":return l=h.async,h=h.src,typeof h=="string"&&l&&typeof l!="function"&&typeof l!="symbol"?(l=Ou(h),h=he(T).hoistableScripts,m=h.get(l),m||(m={type:"script",instance:null,count:0,state:null},h.set(l,m)),m):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,a))}}function Nu(a){return'href="'+Bs(a)+'"'}function Cd(a){return'link[rel="stylesheet"]['+a+"]"}function C_(a){return p({},a,{"data-precedence":a.precedence,precedence:null})}function KR(a,l,h,m){a.querySelector('link[rel="preload"][as="style"]['+l+"]")?m.loading=1:(l=a.createElement("link"),m.preload=l,l.addEventListener("load",function(){return m.loading|=1}),l.addEventListener("error",function(){return m.loading|=2}),qs(l,"link",h),ye(l),a.head.appendChild(l))}function Ou(a){return'[src="'+Bs(a)+'"]'}function kd(a){return"script[async]"+a}function k_(a,l,h){if(l.count++,l.instance===null)switch(l.type){case"style":var m=a.querySelector('style[data-href~="'+Bs(h.href)+'"]');if(m)return l.instance=m,ye(m),m;var T=p({},h,{"data-href":h.href,"data-precedence":h.precedence,href:null,precedence:null});return m=(a.ownerDocument||a).createElement("style"),ye(m),qs(m,"style",T),Gf(m,h.precedence,a),l.instance=m;case"stylesheet":T=Nu(h.href);var S=a.querySelector(Cd(T));if(S)return l.state.loading|=4,l.instance=S,ye(S),S;m=C_(h),(T=or.get(T))&&qg(m,T),S=(a.ownerDocument||a).createElement("link"),ye(S);var F=S;return F._p=new Promise(function(X,de){F.onload=X,F.onerror=de}),qs(S,"link",m),l.state.loading|=4,Gf(S,h.precedence,a),l.instance=S;case"script":return S=Ou(h.src),(T=a.querySelector(kd(S)))?(l.instance=T,ye(T),T):(m=h,(T=or.get(S))&&(m=p({},h),Kg(m,T)),a=a.ownerDocument||a,T=a.createElement("script"),ye(T),qs(T,"link",m),a.head.appendChild(T),l.instance=T);case"void":return null;default:throw Error(i(443,l.type))}else l.type==="stylesheet"&&(l.state.loading&4)===0&&(m=l.instance,l.state.loading|=4,Gf(m,h.precedence,a));return l.instance}function Gf(a,l,h){for(var m=h.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),T=m.length?m[m.length-1]:null,S=T,F=0;F title"):null)}function YR(a,l,h){if(h===1||l.itemProp!=null)return!1;switch(a){case"meta":case"title":return!0;case"style":if(typeof l.precedence!="string"||typeof l.href!="string"||l.href==="")break;return!0;case"link":if(typeof l.rel!="string"||typeof l.href!="string"||l.href===""||l.onLoad||l.onError)break;return l.rel==="stylesheet"?(a=l.disabled,typeof l.precedence=="string"&&a==null):!0;case"script":if(l.async&&typeof l.async!="function"&&typeof l.async!="symbol"&&!l.onLoad&&!l.onError&&l.src&&typeof l.src=="string")return!0}return!1}function R_(a){return!(a.type==="stylesheet"&&(a.state.loading&3)===0)}function WR(a,l,h,m){if(h.type==="stylesheet"&&(typeof m.media!="string"||matchMedia(m.media).matches!==!1)&&(h.state.loading&4)===0){if(h.instance===null){var T=Nu(m.href),S=l.querySelector(Cd(T));if(S){l=S._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(a.count++,a=qf.bind(a),l.then(a,a)),h.state.loading|=4,h.instance=S,ye(S);return}S=l.ownerDocument||l,m=C_(m),(T=or.get(T))&&qg(m,T),S=S.createElement("link"),ye(S);var F=S;F._p=new Promise(function(X,de){F.onload=X,F.onerror=de}),qs(S,"link",m),h.instance=S}a.stylesheets===null&&(a.stylesheets=new Map),a.stylesheets.set(h,l),(l=h.state.preload)&&(h.state.loading&3)===0&&(a.count++,h=qf.bind(a),l.addEventListener("load",h),l.addEventListener("error",h))}}var Yg=0;function XR(a,l){return a.stylesheets&&a.count===0&&Yf(a,a.stylesheets),0Yg?50:800)+l);return a.unsuspend=h,function(){a.unsuspend=null,clearTimeout(m),clearTimeout(T)}}:null}function qf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Yf(this,this.stylesheets);else if(this.unsuspend){var a=this.unsuspend;this.unsuspend=null,a()}}}var Kf=null;function Yf(a,l){a.stylesheets=null,a.unsuspend!==null&&(a.count++,Kf=new Map,l.forEach(QR,a),Kf=null,qf.call(a))}function QR(a,l){if(!(l.state.loading&4)){var h=Kf.get(a);if(h)var m=h.get(null);else{h=new Map,Kf.set(a,h);for(var T=a.querySelectorAll("link[data-precedence],style[data-precedence]"),S=0;S"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),sy.exports=mI(),sy.exports}var gI=pI();function yI(...s){return s.filter(Boolean).join(" ")}const vI="inline-flex items-center justify-center font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",xI={sm:"rounded-sm",md:"rounded-md",full:"rounded-full"},bI={xs:"px-2 py-1 text-xs",sm:"px-2.5 py-1.5 text-sm",md:"px-3 py-2 text-sm",lg:"px-3.5 py-2.5 text-sm"},TI={indigo:{primary:"!bg-indigo-600 !text-white shadow-sm hover:!bg-indigo-700 focus-visible:outline-indigo-600 dark:!bg-indigo-500 dark:hover:!bg-indigo-400 dark:focus-visible:outline-indigo-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-indigo-50 text-indigo-600 shadow-xs hover:bg-indigo-100 dark:bg-indigo-500/20 dark:text-indigo-400 dark:shadow-none dark:hover:bg-indigo-500/30"},blue:{primary:"!bg-blue-600 !text-white shadow-sm hover:!bg-blue-700 focus-visible:outline-blue-600 dark:!bg-blue-500 dark:hover:!bg-blue-400 dark:focus-visible:outline-blue-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-blue-50 text-blue-600 shadow-xs hover:bg-blue-100 dark:bg-blue-500/20 dark:text-blue-400 dark:shadow-none dark:hover:bg-blue-500/30"},emerald:{primary:"!bg-emerald-600 !text-white shadow-sm hover:!bg-emerald-700 focus-visible:outline-emerald-600 dark:!bg-emerald-500 dark:hover:!bg-emerald-400 dark:focus-visible:outline-emerald-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-emerald-50 text-emerald-700 shadow-xs hover:bg-emerald-100 dark:bg-emerald-500/20 dark:text-emerald-400 dark:shadow-none dark:hover:bg-emerald-500/30"},red:{primary:"!bg-red-600 !text-white shadow-sm hover:!bg-red-700 focus-visible:outline-red-600 dark:!bg-red-500 dark:hover:!bg-red-400 dark:focus-visible:outline-red-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-red-50 text-red-700 shadow-xs hover:bg-red-100 dark:bg-red-500/20 dark:text-red-400 dark:shadow-none dark:hover:bg-red-500/30"},amber:{primary:"!bg-amber-500 !text-white shadow-sm hover:!bg-amber-600 focus-visible:outline-amber-500 dark:!bg-amber-500 dark:hover:!bg-amber-400 dark:focus-visible:outline-amber-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-amber-50 text-amber-800 shadow-xs hover:bg-amber-100 dark:bg-amber-500/20 dark:text-amber-300 dark:shadow-none dark:hover:bg-amber-500/30"}};function _I(){return v.jsxs("svg",{viewBox:"0 0 24 24",className:"size-4 animate-spin","aria-hidden":"true",children:[v.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.25"}),v.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.9"})]})}function _i({children:s,variant:e="primary",color:t="indigo",size:i="md",rounded:n="md",leadingIcon:r,trailingIcon:o,isLoading:u=!1,disabled:c,className:d,type:f="button",...p}){const g=r||o||u?"gap-x-1.5":"";return v.jsxs("button",{type:f,disabled:c||u,className:yI(vI,xI[n],bI[i],TI[t][e],g,d),...p,children:[u?v.jsx("span",{className:"-ml-0.5",children:v.jsx(_I,{})}):r&&v.jsx("span",{className:"-ml-0.5",children:r}),v.jsx("span",{children:s}),o&&!u&&v.jsx("span",{className:"-mr-0.5",children:o})]})}function Uw(s){var e,t,i="";if(typeof s=="string"||typeof s=="number")i+=s;else if(typeof s=="object")if(Array.isArray(s)){var n=s.length;for(e=0;ee in s?SI(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,oy=(s,e,t)=>(EI(s,typeof e!="symbol"?e+"":e,t),t);let wI=class{constructor(){oy(this,"current",this.detect()),oy(this,"handoffState","pending"),oy(this,"currentId",0)}set(e){this.current!==e&&(this.handoffState="pending",this.currentId=0,this.current=e)}reset(){this.set(this.detect())}nextId(){return++this.currentId}get isServer(){return this.current==="server"}get isClient(){return this.current==="client"}detect(){return typeof window>"u"||typeof document>"u"?"server":"client"}handoff(){this.handoffState==="pending"&&(this.handoffState="complete")}get isHandoffComplete(){return this.handoffState==="complete"}},oa=new wI;function Eh(s){var e;return oa.isServer?null:s==null?document:(e=s?.ownerDocument)!=null?e:document}function kv(s){var e,t;return oa.isServer?null:s==null?document:(t=(e=s?.getRootNode)==null?void 0:e.call(s))!=null?t:document}function jw(s){var e,t;return(t=(e=kv(s))==null?void 0:e.activeElement)!=null?t:null}function AI(s){return jw(s)===s}function Dp(s){typeof queueMicrotask=="function"?queueMicrotask(s):Promise.resolve().then(s).catch(e=>setTimeout(()=>{throw e}))}function Ka(){let s=[],e={addEventListener(t,i,n,r){return t.addEventListener(i,n,r),e.add(()=>t.removeEventListener(i,n,r))},requestAnimationFrame(...t){let i=requestAnimationFrame(...t);return e.add(()=>cancelAnimationFrame(i))},nextFrame(...t){return e.requestAnimationFrame(()=>e.requestAnimationFrame(...t))},setTimeout(...t){let i=setTimeout(...t);return e.add(()=>clearTimeout(i))},microTask(...t){let i={current:!0};return Dp(()=>{i.current&&t[0]()}),e.add(()=>{i.current=!1})},style(t,i,n){let r=t.style.getPropertyValue(i);return Object.assign(t.style,{[i]:n}),this.add(()=>{Object.assign(t.style,{[i]:r})})},group(t){let i=Ka();return t(i),this.add(()=>i.dispose())},add(t){return s.includes(t)||s.push(t),()=>{let i=s.indexOf(t);if(i>=0)for(let n of s.splice(i,1))n()}},dispose(){for(let t of s.splice(0))t()}};return e}function Lp(){let[s]=k.useState(Ka);return k.useEffect(()=>()=>s.dispose(),[s]),s}let Pn=(s,e)=>{oa.isServer?k.useEffect(s,e):k.useLayoutEffect(s,e)};function Wl(s){let e=k.useRef(s);return Pn(()=>{e.current=s},[s]),e}let Ki=function(s){let e=Wl(s);return Bt.useCallback((...t)=>e.current(...t),[e])};function wh(s){return k.useMemo(()=>s,Object.values(s))}let CI=k.createContext(void 0);function kI(){return k.useContext(CI)}function Dv(...s){return Array.from(new Set(s.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function Ga(s,e,...t){if(s in e){let n=e[s];return typeof n=="function"?n(...t):n}let i=new Error(`Tried to handle "${s}" but there is no handler defined. Only defined handlers are: ${Object.keys(e).map(n=>`"${n}"`).join(", ")}.`);throw Error.captureStackTrace&&Error.captureStackTrace(i,Ga),i}var zm=(s=>(s[s.None=0]="None",s[s.RenderStrategy=1]="RenderStrategy",s[s.Static=2]="Static",s))(zm||{}),Vo=(s=>(s[s.Unmount=0]="Unmount",s[s.Hidden=1]="Hidden",s))(Vo||{});function mr(){let s=LI();return k.useCallback(e=>DI({mergeRefs:s,...e}),[s])}function DI({ourProps:s,theirProps:e,slot:t,defaultTag:i,features:n,visible:r=!0,name:o,mergeRefs:u}){u=u??RI;let c=$w(e,s);if(r)return im(c,t,i,o,u);let d=n??0;if(d&2){let{static:f=!1,...p}=c;if(f)return im(p,t,i,o,u)}if(d&1){let{unmount:f=!0,...p}=c;return Ga(f?0:1,{0(){return null},1(){return im({...p,hidden:!0,style:{display:"none"}},t,i,o,u)}})}return im(c,t,i,o,u)}function im(s,e={},t,i,n){let{as:r=t,children:o,refName:u="ref",...c}=ly(s,["unmount","static"]),d=s.ref!==void 0?{[u]:s.ref}:{},f=typeof o=="function"?o(e):o;"className"in c&&c.className&&typeof c.className=="function"&&(c.className=c.className(e)),c["aria-labelledby"]&&c["aria-labelledby"]===c.id&&(c["aria-labelledby"]=void 0);let p={};if(e){let g=!1,y=[];for(let[x,_]of Object.entries(e))typeof _=="boolean"&&(g=!0),_===!0&&y.push(x.replace(/([A-Z])/g,w=>`-${w.toLowerCase()}`));if(g){p["data-headlessui-state"]=y.join(" ");for(let x of y)p[`data-${x}`]=""}}if(Xd(r)&&(Object.keys(Rl(c)).length>0||Object.keys(Rl(p)).length>0))if(!k.isValidElement(f)||Array.isArray(f)&&f.length>1||NI(f)){if(Object.keys(Rl(c)).length>0)throw new Error(['Passing props on "Fragment"!',"",`The current component <${i} /> is rendering a "Fragment".`,"However we need to passthrough the following props:",Object.keys(Rl(c)).concat(Object.keys(Rl(p))).map(g=>` - ${g}`).join(` +`),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(g=>` - ${g}`).join(` +`)].join(` +`))}else{let g=f.props,y=g?.className,x=typeof y=="function"?(...D)=>Dv(y(...D),c.className):Dv(y,c.className),_=x?{className:x}:{},w=$w(f.props,Rl(ly(c,["ref"])));for(let D in p)D in w&&delete p[D];return k.cloneElement(f,Object.assign({},w,p,d,{ref:n(II(f),d.ref)},_))}return k.createElement(r,Object.assign({},ly(c,["ref"]),!Xd(r)&&d,!Xd(r)&&p),f)}function LI(){let s=k.useRef([]),e=k.useCallback(t=>{for(let i of s.current)i!=null&&(typeof i=="function"?i(t):i.current=t)},[]);return(...t)=>{if(!t.every(i=>i==null))return s.current=t,e}}function RI(...s){return s.every(e=>e==null)?void 0:e=>{for(let t of s)t!=null&&(typeof t=="function"?t(e):t.current=e)}}function $w(...s){if(s.length===0)return{};if(s.length===1)return s[0];let e={},t={};for(let i of s)for(let n in i)n.startsWith("on")&&typeof i[n]=="function"?(t[n]!=null||(t[n]=[]),t[n].push(i[n])):e[n]=i[n];if(e.disabled||e["aria-disabled"])for(let i in t)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(i)&&(t[i]=[n=>{var r;return(r=n?.preventDefault)==null?void 0:r.call(n)}]);for(let i in t)Object.assign(e,{[i](n,...r){let o=t[i];for(let u of o){if((n instanceof Event||n?.nativeEvent instanceof Event)&&n.defaultPrevented)return;u(n,...r)}}});return e}function Fn(s){var e;return Object.assign(k.forwardRef(s),{displayName:(e=s.displayName)!=null?e:s.name})}function Rl(s){let e=Object.assign({},s);for(let t in e)e[t]===void 0&&delete e[t];return e}function ly(s,e=[]){let t=Object.assign({},s);for(let i of e)i in t&&delete t[i];return t}function II(s){return Bt.version.split(".")[0]>="19"?s.props.ref:s.ref}function Xd(s){return s===k.Fragment||s===Symbol.for("react.fragment")}function NI(s){return Xd(s.type)}let OI="span";var qm=(s=>(s[s.None=1]="None",s[s.Focusable=2]="Focusable",s[s.Hidden=4]="Hidden",s))(qm||{});function MI(s,e){var t;let{features:i=1,...n}=s,r={ref:e,"aria-hidden":(i&2)===2?!0:(t=n["aria-hidden"])!=null?t:void 0,hidden:(i&4)===4?!0:void 0,style:{position:"fixed",top:1,left:1,width:1,height:0,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0",...(i&4)===4&&(i&2)!==2&&{display:"none"}}};return mr()({ourProps:r,theirProps:n,slot:{},defaultTag:OI,name:"Hidden"})}let Lv=Fn(MI);function PI(s){return typeof s!="object"||s===null?!1:"nodeType"in s}function zo(s){return PI(s)&&"tagName"in s}function zl(s){return zo(s)&&"accessKey"in s}function Go(s){return zo(s)&&"tabIndex"in s}function BI(s){return zo(s)&&"style"in s}function FI(s){return zl(s)&&s.nodeName==="IFRAME"}function UI(s){return zl(s)&&s.nodeName==="INPUT"}let Hw=Symbol();function jI(s,e=!0){return Object.assign(s,{[Hw]:e})}function ma(...s){let e=k.useRef(s);k.useEffect(()=>{e.current=s},[s]);let t=Ki(i=>{for(let n of e.current)n!=null&&(typeof n=="function"?n(i):n.current=i)});return s.every(i=>i==null||i?.[Hw])?void 0:t}let Nx=k.createContext(null);Nx.displayName="DescriptionContext";function Vw(){let s=k.useContext(Nx);if(s===null){let e=new Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(e,Vw),e}return s}function $I(){let[s,e]=k.useState([]);return[s.length>0?s.join(" "):void 0,k.useMemo(()=>function(t){let i=Ki(r=>(e(o=>[...o,r]),()=>e(o=>{let u=o.slice(),c=u.indexOf(r);return c!==-1&&u.splice(c,1),u}))),n=k.useMemo(()=>({register:i,slot:t.slot,name:t.name,props:t.props,value:t.value}),[i,t.slot,t.name,t.props,t.value]);return Bt.createElement(Nx.Provider,{value:n},t.children)},[e])]}let HI="p";function VI(s,e){let t=k.useId(),i=kI(),{id:n=`headlessui-description-${t}`,...r}=s,o=Vw(),u=ma(e);Pn(()=>o.register(n),[n,o.register]);let c=wh({...o.slot,disabled:i||!1}),d={ref:u,...o.props,id:n};return mr()({ourProps:d,theirProps:r,slot:c,defaultTag:HI,name:o.name||"Description"})}let GI=Fn(VI),zI=Object.assign(GI,{});var Gw=(s=>(s.Space=" ",s.Enter="Enter",s.Escape="Escape",s.Backspace="Backspace",s.Delete="Delete",s.ArrowLeft="ArrowLeft",s.ArrowUp="ArrowUp",s.ArrowRight="ArrowRight",s.ArrowDown="ArrowDown",s.Home="Home",s.End="End",s.PageUp="PageUp",s.PageDown="PageDown",s.Tab="Tab",s))(Gw||{});let qI=k.createContext(()=>{});function KI({value:s,children:e}){return Bt.createElement(qI.Provider,{value:s},e)}let zw=class extends Map{constructor(e){super(),this.factory=e}get(e){let t=super.get(e);return t===void 0&&(t=this.factory(e),this.set(e,t)),t}};var YI=Object.defineProperty,WI=(s,e,t)=>e in s?YI(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,XI=(s,e,t)=>(WI(s,e+"",t),t),qw=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},lr=(s,e,t)=>(qw(s,e,"read from private field"),t?t.call(s):e.get(s)),uy=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)},iS=(s,e,t,i)=>(qw(s,e,"write to private field"),e.set(s,t),t),Xr,Vd,Gd;let QI=class{constructor(e){uy(this,Xr,{}),uy(this,Vd,new zw(()=>new Set)),uy(this,Gd,new Set),XI(this,"disposables",Ka()),iS(this,Xr,e),oa.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return lr(this,Xr)}subscribe(e,t){if(oa.isServer)return()=>{};let i={selector:e,callback:t,current:e(lr(this,Xr))};return lr(this,Gd).add(i),this.disposables.add(()=>{lr(this,Gd).delete(i)})}on(e,t){return oa.isServer?()=>{}:(lr(this,Vd).get(e).add(t),this.disposables.add(()=>{lr(this,Vd).get(e).delete(t)}))}send(e){let t=this.reduce(lr(this,Xr),e);if(t!==lr(this,Xr)){iS(this,Xr,t);for(let i of lr(this,Gd)){let n=i.selector(lr(this,Xr));Kw(i.current,n)||(i.current=n,i.callback(n))}for(let i of lr(this,Vd).get(e.type))i(lr(this,Xr),e)}}};Xr=new WeakMap,Vd=new WeakMap,Gd=new WeakMap;function Kw(s,e){return Object.is(s,e)?!0:typeof s!="object"||s===null||typeof e!="object"||e===null?!1:Array.isArray(s)&&Array.isArray(e)?s.length!==e.length?!1:cy(s[Symbol.iterator](),e[Symbol.iterator]()):s instanceof Map&&e instanceof Map||s instanceof Set&&e instanceof Set?s.size!==e.size?!1:cy(s.entries(),e.entries()):sS(s)&&sS(e)?cy(Object.entries(s)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function cy(s,e){do{let t=s.next(),i=e.next();if(t.done&&i.done)return!0;if(t.done||i.done||!Object.is(t.value,i.value))return!1}while(!0)}function sS(s){if(Object.prototype.toString.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||Object.getPrototypeOf(e)===null}var ZI=Object.defineProperty,JI=(s,e,t)=>e in s?ZI(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,nS=(s,e,t)=>(JI(s,typeof e!="symbol"?e+"":e,t),t),eN=(s=>(s[s.Push=0]="Push",s[s.Pop=1]="Pop",s))(eN||{});let tN={0(s,e){let t=e.id,i=s.stack,n=s.stack.indexOf(t);if(n!==-1){let r=s.stack.slice();return r.splice(n,1),r.push(t),i=r,{...s,stack:i}}return{...s,stack:[...s.stack,t]}},1(s,e){let t=e.id,i=s.stack.indexOf(t);if(i===-1)return s;let n=s.stack.slice();return n.splice(i,1),{...s,stack:n}}},iN=class Yw extends QI{constructor(){super(...arguments),nS(this,"actions",{push:e=>this.send({type:0,id:e}),pop:e=>this.send({type:1,id:e})}),nS(this,"selectors",{isTop:(e,t)=>e.stack[e.stack.length-1]===t,inStack:(e,t)=>e.stack.includes(t)})}static new(){return new Yw({stack:[]})}reduce(e,t){return Ga(t.type,tN,e,t)}};const Ww=new zw(()=>iN.new());var dy={exports:{}},hy={};var rS;function sN(){if(rS)return hy;rS=1;var s=kp();function e(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var t=typeof Object.is=="function"?Object.is:e,i=s.useSyncExternalStore,n=s.useRef,r=s.useEffect,o=s.useMemo,u=s.useDebugValue;return hy.useSyncExternalStoreWithSelector=function(c,d,f,p,g){var y=n(null);if(y.current===null){var x={hasValue:!1,value:null};y.current=x}else x=y.current;y=o(function(){function w(j){if(!D){if(D=!0,I=j,j=p(j),g!==void 0&&x.hasValue){var V=x.value;if(g(V,j))return L=V}return L=j}if(V=L,t(I,j))return V;var M=p(j);return g!==void 0&&g(V,M)?(I=j,V):(I=j,L=M)}var D=!1,I,L,B=f===void 0?null:f;return[function(){return w(d())},B===null?void 0:function(){return w(B())}]},[d,f,p,g]);var _=i(c,y[0],y[1]);return r(function(){x.hasValue=!0,x.value=_},[_]),u(_),_},hy}var aS;function nN(){return aS||(aS=1,dy.exports=sN()),dy.exports}var rN=nN();function Xw(s,e,t=Kw){return rN.useSyncExternalStoreWithSelector(Ki(i=>s.subscribe(aN,i)),Ki(()=>s.state),Ki(()=>s.state),Ki(e),t)}function aN(s){return s}function Ah(s,e){let t=k.useId(),i=Ww.get(e),[n,r]=Xw(i,k.useCallback(o=>[i.selectors.isTop(o,t),i.selectors.inStack(o,t)],[i,t]));return Pn(()=>{if(s)return i.actions.push(t),()=>i.actions.pop(t)},[i,s,t]),s?r?n:!0:!1}let Rv=new Map,Qd=new Map;function oS(s){var e;let t=(e=Qd.get(s))!=null?e:0;return Qd.set(s,t+1),t!==0?()=>lS(s):(Rv.set(s,{"aria-hidden":s.getAttribute("aria-hidden"),inert:s.inert}),s.setAttribute("aria-hidden","true"),s.inert=!0,()=>lS(s))}function lS(s){var e;let t=(e=Qd.get(s))!=null?e:1;if(t===1?Qd.delete(s):Qd.set(s,t-1),t!==1)return;let i=Rv.get(s);i&&(i["aria-hidden"]===null?s.removeAttribute("aria-hidden"):s.setAttribute("aria-hidden",i["aria-hidden"]),s.inert=i.inert,Rv.delete(s))}function oN(s,{allowed:e,disallowed:t}={}){let i=Ah(s,"inert-others");Pn(()=>{var n,r;if(!i)return;let o=Ka();for(let c of(n=t?.())!=null?n:[])c&&o.add(oS(c));let u=(r=e?.())!=null?r:[];for(let c of u){if(!c)continue;let d=Eh(c);if(!d)continue;let f=c.parentElement;for(;f&&f!==d.body;){for(let p of f.children)u.some(g=>p.contains(g))||o.add(oS(p));f=f.parentElement}}return o.dispose},[i,e,t])}function lN(s,e,t){let i=Wl(n=>{let r=n.getBoundingClientRect();r.x===0&&r.y===0&&r.width===0&&r.height===0&&t()});k.useEffect(()=>{if(!s)return;let n=e===null?null:zl(e)?e:e.current;if(!n)return;let r=Ka();if(typeof ResizeObserver<"u"){let o=new ResizeObserver(()=>i.current(n));o.observe(n),r.add(()=>o.disconnect())}if(typeof IntersectionObserver<"u"){let o=new IntersectionObserver(()=>i.current(n));o.observe(n),r.add(()=>o.disconnect())}return()=>r.dispose()},[e,i,s])}let Km=["[contentEditable=true]","[tabindex]","a[href]","area[href]","button:not([disabled])","iframe","input:not([disabled])","select:not([disabled])","details>summary","textarea:not([disabled])"].map(s=>`${s}:not([tabindex='-1'])`).join(","),uN=["[data-autofocus]"].map(s=>`${s}:not([tabindex='-1'])`).join(",");var Ua=(s=>(s[s.First=1]="First",s[s.Previous=2]="Previous",s[s.Next=4]="Next",s[s.Last=8]="Last",s[s.WrapAround=16]="WrapAround",s[s.NoScroll=32]="NoScroll",s[s.AutoFocus=64]="AutoFocus",s))(Ua||{}),Iv=(s=>(s[s.Error=0]="Error",s[s.Overflow=1]="Overflow",s[s.Success=2]="Success",s[s.Underflow=3]="Underflow",s))(Iv||{}),cN=(s=>(s[s.Previous=-1]="Previous",s[s.Next=1]="Next",s))(cN||{});function dN(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(Km)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}function hN(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(uN)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var Qw=(s=>(s[s.Strict=0]="Strict",s[s.Loose=1]="Loose",s))(Qw||{});function fN(s,e=0){var t;return s===((t=Eh(s))==null?void 0:t.body)?!1:Ga(e,{0(){return s.matches(Km)},1(){let i=s;for(;i!==null;){if(i.matches(Km))return!0;i=i.parentElement}return!1}})}var mN=(s=>(s[s.Keyboard=0]="Keyboard",s[s.Mouse=1]="Mouse",s))(mN||{});typeof window<"u"&&typeof document<"u"&&(document.addEventListener("keydown",s=>{s.metaKey||s.altKey||s.ctrlKey||(document.documentElement.dataset.headlessuiFocusVisible="")},!0),document.addEventListener("click",s=>{s.detail===1?delete document.documentElement.dataset.headlessuiFocusVisible:s.detail===0&&(document.documentElement.dataset.headlessuiFocusVisible="")},!0));function Ha(s){s?.focus({preventScroll:!0})}let pN=["textarea","input"].join(",");function gN(s){var e,t;return(t=(e=s?.matches)==null?void 0:e.call(s,pN))!=null?t:!1}function yN(s,e=t=>t){return s.slice().sort((t,i)=>{let n=e(t),r=e(i);if(n===null||r===null)return 0;let o=n.compareDocumentPosition(r);return o&Node.DOCUMENT_POSITION_FOLLOWING?-1:o&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function Zd(s,e,{sorted:t=!0,relativeTo:i=null,skipElements:n=[]}={}){let r=Array.isArray(s)?s.length>0?kv(s[0]):document:kv(s),o=Array.isArray(s)?t?yN(s):s:e&64?hN(s):dN(s);n.length>0&&o.length>1&&(o=o.filter(y=>!n.some(x=>x!=null&&"current"in x?x?.current===y:x===y))),i=i??r?.activeElement;let u=(()=>{if(e&5)return 1;if(e&10)return-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),c=(()=>{if(e&1)return 0;if(e&2)return Math.max(0,o.indexOf(i))-1;if(e&4)return Math.max(0,o.indexOf(i))+1;if(e&8)return o.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),d=e&32?{preventScroll:!0}:{},f=0,p=o.length,g;do{if(f>=p||f+p<=0)return 0;let y=c+f;if(e&16)y=(y+p)%p;else{if(y<0)return 3;if(y>=p)return 1}g=o[y],g?.focus(d),f+=u}while(g!==jw(g));return e&6&&gN(g)&&g.select(),2}function Zw(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function vN(){return/Android/gi.test(window.navigator.userAgent)}function uS(){return Zw()||vN()}function sm(s,e,t,i){let n=Wl(t);k.useEffect(()=>{if(!s)return;function r(o){n.current(o)}return document.addEventListener(e,r,i),()=>document.removeEventListener(e,r,i)},[s,e,i])}function Jw(s,e,t,i){let n=Wl(t);k.useEffect(()=>{if(!s)return;function r(o){n.current(o)}return window.addEventListener(e,r,i),()=>window.removeEventListener(e,r,i)},[s,e,i])}const cS=30;function xN(s,e,t){let i=Wl(t),n=k.useCallback(function(u,c){if(u.defaultPrevented)return;let d=c(u);if(d===null||!d.getRootNode().contains(d)||!d.isConnected)return;let f=(function p(g){return typeof g=="function"?p(g()):Array.isArray(g)||g instanceof Set?g:[g]})(e);for(let p of f)if(p!==null&&(p.contains(d)||u.composed&&u.composedPath().includes(p)))return;return!fN(d,Qw.Loose)&&d.tabIndex!==-1&&u.preventDefault(),i.current(u,d)},[i,e]),r=k.useRef(null);sm(s,"pointerdown",u=>{var c,d;uS()||(r.current=((d=(c=u.composedPath)==null?void 0:c.call(u))==null?void 0:d[0])||u.target)},!0),sm(s,"pointerup",u=>{if(uS()||!r.current)return;let c=r.current;return r.current=null,n(u,()=>c)},!0);let o=k.useRef({x:0,y:0});sm(s,"touchstart",u=>{o.current.x=u.touches[0].clientX,o.current.y=u.touches[0].clientY},!0),sm(s,"touchend",u=>{let c={x:u.changedTouches[0].clientX,y:u.changedTouches[0].clientY};if(!(Math.abs(c.x-o.current.x)>=cS||Math.abs(c.y-o.current.y)>=cS))return n(u,()=>Go(u.target)?u.target:null)},!0),Jw(s,"blur",u=>n(u,()=>FI(window.document.activeElement)?window.document.activeElement:null),!0)}function Ox(...s){return k.useMemo(()=>Eh(...s),[...s])}function eA(s,e,t,i){let n=Wl(t);k.useEffect(()=>{s=s??window;function r(o){n.current(o)}return s.addEventListener(e,r,i),()=>s.removeEventListener(e,r,i)},[s,e,i])}function bN(s){return k.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getSnapshot)}function TN(s,e){let t=s(),i=new Set;return{getSnapshot(){return t},subscribe(n){return i.add(n),()=>i.delete(n)},dispatch(n,...r){let o=e[n].call(t,...r);o&&(t=o,i.forEach(u=>u()))}}}function _N(){let s;return{before({doc:e}){var t;let i=e.documentElement,n=(t=e.defaultView)!=null?t:window;s=Math.max(0,n.innerWidth-i.clientWidth)},after({doc:e,d:t}){let i=e.documentElement,n=Math.max(0,i.clientWidth-i.offsetWidth),r=Math.max(0,s-n);t.style(i,"paddingRight",`${r}px`)}}}function SN(){return Zw()?{before({doc:s,d:e,meta:t}){function i(n){for(let r of t().containers)for(let o of r())if(o.contains(n))return!0;return!1}e.microTask(()=>{var n;if(window.getComputedStyle(s.documentElement).scrollBehavior!=="auto"){let u=Ka();u.style(s.documentElement,"scrollBehavior","auto"),e.add(()=>e.microTask(()=>u.dispose()))}let r=(n=window.scrollY)!=null?n:window.pageYOffset,o=null;e.addEventListener(s,"click",u=>{if(Go(u.target))try{let c=u.target.closest("a");if(!c)return;let{hash:d}=new URL(c.href),f=s.querySelector(d);Go(f)&&!i(f)&&(o=f)}catch{}},!0),e.group(u=>{e.addEventListener(s,"touchstart",c=>{if(u.dispose(),Go(c.target)&&BI(c.target))if(i(c.target)){let d=c.target;for(;d.parentElement&&i(d.parentElement);)d=d.parentElement;u.style(d,"overscrollBehavior","contain")}else u.style(c.target,"touchAction","none")})}),e.addEventListener(s,"touchmove",u=>{if(Go(u.target)){if(UI(u.target))return;if(i(u.target)){let c=u.target;for(;c.parentElement&&c.dataset.headlessuiPortal!==""&&!(c.scrollHeight>c.clientHeight||c.scrollWidth>c.clientWidth);)c=c.parentElement;c.dataset.headlessuiPortal===""&&u.preventDefault()}else u.preventDefault()}},{passive:!1}),e.add(()=>{var u;let c=(u=window.scrollY)!=null?u:window.pageYOffset;r!==c&&window.scrollTo(0,r),o&&o.isConnected&&(o.scrollIntoView({block:"nearest"}),o=null)})})}}:{}}function EN(){return{before({doc:s,d:e}){e.style(s.documentElement,"overflow","hidden")}}}function dS(s){let e={};for(let t of s)Object.assign(e,t(e));return e}let Pl=TN(()=>new Map,{PUSH(s,e){var t;let i=(t=this.get(s))!=null?t:{doc:s,count:0,d:Ka(),meta:new Set,computedMeta:{}};return i.count++,i.meta.add(e),i.computedMeta=dS(i.meta),this.set(s,i),this},POP(s,e){let t=this.get(s);return t&&(t.count--,t.meta.delete(e),t.computedMeta=dS(t.meta)),this},SCROLL_PREVENT(s){let e={doc:s.doc,d:s.d,meta(){return s.computedMeta}},t=[SN(),_N(),EN()];t.forEach(({before:i})=>i?.(e)),t.forEach(({after:i})=>i?.(e))},SCROLL_ALLOW({d:s}){s.dispose()},TEARDOWN({doc:s}){this.delete(s)}});Pl.subscribe(()=>{let s=Pl.getSnapshot(),e=new Map;for(let[t]of s)e.set(t,t.documentElement.style.overflow);for(let t of s.values()){let i=e.get(t.doc)==="hidden",n=t.count!==0;(n&&!i||!n&&i)&&Pl.dispatch(t.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",t),t.count===0&&Pl.dispatch("TEARDOWN",t)}});function wN(s,e,t=()=>({containers:[]})){let i=bN(Pl),n=e?i.get(e):void 0,r=n?n.count>0:!1;return Pn(()=>{if(!(!e||!s))return Pl.dispatch("PUSH",e,t),()=>Pl.dispatch("POP",e,t)},[s,e]),r}function AN(s,e,t=()=>[document.body]){let i=Ah(s,"scroll-lock");wN(i,e,n=>{var r;return{containers:[...(r=n.containers)!=null?r:[],t]}})}function CN(s=0){let[e,t]=k.useState(s),i=k.useCallback(c=>t(c),[]),n=k.useCallback(c=>t(d=>d|c),[]),r=k.useCallback(c=>(e&c)===c,[e]),o=k.useCallback(c=>t(d=>d&~c),[]),u=k.useCallback(c=>t(d=>d^c),[]);return{flags:e,setFlag:i,addFlag:n,hasFlag:r,removeFlag:o,toggleFlag:u}}var kN={},hS,fS;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((hS=process==null?void 0:kN)==null?void 0:hS.NODE_ENV)==="test"&&typeof((fS=Element?.prototype)==null?void 0:fS.getAnimations)>"u"&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` +`)),[]});var DN=(s=>(s[s.None=0]="None",s[s.Closed=1]="Closed",s[s.Enter=2]="Enter",s[s.Leave=4]="Leave",s))(DN||{});function LN(s){let e={};for(let t in s)s[t]===!0&&(e[`data-${t}`]="");return e}function RN(s,e,t,i){let[n,r]=k.useState(t),{hasFlag:o,addFlag:u,removeFlag:c}=CN(s&&n?3:0),d=k.useRef(!1),f=k.useRef(!1),p=Lp();return Pn(()=>{var g;if(s){if(t&&r(!0),!e){t&&u(3);return}return(g=i?.start)==null||g.call(i,t),IN(e,{inFlight:d,prepare(){f.current?f.current=!1:f.current=d.current,d.current=!0,!f.current&&(t?(u(3),c(4)):(u(4),c(2)))},run(){f.current?t?(c(3),u(4)):(c(4),u(3)):t?c(1):u(1)},done(){var y;f.current&&MN(e)||(d.current=!1,c(7),t||r(!1),(y=i?.end)==null||y.call(i,t))}})}},[s,t,e,p]),s?[n,{closed:o(1),enter:o(2),leave:o(4),transition:o(2)||o(4)}]:[t,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function IN(s,{prepare:e,run:t,done:i,inFlight:n}){let r=Ka();return ON(s,{prepare:e,inFlight:n}),r.nextFrame(()=>{t(),r.requestAnimationFrame(()=>{r.add(NN(s,i))})}),r.dispose}function NN(s,e){var t,i;let n=Ka();if(!s)return n.dispose;let r=!1;n.add(()=>{r=!0});let o=(i=(t=s.getAnimations)==null?void 0:t.call(s).filter(u=>u instanceof CSSTransition))!=null?i:[];return o.length===0?(e(),n.dispose):(Promise.allSettled(o.map(u=>u.finished)).then(()=>{r||e()}),n.dispose)}function ON(s,{inFlight:e,prepare:t}){if(e!=null&&e.current){t();return}let i=s.style.transition;s.style.transition="none",t(),s.offsetHeight,s.style.transition=i}function MN(s){var e,t;return((t=(e=s.getAnimations)==null?void 0:e.call(s))!=null?t:[]).some(i=>i instanceof CSSTransition&&i.playState!=="finished")}function Mx(s,e){let t=k.useRef([]),i=Ki(s);k.useEffect(()=>{let n=[...t.current];for(let[r,o]of e.entries())if(t.current[r]!==o){let u=i(e,n);return t.current=e,u}},[i,...e])}let Rp=k.createContext(null);Rp.displayName="OpenClosedContext";var Cr=(s=>(s[s.Open=1]="Open",s[s.Closed=2]="Closed",s[s.Closing=4]="Closing",s[s.Opening=8]="Opening",s))(Cr||{});function Ip(){return k.useContext(Rp)}function PN({value:s,children:e}){return Bt.createElement(Rp.Provider,{value:s},e)}function BN({children:s}){return Bt.createElement(Rp.Provider,{value:null},s)}function FN(s){function e(){document.readyState!=="loading"&&(s(),document.removeEventListener("DOMContentLoaded",e))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",e),e())}let Ho=[];FN(()=>{function s(e){if(!Go(e.target)||e.target===document.body||Ho[0]===e.target)return;let t=e.target;t=t.closest(Km),Ho.unshift(t??e.target),Ho=Ho.filter(i=>i!=null&&i.isConnected),Ho.splice(10)}window.addEventListener("click",s,{capture:!0}),window.addEventListener("mousedown",s,{capture:!0}),window.addEventListener("focus",s,{capture:!0}),document.body.addEventListener("click",s,{capture:!0}),document.body.addEventListener("mousedown",s,{capture:!0}),document.body.addEventListener("focus",s,{capture:!0})});function tA(s){let e=Ki(s),t=k.useRef(!1);k.useEffect(()=>(t.current=!1,()=>{t.current=!0,Dp(()=>{t.current&&e()})}),[e])}let iA=k.createContext(!1);function UN(){return k.useContext(iA)}function mS(s){return Bt.createElement(iA.Provider,{value:s.force},s.children)}function jN(s){let e=UN(),t=k.useContext(nA),[i,n]=k.useState(()=>{var r;if(!e&&t!==null)return(r=t.current)!=null?r:null;if(oa.isServer)return null;let o=s?.getElementById("headlessui-portal-root");if(o)return o;if(s===null)return null;let u=s.createElement("div");return u.setAttribute("id","headlessui-portal-root"),s.body.appendChild(u)});return k.useEffect(()=>{i!==null&&(s!=null&&s.body.contains(i)||s==null||s.body.appendChild(i))},[i,s]),k.useEffect(()=>{e||t!==null&&n(t.current)},[t,n,e]),i}let sA=k.Fragment,$N=Fn(function(s,e){let{ownerDocument:t=null,...i}=s,n=k.useRef(null),r=ma(jI(g=>{n.current=g}),e),o=Ox(n.current),u=t??o,c=jN(u),d=k.useContext(Nv),f=Lp(),p=mr();return tA(()=>{var g;c&&c.childNodes.length<=0&&((g=c.parentElement)==null||g.removeChild(c))}),c?Sh.createPortal(Bt.createElement("div",{"data-headlessui-portal":"",ref:g=>{f.dispose(),d&&g&&f.add(d.register(g))}},p({ourProps:{ref:r},theirProps:i,slot:{},defaultTag:sA,name:"Portal"})),c):null});function HN(s,e){let t=ma(e),{enabled:i=!0,ownerDocument:n,...r}=s,o=mr();return i?Bt.createElement($N,{...r,ownerDocument:n,ref:t}):o({ourProps:{ref:t},theirProps:r,slot:{},defaultTag:sA,name:"Portal"})}let VN=k.Fragment,nA=k.createContext(null);function GN(s,e){let{target:t,...i}=s,n={ref:ma(e)},r=mr();return Bt.createElement(nA.Provider,{value:t},r({ourProps:n,theirProps:i,defaultTag:VN,name:"Popover.Group"}))}let Nv=k.createContext(null);function zN(){let s=k.useContext(Nv),e=k.useRef([]),t=Ki(r=>(e.current.push(r),s&&s.register(r),()=>i(r))),i=Ki(r=>{let o=e.current.indexOf(r);o!==-1&&e.current.splice(o,1),s&&s.unregister(r)}),n=k.useMemo(()=>({register:t,unregister:i,portals:e}),[t,i,e]);return[e,k.useMemo(()=>function({children:r}){return Bt.createElement(Nv.Provider,{value:n},r)},[n])]}let qN=Fn(HN),rA=Fn(GN),KN=Object.assign(qN,{Group:rA});function YN(s,e=typeof document<"u"?document.defaultView:null,t){let i=Ah(s,"escape");eA(e,"keydown",n=>{i&&(n.defaultPrevented||n.key===Gw.Escape&&t(n))})}function WN(){var s;let[e]=k.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null),[t,i]=k.useState((s=e?.matches)!=null?s:!1);return Pn(()=>{if(!e)return;function n(r){i(r.matches)}return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[e]),t}function XN({defaultContainers:s=[],portals:e,mainTreeNode:t}={}){let i=Ki(()=>{var n,r;let o=Eh(t),u=[];for(let c of s)c!==null&&(zo(c)?u.push(c):"current"in c&&zo(c.current)&&u.push(c.current));if(e!=null&&e.current)for(let c of e.current)u.push(c);for(let c of(n=o?.querySelectorAll("html > *, body > *"))!=null?n:[])c!==document.body&&c!==document.head&&zo(c)&&c.id!=="headlessui-portal-root"&&(t&&(c.contains(t)||c.contains((r=t?.getRootNode())==null?void 0:r.host))||u.some(d=>c.contains(d))||u.push(c));return u});return{resolveContainers:i,contains:Ki(n=>i().some(r=>r.contains(n)))}}let aA=k.createContext(null);function pS({children:s,node:e}){let[t,i]=k.useState(null),n=oA(e??t);return Bt.createElement(aA.Provider,{value:n},s,n===null&&Bt.createElement(Lv,{features:qm.Hidden,ref:r=>{var o,u;if(r){for(let c of(u=(o=Eh(r))==null?void 0:o.querySelectorAll("html > *, body > *"))!=null?u:[])if(c!==document.body&&c!==document.head&&zo(c)&&c!=null&&c.contains(r)){i(c);break}}}}))}function oA(s=null){var e;return(e=k.useContext(aA))!=null?e:s}function QN(){let s=typeof document>"u";return"useSyncExternalStore"in W_?(e=>e.useSyncExternalStore)(W_)(()=>()=>{},()=>!1,()=>!s):!1}function Np(){let s=QN(),[e,t]=k.useState(oa.isHandoffComplete);return e&&oa.isHandoffComplete===!1&&t(!1),k.useEffect(()=>{e!==!0&&t(!0)},[e]),k.useEffect(()=>oa.handoff(),[]),s?!1:e}function Px(){let s=k.useRef(!1);return Pn(()=>(s.current=!0,()=>{s.current=!1}),[]),s}var zd=(s=>(s[s.Forwards=0]="Forwards",s[s.Backwards=1]="Backwards",s))(zd||{});function ZN(){let s=k.useRef(0);return Jw(!0,"keydown",e=>{e.key==="Tab"&&(s.current=e.shiftKey?1:0)},!0),s}function lA(s){if(!s)return new Set;if(typeof s=="function")return new Set(s());let e=new Set;for(let t of s.current)zo(t.current)&&e.add(t.current);return e}let JN="div";var Ol=(s=>(s[s.None=0]="None",s[s.InitialFocus=1]="InitialFocus",s[s.TabLock=2]="TabLock",s[s.FocusLock=4]="FocusLock",s[s.RestoreFocus=8]="RestoreFocus",s[s.AutoFocus=16]="AutoFocus",s))(Ol||{});function e5(s,e){let t=k.useRef(null),i=ma(t,e),{initialFocus:n,initialFocusFallback:r,containers:o,features:u=15,...c}=s;Np()||(u=0);let d=Ox(t.current);n5(u,{ownerDocument:d});let f=r5(u,{ownerDocument:d,container:t,initialFocus:n,initialFocusFallback:r});a5(u,{ownerDocument:d,container:t,containers:o,previousActiveElement:f});let p=ZN(),g=Ki(I=>{if(!zl(t.current))return;let L=t.current;(B=>B())(()=>{Ga(p.current,{[zd.Forwards]:()=>{Zd(L,Ua.First,{skipElements:[I.relatedTarget,r]})},[zd.Backwards]:()=>{Zd(L,Ua.Last,{skipElements:[I.relatedTarget,r]})}})})}),y=Ah(!!(u&2),"focus-trap#tab-lock"),x=Lp(),_=k.useRef(!1),w={ref:i,onKeyDown(I){I.key=="Tab"&&(_.current=!0,x.requestAnimationFrame(()=>{_.current=!1}))},onBlur(I){if(!(u&4))return;let L=lA(o);zl(t.current)&&L.add(t.current);let B=I.relatedTarget;Go(B)&&B.dataset.headlessuiFocusGuard!=="true"&&(uA(L,B)||(_.current?Zd(t.current,Ga(p.current,{[zd.Forwards]:()=>Ua.Next,[zd.Backwards]:()=>Ua.Previous})|Ua.WrapAround,{relativeTo:I.target}):Go(I.target)&&Ha(I.target)))}},D=mr();return Bt.createElement(Bt.Fragment,null,y&&Bt.createElement(Lv,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:g,features:qm.Focusable}),D({ourProps:w,theirProps:c,defaultTag:JN,name:"FocusTrap"}),y&&Bt.createElement(Lv,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:g,features:qm.Focusable}))}let t5=Fn(e5),i5=Object.assign(t5,{features:Ol});function s5(s=!0){let e=k.useRef(Ho.slice());return Mx(([t],[i])=>{i===!0&&t===!1&&Dp(()=>{e.current.splice(0)}),i===!1&&t===!0&&(e.current=Ho.slice())},[s,Ho,e]),Ki(()=>{var t;return(t=e.current.find(i=>i!=null&&i.isConnected))!=null?t:null})}function n5(s,{ownerDocument:e}){let t=!!(s&8),i=s5(t);Mx(()=>{t||AI(e?.body)&&Ha(i())},[t]),tA(()=>{t&&Ha(i())})}function r5(s,{ownerDocument:e,container:t,initialFocus:i,initialFocusFallback:n}){let r=k.useRef(null),o=Ah(!!(s&1),"focus-trap#initial-focus"),u=Px();return Mx(()=>{if(s===0)return;if(!o){n!=null&&n.current&&Ha(n.current);return}let c=t.current;c&&Dp(()=>{if(!u.current)return;let d=e?.activeElement;if(i!=null&&i.current){if(i?.current===d){r.current=d;return}}else if(c.contains(d)){r.current=d;return}if(i!=null&&i.current)Ha(i.current);else{if(s&16){if(Zd(c,Ua.First|Ua.AutoFocus)!==Iv.Error)return}else if(Zd(c,Ua.First)!==Iv.Error)return;if(n!=null&&n.current&&(Ha(n.current),e?.activeElement===n.current))return;console.warn("There are no focusable elements inside the ")}r.current=e?.activeElement})},[n,o,s]),r}function a5(s,{ownerDocument:e,container:t,containers:i,previousActiveElement:n}){let r=Px(),o=!!(s&4);eA(e?.defaultView,"focus",u=>{if(!o||!r.current)return;let c=lA(i);zl(t.current)&&c.add(t.current);let d=n.current;if(!d)return;let f=u.target;zl(f)?uA(c,f)?(n.current=f,Ha(f)):(u.preventDefault(),u.stopPropagation(),Ha(d)):Ha(n.current)},!0)}function uA(s,e){for(let t of s)if(t.contains(e))return!0;return!1}function cA(s){var e;return!!(s.enter||s.enterFrom||s.enterTo||s.leave||s.leaveFrom||s.leaveTo)||!Xd((e=s.as)!=null?e:hA)||Bt.Children.count(s.children)===1}let Op=k.createContext(null);Op.displayName="TransitionContext";var o5=(s=>(s.Visible="visible",s.Hidden="hidden",s))(o5||{});function l5(){let s=k.useContext(Op);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}function u5(){let s=k.useContext(Mp);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}let Mp=k.createContext(null);Mp.displayName="NestingContext";function Pp(s){return"children"in s?Pp(s.children):s.current.filter(({el:e})=>e.current!==null).filter(({state:e})=>e==="visible").length>0}function dA(s,e){let t=Wl(s),i=k.useRef([]),n=Px(),r=Lp(),o=Ki((y,x=Vo.Hidden)=>{let _=i.current.findIndex(({el:w})=>w===y);_!==-1&&(Ga(x,{[Vo.Unmount](){i.current.splice(_,1)},[Vo.Hidden](){i.current[_].state="hidden"}}),r.microTask(()=>{var w;!Pp(i)&&n.current&&((w=t.current)==null||w.call(t))}))}),u=Ki(y=>{let x=i.current.find(({el:_})=>_===y);return x?x.state!=="visible"&&(x.state="visible"):i.current.push({el:y,state:"visible"}),()=>o(y,Vo.Unmount)}),c=k.useRef([]),d=k.useRef(Promise.resolve()),f=k.useRef({enter:[],leave:[]}),p=Ki((y,x,_)=>{c.current.splice(0),e&&(e.chains.current[x]=e.chains.current[x].filter(([w])=>w!==y)),e?.chains.current[x].push([y,new Promise(w=>{c.current.push(w)})]),e?.chains.current[x].push([y,new Promise(w=>{Promise.all(f.current[x].map(([D,I])=>I)).then(()=>w())})]),x==="enter"?d.current=d.current.then(()=>e?.wait.current).then(()=>_(x)):_(x)}),g=Ki((y,x,_)=>{Promise.all(f.current[x].splice(0).map(([w,D])=>D)).then(()=>{var w;(w=c.current.shift())==null||w()}).then(()=>_(x))});return k.useMemo(()=>({children:i,register:u,unregister:o,onStart:p,onStop:g,wait:d,chains:f}),[u,o,i,p,g,f,d])}let hA=k.Fragment,fA=zm.RenderStrategy;function c5(s,e){var t,i;let{transition:n=!0,beforeEnter:r,afterEnter:o,beforeLeave:u,afterLeave:c,enter:d,enterFrom:f,enterTo:p,entered:g,leave:y,leaveFrom:x,leaveTo:_,...w}=s,[D,I]=k.useState(null),L=k.useRef(null),B=cA(s),j=ma(...B?[L,e,I]:e===null?[]:[e]),V=(t=w.unmount)==null||t?Vo.Unmount:Vo.Hidden,{show:M,appear:z,initial:O}=l5(),[N,q]=k.useState(M?"visible":"hidden"),Q=u5(),{register:Y,unregister:re}=Q;Pn(()=>Y(L),[Y,L]),Pn(()=>{if(V===Vo.Hidden&&L.current){if(M&&N!=="visible"){q("visible");return}return Ga(N,{hidden:()=>re(L),visible:()=>Y(L)})}},[N,L,Y,re,M,V]);let Z=Np();Pn(()=>{if(B&&Z&&N==="visible"&&L.current===null)throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[L,N,Z,B]);let H=O&&!z,K=z&&M&&O,ie=k.useRef(!1),te=dA(()=>{ie.current||(q("hidden"),re(L))},Q),ne=Ki(Me=>{ie.current=!0;let et=Me?"enter":"leave";te.onStart(L,et,Ge=>{Ge==="enter"?r?.():Ge==="leave"&&u?.()})}),$=Ki(Me=>{let et=Me?"enter":"leave";ie.current=!1,te.onStop(L,et,Ge=>{Ge==="enter"?o?.():Ge==="leave"&&c?.()}),et==="leave"&&!Pp(te)&&(q("hidden"),re(L))});k.useEffect(()=>{B&&n||(ne(M),$(M))},[M,B,n]);let ee=!(!n||!B||!Z||H),[,le]=RN(ee,D,M,{start:ne,end:$}),be=Rl({ref:j,className:((i=Dv(w.className,K&&d,K&&f,le.enter&&d,le.enter&&le.closed&&f,le.enter&&!le.closed&&p,le.leave&&y,le.leave&&!le.closed&&x,le.leave&&le.closed&&_,!le.transition&&M&&g))==null?void 0:i.trim())||void 0,...LN(le)}),fe=0;N==="visible"&&(fe|=Cr.Open),N==="hidden"&&(fe|=Cr.Closed),M&&N==="hidden"&&(fe|=Cr.Opening),!M&&N==="visible"&&(fe|=Cr.Closing);let _e=mr();return Bt.createElement(Mp.Provider,{value:te},Bt.createElement(PN,{value:fe},_e({ourProps:be,theirProps:w,defaultTag:hA,features:fA,visible:N==="visible",name:"Transition.Child"})))}function d5(s,e){let{show:t,appear:i=!1,unmount:n=!0,...r}=s,o=k.useRef(null),u=cA(s),c=ma(...u?[o,e]:e===null?[]:[e]);Np();let d=Ip();if(t===void 0&&d!==null&&(t=(d&Cr.Open)===Cr.Open),t===void 0)throw new Error("A is used but it is missing a `show={true | false}` prop.");let[f,p]=k.useState(t?"visible":"hidden"),g=dA(()=>{t||p("hidden")}),[y,x]=k.useState(!0),_=k.useRef([t]);Pn(()=>{y!==!1&&_.current[_.current.length-1]!==t&&(_.current.push(t),x(!1))},[_,t]);let w=k.useMemo(()=>({show:t,appear:i,initial:y}),[t,i,y]);Pn(()=>{t?p("visible"):!Pp(g)&&o.current!==null&&p("hidden")},[t,g]);let D={unmount:n},I=Ki(()=>{var j;y&&x(!1),(j=s.beforeEnter)==null||j.call(s)}),L=Ki(()=>{var j;y&&x(!1),(j=s.beforeLeave)==null||j.call(s)}),B=mr();return Bt.createElement(Mp.Provider,{value:g},Bt.createElement(Op.Provider,{value:w},B({ourProps:{...D,as:k.Fragment,children:Bt.createElement(mA,{ref:c,...D,...r,beforeEnter:I,beforeLeave:L})},theirProps:{},defaultTag:k.Fragment,features:fA,visible:f==="visible",name:"Transition"})))}function h5(s,e){let t=k.useContext(Op)!==null,i=Ip()!==null;return Bt.createElement(Bt.Fragment,null,!t&&i?Bt.createElement(Ov,{ref:e,...s}):Bt.createElement(mA,{ref:e,...s}))}let Ov=Fn(d5),mA=Fn(c5),Bx=Fn(h5),Jd=Object.assign(Ov,{Child:Bx,Root:Ov});var f5=(s=>(s[s.Open=0]="Open",s[s.Closed=1]="Closed",s))(f5||{}),m5=(s=>(s[s.SetTitleId=0]="SetTitleId",s))(m5||{});let p5={0(s,e){return s.titleId===e.id?s:{...s,titleId:e.id}}},Fx=k.createContext(null);Fx.displayName="DialogContext";function Bp(s){let e=k.useContext(Fx);if(e===null){let t=new Error(`<${s} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,Bp),t}return e}function g5(s,e){return Ga(e.type,p5,s,e)}let gS=Fn(function(s,e){let t=k.useId(),{id:i=`headlessui-dialog-${t}`,open:n,onClose:r,initialFocus:o,role:u="dialog",autoFocus:c=!0,__demoMode:d=!1,unmount:f=!1,...p}=s,g=k.useRef(!1);u=(function(){return u==="dialog"||u==="alertdialog"?u:(g.current||(g.current=!0,console.warn(`Invalid role [${u}] passed to . Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`)),"dialog")})();let y=Ip();n===void 0&&y!==null&&(n=(y&Cr.Open)===Cr.Open);let x=k.useRef(null),_=ma(x,e),w=Ox(x.current),D=n?0:1,[I,L]=k.useReducer(g5,{titleId:null,descriptionId:null,panelRef:k.createRef()}),B=Ki(()=>r(!1)),j=Ki(le=>L({type:0,id:le})),V=Np()?D===0:!1,[M,z]=zN(),O={get current(){var le;return(le=I.panelRef.current)!=null?le:x.current}},N=oA(),{resolveContainers:q}=XN({mainTreeNode:N,portals:M,defaultContainers:[O]}),Q=y!==null?(y&Cr.Closing)===Cr.Closing:!1;oN(d||Q?!1:V,{allowed:Ki(()=>{var le,be;return[(be=(le=x.current)==null?void 0:le.closest("[data-headlessui-portal]"))!=null?be:null]}),disallowed:Ki(()=>{var le;return[(le=N?.closest("body > *:not(#headlessui-portal-root)"))!=null?le:null]})});let Y=Ww.get(null);Pn(()=>{if(V)return Y.actions.push(i),()=>Y.actions.pop(i)},[Y,i,V]);let re=Xw(Y,k.useCallback(le=>Y.selectors.isTop(le,i),[Y,i]));xN(re,q,le=>{le.preventDefault(),B()}),YN(re,w?.defaultView,le=>{le.preventDefault(),le.stopPropagation(),document.activeElement&&"blur"in document.activeElement&&typeof document.activeElement.blur=="function"&&document.activeElement.blur(),B()}),AN(d||Q?!1:V,w,q),lN(V,x,B);let[Z,H]=$I(),K=k.useMemo(()=>[{dialogState:D,close:B,setTitleId:j,unmount:f},I],[D,B,j,f,I]),ie=wh({open:D===0}),te={ref:_,id:i,role:u,tabIndex:-1,"aria-modal":d?void 0:D===0?!0:void 0,"aria-labelledby":I.titleId,"aria-describedby":Z,unmount:f},ne=!WN(),$=Ol.None;V&&!d&&($|=Ol.RestoreFocus,$|=Ol.TabLock,c&&($|=Ol.AutoFocus),ne&&($|=Ol.InitialFocus));let ee=mr();return Bt.createElement(BN,null,Bt.createElement(mS,{force:!0},Bt.createElement(KN,null,Bt.createElement(Fx.Provider,{value:K},Bt.createElement(rA,{target:x},Bt.createElement(mS,{force:!1},Bt.createElement(H,{slot:ie},Bt.createElement(z,null,Bt.createElement(i5,{initialFocus:o,initialFocusFallback:x,containers:q,features:$},Bt.createElement(KI,{value:B},ee({ourProps:te,theirProps:p,slot:ie,defaultTag:y5,features:v5,visible:D===0,name:"Dialog"})))))))))))}),y5="div",v5=zm.RenderStrategy|zm.Static;function x5(s,e){let{transition:t=!1,open:i,...n}=s,r=Ip(),o=s.hasOwnProperty("open")||r!==null,u=s.hasOwnProperty("onClose");if(!o&&!u)throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");if(!o)throw new Error("You provided an `onClose` prop to the `Dialog`, but forgot an `open` prop.");if(!u)throw new Error("You provided an `open` prop to the `Dialog`, but forgot an `onClose` prop.");if(!r&&typeof s.open!="boolean")throw new Error(`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${s.open}`);if(typeof s.onClose!="function")throw new Error(`You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${s.onClose}`);return(i!==void 0||t)&&!n.static?Bt.createElement(pS,null,Bt.createElement(Jd,{show:i,transition:t,unmount:n.unmount},Bt.createElement(gS,{ref:e,...n}))):Bt.createElement(pS,null,Bt.createElement(gS,{ref:e,open:i,...n}))}let b5="div";function T5(s,e){let t=k.useId(),{id:i=`headlessui-dialog-panel-${t}`,transition:n=!1,...r}=s,[{dialogState:o,unmount:u},c]=Bp("Dialog.Panel"),d=ma(e,c.panelRef),f=wh({open:o===0}),p=Ki(w=>{w.stopPropagation()}),g={ref:d,id:i,onClick:p},y=n?Bx:k.Fragment,x=n?{unmount:u}:{},_=mr();return Bt.createElement(y,{...x},_({ourProps:g,theirProps:r,slot:f,defaultTag:b5,name:"Dialog.Panel"}))}let _5="div";function S5(s,e){let{transition:t=!1,...i}=s,[{dialogState:n,unmount:r}]=Bp("Dialog.Backdrop"),o=wh({open:n===0}),u={ref:e,"aria-hidden":!0},c=t?Bx:k.Fragment,d=t?{unmount:r}:{},f=mr();return Bt.createElement(c,{...d},f({ourProps:u,theirProps:i,slot:o,defaultTag:_5,name:"Dialog.Backdrop"}))}let E5="h2";function w5(s,e){let t=k.useId(),{id:i=`headlessui-dialog-title-${t}`,...n}=s,[{dialogState:r,setTitleId:o}]=Bp("Dialog.Title"),u=ma(e);k.useEffect(()=>(o(i),()=>o(null)),[i,o]);let c=wh({open:r===0}),d={ref:u,id:i};return mr()({ourProps:d,theirProps:n,slot:c,defaultTag:E5,name:"Dialog.Title"})}let A5=Fn(x5),C5=Fn(T5);Fn(S5);let k5=Fn(w5),Ju=Object.assign(A5,{Panel:C5,Title:k5,Description:zI});function D5({open:s,onClose:e,onApply:t,initialCookies:i}){const[n,r]=k.useState(""),[o,u]=k.useState(""),[c,d]=k.useState([]),f=k.useRef(!1);k.useEffect(()=>{s&&!f.current&&(r(""),u(""),d(i??[])),f.current=s},[s,i]);function p(){const x=n.trim(),_=o.trim();!x||!_||(d(w=>[...w.filter(I=>I.name!==x),{name:x,value:_}]),r(""),u(""))}function g(x){d(_=>_.filter(w=>w.name!==x))}function y(){t(c),e()}return v.jsxs(Ju,{open:s,onClose:e,className:"relative z-50",children:[v.jsx("div",{className:"fixed inset-0 bg-black/40","aria-hidden":"true"}),v.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:v.jsxs(Ju.Panel,{className:"w-full max-w-lg rounded-lg bg-white dark:bg-gray-800 p-6 shadow-xl dark:outline dark:-outline-offset-1 dark:outline-white/10",children:[v.jsx(Ju.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Zusätzliche Cookies"}),v.jsxs("div",{className:"mt-4 grid grid-cols-1 sm:grid-cols-3 gap-2",children:[v.jsx("input",{value:n,onChange:x=>r(x.target.value),placeholder:"Name (z. B. cf_clearance)",className:"col-span-1 truncate rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),v.jsx("input",{value:o,onChange:x=>u(x.target.value),placeholder:"Wert",className:"col-span-1 truncate sm:col-span-2 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"})]}),v.jsx("div",{className:"mt-2",children:v.jsx(_i,{size:"sm",variant:"secondary",onClick:p,disabled:!n.trim()||!o.trim(),children:"Hinzufügen"})}),v.jsx("div",{className:"mt-4",children:c.length===0?v.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Noch keine Cookies hinzugefügt."}):v.jsxs("table",{className:"min-w-full text-sm border divide-y dark:divide-white/10",children:[v.jsx("thead",{className:"bg-gray-50 dark:bg-gray-700/50",children:v.jsxs("tr",{children:[v.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Name"}),v.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Wert"}),v.jsx("th",{className:"px-3 py-2"})]})}),v.jsx("tbody",{className:"divide-y dark:divide-white/10",children:c.map(x=>v.jsxs("tr",{children:[v.jsx("td",{className:"px-3 py-2 font-mono",children:x.name}),v.jsx("td",{className:"px-3 py-2 truncate max-w-[240px]",children:x.value}),v.jsx("td",{className:"px-3 py-2 text-right",children:v.jsx("button",{onClick:()=>g(x.name),className:"text-xs text-red-600 hover:underline dark:text-red-400",children:"Entfernen"})})]},x.name))})]})}),v.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[v.jsx(_i,{variant:"secondary",onClick:e,children:"Abbrechen"}),v.jsx(_i,{variant:"primary",onClick:y,children:"Übernehmen"})]})]})})]})}function L5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const R5=k.forwardRef(L5);function yS({tabs:s,value:e,onChange:t,className:i,ariaLabel:n="Ansicht auswählen",variant:r="underline",hideCountUntilMd:o=!1}){if(!s?.length)return null;const u=s.find(g=>g.id===e)??s[0],c=Ti("col-start-1 row-start-1 w-full appearance-none rounded-md bg-white py-2 pr-8 pl-3 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600 dark:text-gray-100 dark:outline-white/10 dark:*:bg-gray-800 dark:focus:outline-indigo-500",r==="pillsBrand"?"dark:bg-gray-800/50":"dark:bg-white/5"),d=g=>Ti(g?"bg-indigo-100 text-indigo-600 dark:bg-indigo-500/20 dark:text-indigo-400":"bg-gray-100 text-gray-900 dark:bg-white/10 dark:text-gray-300",o?"ml-3 hidden rounded-full px-2.5 py-0.5 text-xs font-medium md:inline-block":"ml-3 rounded-full px-2.5 py-0.5 text-xs font-medium"),f=(g,y)=>y.count===void 0?null:v.jsx("span",{className:d(g),children:y.count}),p=()=>{switch(r){case"underline":case"underlineIcons":return v.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:v.jsx("nav",{"aria-label":n,className:"-mb-px flex space-x-8",children:s.map(g=>{const y=g.id===u.id,x=!!g.disabled;return v.jsxs("button",{type:"button",onClick:()=>!x&&t(g.id),disabled:x,"aria-current":y?"page":void 0,className:Ti(y?"border-indigo-500 text-indigo-600 dark:border-indigo-400 dark:text-indigo-400":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:border-white/20 dark:hover:text-gray-200",r==="underlineIcons"?"group inline-flex items-center border-b-2 px-1 py-4 text-sm font-medium":"flex items-center border-b-2 px-1 py-4 text-sm font-medium whitespace-nowrap",x&&"cursor-not-allowed opacity-50 hover:border-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[r==="underlineIcons"&&g.icon?v.jsx(g.icon,{"aria-hidden":"true",className:Ti(y?"text-indigo-500 dark:text-indigo-400":"text-gray-400 group-hover:text-gray-500 dark:text-gray-500 dark:group-hover:text-gray-400","mr-2 -ml-0.5 size-5")}):null,v.jsx("span",{children:g.label}),f(y,g)]},g.id)})})});case"pills":case"pillsGray":case"pillsBrand":{const g=r==="pills"?"bg-gray-100 text-gray-700 dark:bg-white/10 dark:text-gray-200":r==="pillsGray"?"bg-gray-200 text-gray-800 dark:bg-white/10 dark:text-white":"bg-indigo-100 text-indigo-700 dark:bg-indigo-500/20 dark:text-indigo-300",y=r==="pills"?"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200":r==="pillsGray"?"text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-white":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200";return v.jsx("nav",{"aria-label":n,className:"flex space-x-4",children:s.map(x=>{const _=x.id===u.id,w=!!x.disabled;return v.jsxs("button",{type:"button",onClick:()=>!w&&t(x.id),disabled:w,"aria-current":_?"page":void 0,className:Ti(_?g:y,"inline-flex items-center rounded-md px-3 py-2 text-sm font-medium",w&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:[v.jsx("span",{children:x.label}),x.count!==void 0?v.jsx("span",{className:Ti(_?"ml-2 bg-white/70 text-gray-900 dark:bg-white/10 dark:text-white":"ml-2 bg-gray-100 text-gray-900 dark:bg-white/10 dark:text-gray-300","rounded-full px-2 py-0.5 text-xs font-medium"),children:x.count}):null]},x.id)})})}case"fullWidthUnderline":return v.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:v.jsx("nav",{"aria-label":n,className:"-mb-px flex",children:s.map(g=>{const y=g.id===u.id,x=!!g.disabled;return v.jsx("button",{type:"button",onClick:()=>!x&&t(g.id),disabled:x,"aria-current":y?"page":void 0,className:Ti(y?"border-indigo-500 text-indigo-600 dark:border-indigo-400 dark:text-indigo-400":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:border-white/20 dark:hover:text-gray-300","flex-1 border-b-2 px-1 py-4 text-center text-sm font-medium",x&&"cursor-not-allowed opacity-50 hover:border-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:g.label},g.id)})})});case"barUnderline":return v.jsx("nav",{"aria-label":n,className:"isolate flex divide-x divide-gray-200 rounded-lg bg-white shadow-sm dark:divide-white/10 dark:bg-gray-800/50 dark:shadow-none dark:outline dark:-outline-offset-1 dark:outline-white/10",children:s.map((g,y)=>{const x=g.id===u.id,_=!!g.disabled;return v.jsxs("button",{type:"button",onClick:()=>!_&&t(g.id),disabled:_,"aria-current":x?"page":void 0,className:Ti(x?"text-gray-900 dark:text-white":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-white",y===0?"rounded-l-lg":"",y===s.length-1?"rounded-r-lg":"","group relative min-w-0 flex-1 overflow-hidden px-4 py-4 text-center text-sm font-medium hover:bg-gray-50 focus:z-10 dark:hover:bg-white/5",_&&"cursor-not-allowed opacity-50 hover:bg-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[v.jsxs("span",{className:"inline-flex items-center justify-center",children:[g.label,g.count!==void 0?v.jsx("span",{className:"ml-2 rounded-full bg-white/70 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-white",children:g.count}):null]}),v.jsx("span",{"aria-hidden":"true",className:Ti(x?"bg-indigo-500 dark:bg-indigo-400":"bg-transparent","absolute inset-x-0 bottom-0 h-0.5")})]},g.id)})});case"simple":return v.jsx("nav",{className:"flex border-b border-gray-200 py-4 dark:border-white/10","aria-label":n,children:v.jsx("ul",{role:"list",className:"flex min-w-full flex-none gap-x-8 px-2 text-sm/6 font-semibold text-gray-500 dark:text-gray-400",children:s.map(g=>{const y=g.id===u.id,x=!!g.disabled;return v.jsx("li",{children:v.jsx("button",{type:"button",onClick:()=>!x&&t(g.id),disabled:x,"aria-current":y?"page":void 0,className:Ti(y?"text-indigo-600 dark:text-indigo-400":"hover:text-gray-700 dark:hover:text-white",x&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:g.label})},g.id)})})});default:return null}};return v.jsxs("div",{className:i,children:[v.jsxs("div",{className:"grid grid-cols-1 sm:hidden",children:[v.jsx("select",{value:u.id,onChange:g=>t(g.target.value),"aria-label":n,className:c,children:s.map(g=>v.jsx("option",{value:g.id,children:g.label},g.id))}),v.jsx(R5,{"aria-hidden":"true",className:"pointer-events-none col-start-1 row-start-1 mr-2 size-5 self-center justify-self-end fill-gray-500 dark:fill-gray-400"})]}),v.jsx("div",{className:"hidden sm:block",children:p()})]})}function za({header:s,footer:e,grayBody:t=!1,grayFooter:i=!1,edgeToEdgeMobile:n=!1,well:r=!1,noBodyPadding:o=!1,className:u,bodyClassName:c,children:d}){const f=r;return v.jsxs("div",{className:Ti("overflow-hidden",n?"sm:rounded-lg":"rounded-lg",f?"bg-gray-50 dark:bg-gray-800 shadow-none":"bg-white shadow-sm dark:bg-gray-800 dark:shadow-none dark:outline dark:-outline-offset-1 dark:outline-white/10",u),children:[s&&v.jsx("div",{className:"shrink-0 px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-white/10",children:s}),v.jsx("div",{className:Ti("min-h-0",o?"p-0":"px-4 py-5 sm:p-6",t&&"bg-gray-50 dark:bg-gray-800",c),children:d}),e&&v.jsx("div",{className:Ti("shrink-0 px-4 py-4 sm:px-6",i&&"bg-gray-50 dark:bg-gray-800/50","border-t border-gray-200 dark:border-white/10"),children:e})]})}function vS({checked:s,onChange:e,id:t,name:i,disabled:n,required:r,ariaLabel:o,ariaLabelledby:u,ariaDescribedby:c,size:d="default",variant:f="simple",className:p}){const g=x=>{n||e(x.target.checked)},y=Ti("absolute inset-0 size-full appearance-none focus:outline-hidden",n&&"cursor-not-allowed");return d==="short"?v.jsxs("div",{className:Ti("group relative inline-flex h-5 w-10 shrink-0 items-center justify-center rounded-full outline-offset-2 outline-indigo-600 has-focus-visible:outline-2 dark:outline-indigo-500",n&&"opacity-60",p),children:[v.jsx("span",{className:Ti("absolute mx-auto h-4 w-9 rounded-full bg-gray-200 inset-ring inset-ring-gray-900/5 transition-colors duration-200 ease-in-out dark:bg-gray-800/50 dark:inset-ring-white/10",s&&"bg-indigo-600 dark:bg-indigo-500")}),v.jsx("span",{className:Ti("absolute left-0 size-5 rounded-full border border-gray-300 bg-white shadow-xs transition-transform duration-200 ease-in-out dark:shadow-none",s&&"translate-x-5")}),v.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:g,disabled:n,required:r,"aria-label":o,"aria-labelledby":u,"aria-describedby":c,className:y})]}):v.jsxs("div",{className:Ti("group relative inline-flex w-11 shrink-0 rounded-full bg-gray-200 p-0.5 inset-ring inset-ring-gray-900/5 outline-offset-2 outline-indigo-600 transition-colors duration-200 ease-in-out has-focus-visible:outline-2 dark:bg-white/5 dark:inset-ring-white/10 dark:outline-indigo-500",s&&"bg-indigo-600 dark:bg-indigo-500",n&&"opacity-60",p),children:[f==="icon"?v.jsxs("span",{className:Ti("relative size-5 rounded-full bg-white shadow-xs ring-1 ring-gray-900/5 transition-transform duration-200 ease-in-out",s&&"translate-x-5"),children:[v.jsx("span",{"aria-hidden":"true",className:Ti("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-in",s?"opacity-0 duration-100":"opacity-100 duration-200"),children:v.jsx("svg",{fill:"none",viewBox:"0 0 12 12",className:"size-3 text-gray-400 dark:text-gray-600",children:v.jsx("path",{d:"M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})})}),v.jsx("span",{"aria-hidden":"true",className:Ti("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-out",s?"opacity-100 duration-200":"opacity-0 duration-100"),children:v.jsx("svg",{fill:"currentColor",viewBox:"0 0 12 12",className:"size-3 text-indigo-600 dark:text-indigo-500",children:v.jsx("path",{d:"M3.707 5.293a1 1 0 00-1.414 1.414l1.414-1.414zM5 8l-.707.707a1 1 0 001.414 0L5 8zm4.707-3.293a1 1 0 00-1.414-1.414l1.414 1.414zm-7.414 2l2 2 1.414-1.414-2-2-1.414 1.414zm3.414 2l4-4-1.414-1.414-4 4 1.414 1.414z"})})})]}):v.jsx("span",{className:Ti("size-5 rounded-full bg-white shadow-xs ring-1 ring-gray-900/5 transition-transform duration-200 ease-in-out",s&&"translate-x-5")}),v.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:g,disabled:n,required:r,"aria-label":o,"aria-labelledby":u,"aria-describedby":c,className:y})]})}function Al({label:s,description:e,labelPosition:t="left",id:i,className:n,...r}){const o=k.useId(),u=i??`sw-${o}`,c=`${u}-label`,d=`${u}-desc`;return t==="right"?v.jsxs("div",{className:Ti("flex items-center justify-between gap-3",n),children:[v.jsx(vS,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0}),v.jsxs("div",{className:"text-sm",children:[v.jsx("label",{id:c,htmlFor:u,className:"font-medium text-gray-900 dark:text-white",children:s})," ",e?v.jsx("span",{id:d,className:"text-gray-500 dark:text-gray-400",children:e}):null]})]}):v.jsxs("div",{className:Ti("flex items-center justify-between",n),children:[v.jsxs("span",{className:"flex grow flex-col",children:[v.jsx("label",{id:c,htmlFor:u,className:"text-sm/6 font-medium text-gray-900 dark:text-white",children:s}),e?v.jsx("span",{id:d,className:"text-sm text-gray-500 dark:text-gray-400",children:e}):null]}),v.jsx(vS,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0})]})}function fc({label:s,value:e=0,indeterminate:t=!1,showPercent:i=!1,rightLabel:n,steps:r,currentStep:o,size:u="md",className:c}){const d=Math.max(0,Math.min(100,Number(e)||0)),f=u==="sm"?"h-1.5":"h-2",p=Array.isArray(r)&&r.length>0,g=p?r.length:0,y=w=>w===0?"text-left":w===g-1?"text-right":"text-center",x=w=>typeof o!="number"||!Number.isFinite(o)?!1:w<=o,_=i&&!t;return v.jsxs("div",{className:c,children:[s||_?v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s?v.jsx("p",{className:"flex-1 min-w-0 truncate text-xs font-medium text-gray-900 dark:text-white",children:s}):v.jsx("span",{className:"flex-1"}),_?v.jsxs("span",{className:"shrink-0 text-xs font-medium text-gray-700 dark:text-gray-300",children:[Math.round(d),"%"]}):null]}):null,v.jsxs("div",{"aria-hidden":"true",className:s||_?"mt-2":"",children:[v.jsx("div",{className:"overflow-hidden rounded-full bg-gray-200 dark:bg-white/10",children:t?v.jsx("div",{className:`${f} w-full rounded-full bg-indigo-600/70 dark:bg-indigo-500/70 animate-pulse`}):v.jsx("div",{className:`${f} rounded-full bg-indigo-600 dark:bg-indigo-500 transition-[width] duration-200`,style:{width:`${d}%`}})}),n?v.jsx("div",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400",children:n}):null,p?v.jsx("div",{className:"mt-3 hidden text-sm font-medium text-gray-600 sm:grid dark:text-gray-400",style:{gridTemplateColumns:`repeat(${g}, minmax(0, 1fr))`},children:r.map((w,D)=>v.jsx("div",{className:[y(D),x(D)?"text-indigo-600 dark:text-indigo-400":""].join(" "),children:w},`${D}-${w}`))}):null]})]})}async function xS(s,e){const t=await fetch(s,{cache:"no-store",...e,headers:{"Content-Type":"application/json",...e?.headers||{}}});let i=null;try{i=await t.json()}catch{}if(!t.ok){const n=i&&(i.error||i.message)||t.statusText;throw new Error(n)}return i}function I5({onFinished:s}){const[e,t]=k.useState(null),[i,n]=k.useState(null),[r,o]=k.useState(!1),[u,c]=k.useState(!1),d=k.useCallback(async()=>{try{const B=await xS("/api/tasks/generate-assets");t(B)}catch(B){n(B?.message??String(B))}},[]),f=k.useRef(!1);k.useEffect(()=>{const B=f.current,j=!!e?.running;f.current=j,B&&!j&&s?.()},[e?.running,s]),k.useEffect(()=>{d()},[d]),k.useEffect(()=>{if(!e?.running)return;const B=window.setInterval(d,1200);return()=>window.clearInterval(B)},[e?.running,d]);async function p(){n(null),o(!0);try{const B=await xS("/api/tasks/generate-assets",{method:"POST"});t(B)}catch(B){n(B?.message??String(B))}finally{o(!1)}}async function g(){n(null),c(!0);try{await fetch("/api/tasks/generate-assets",{method:"DELETE",cache:"no-store"})}catch{}finally{await d(),c(!1)}}const y=!!e?.running,x=e?.total??0,_=e?.done??0,w=x>0?Math.min(100,Math.round(_/x*100)):0,D=B=>{const j=String(B??"").trim();if(!j)return null;const V=new Date(j);return Number.isFinite(V.getTime())?V.toLocaleString(void 0,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):null},I=D(e?.startedAt),L=D(e?.finishedAt);return v.jsxs("div",{className:`\r + rounded-2xl border border-gray-200 bg-white/80 p-4 shadow-sm\r + backdrop-blur supports-[backdrop-filter]:bg-white/60\r + dark:border-white/10 dark:bg-gray-950/50 dark:supports-[backdrop-filter]:bg-gray-950/35\r + `,children:[v.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[v.jsxs("div",{className:"min-w-0",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Assets-Generator"}),y?v.jsx("span",{className:"inline-flex items-center rounded-full bg-indigo-500/10 px-2 py-0.5 text-[11px] font-semibold text-indigo-700 ring-1 ring-inset ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/30",children:"läuft"}):v.jsx("span",{className:"inline-flex items-center rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-semibold text-gray-700 ring-1 ring-inset ring-gray-200 dark:bg-white/5 dark:text-gray-200 dark:ring-white/10",children:"bereit"})]}),v.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-white/70",children:["Erzeugt pro fertiger Datei unter ",v.jsx("span",{className:"font-mono",children:"/generated//"})," ",v.jsx("span",{className:"font-mono",children:"thumbs.jpg"}),", ",v.jsx("span",{className:"font-mono",children:"preview.mp4"})," ","und ",v.jsx("span",{className:"font-mono",children:"meta.json"})," für schnelle Listen & zuverlässige Duration."]})]}),v.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[y?v.jsx(_i,{variant:"secondary",color:"red",onClick:g,disabled:u,className:"w-full sm:w-auto",children:u?"Stoppe…":"Stop"}):null,v.jsx(_i,{variant:"primary",onClick:p,disabled:r||y,className:"w-full sm:w-auto",children:r?"Starte…":y?"Läuft…":"Generieren"})]})]}),i?v.jsx("div",{className:"mt-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-200",children:i}):null,e?.error?v.jsx("div",{className:"mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200",children:e.error}):null,e?v.jsxs("div",{className:"mt-4 space-y-3",children:[v.jsx(fc,{value:w,showPercent:!0,rightLabel:x?`${_}/${x} Dateien`:"—"}),v.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[v.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[v.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Thumbs"}),v.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.generatedThumbs??0})]}),v.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[v.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Previews"}),v.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.generatedPreviews??0})]}),v.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[v.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Übersprungen"}),v.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.skipped??0})]})]}),v.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-1 text-xs text-gray-600 dark:text-white/70",children:[v.jsx("span",{children:I?v.jsxs(v.Fragment,{children:["Start: ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:I})]}):"Start: —"}),v.jsx("span",{children:L?v.jsxs(v.Fragment,{children:["Ende: ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:L})]}):"Ende: —"})]})]}):v.jsx("div",{className:"mt-4 text-xs text-gray-600 dark:text-white/70",children:"Status wird geladen…"})]})}const Ks={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!0,autoStartAddedDownloads:!0,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!1,autoDeleteSmallDownloadsBelowMB:50,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1,lowDiskPauseBelowGB:5};function N5({onAssetsGenerated:s}){const[e,t]=k.useState(Ks),[i,n]=k.useState(!1),[r,o]=k.useState(null),[u,c]=k.useState(null),[d,f]=k.useState(null);k.useEffect(()=>{let y=!0;return fetch("/api/settings",{cache:"no-store"}).then(async x=>{if(!x.ok)throw new Error(await x.text());return x.json()}).then(x=>{y&&t({recordDir:(x.recordDir||Ks.recordDir).toString(),doneDir:(x.doneDir||Ks.doneDir).toString(),ffmpegPath:String(x.ffmpegPath??Ks.ffmpegPath??""),autoAddToDownloadList:x.autoAddToDownloadList??Ks.autoAddToDownloadList,autoStartAddedDownloads:x.autoStartAddedDownloads??Ks.autoStartAddedDownloads,useChaturbateApi:x.useChaturbateApi??Ks.useChaturbateApi,useMyFreeCamsWatcher:x.useMyFreeCamsWatcher??Ks.useMyFreeCamsWatcher,autoDeleteSmallDownloads:x.autoDeleteSmallDownloads??Ks.autoDeleteSmallDownloads,autoDeleteSmallDownloadsBelowMB:x.autoDeleteSmallDownloadsBelowMB??Ks.autoDeleteSmallDownloadsBelowMB,blurPreviews:x.blurPreviews??Ks.blurPreviews,teaserPlayback:x.teaserPlayback??Ks.teaserPlayback,teaserAudio:x.teaserAudio??Ks.teaserAudio,lowDiskPauseBelowGB:x.lowDiskPauseBelowGB??Ks.lowDiskPauseBelowGB})}).catch(()=>{}),()=>{y=!1}},[]);async function p(y){f(null),c(null),o(y);try{window.focus();const x=await fetch(`/api/settings/browse?target=${y}`,{cache:"no-store"});if(x.status===204)return;if(!x.ok){const D=await x.text().catch(()=>"");throw new Error(D||`HTTP ${x.status}`)}const w=((await x.json()).path??"").trim();if(!w)return;t(D=>y==="record"?{...D,recordDir:w}:y==="done"?{...D,doneDir:w}:{...D,ffmpegPath:w})}catch(x){f(x?.message??String(x))}finally{o(null)}}async function g(){f(null),c(null);const y=e.recordDir.trim(),x=e.doneDir.trim(),_=(e.ffmpegPath??"").trim();if(!y||!x){f("Bitte Aufnahme-Ordner und Ziel-Ordner angeben.");return}const w=!!e.autoAddToDownloadList,D=w?!!e.autoStartAddedDownloads:!1,I=!!e.useChaturbateApi,L=!!e.useMyFreeCamsWatcher,B=!!e.autoDeleteSmallDownloads,j=Math.max(0,Math.min(1e5,Math.floor(Number(e.autoDeleteSmallDownloadsBelowMB??Ks.autoDeleteSmallDownloadsBelowMB)))),V=!!e.blurPreviews,M=e.teaserPlayback==="still"||e.teaserPlayback==="all"||e.teaserPlayback==="hover"?e.teaserPlayback:Ks.teaserPlayback,z=!!e.teaserAudio,O=Math.max(1,Math.floor(Number(e.lowDiskPauseBelowGB??Ks.lowDiskPauseBelowGB)));n(!0);try{const N=await fetch("/api/settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recordDir:y,doneDir:x,ffmpegPath:_,autoAddToDownloadList:w,autoStartAddedDownloads:D,useChaturbateApi:I,useMyFreeCamsWatcher:L,autoDeleteSmallDownloads:B,autoDeleteSmallDownloadsBelowMB:j,blurPreviews:V,teaserPlayback:M,teaserAudio:z,lowDiskPauseBelowGB:O})});if(!N.ok){const q=await N.text().catch(()=>"");throw new Error(q||`HTTP ${N.status}`)}c("✅ Gespeichert."),window.dispatchEvent(new CustomEvent("recorder-settings-updated"))}catch(N){f(N?.message??String(N))}finally{n(!1)}}return v.jsx(za,{header:v.jsxs("div",{className:"flex items-center justify-between gap-4",children:[v.jsxs("div",{children:[v.jsx("div",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Einstellungen"}),v.jsx("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:"Recorder-Konfiguration, Automatisierung und Tasks."})]}),v.jsx(_i,{variant:"primary",onClick:g,disabled:i,children:"Speichern"})]}),grayBody:!0,children:v.jsxs("div",{className:"space-y-4",children:[d&&v.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-200",children:d}),u&&v.jsx("div",{className:"rounded-lg border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700 dark:border-green-500/30 dark:bg-green-500/10 dark:text-green-200",children:u}),v.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white p-4 shadow-sm dark:border-white/10 dark:bg-gray-950/40",children:[v.jsxs("div",{className:"flex items-start justify-between gap-4",children:[v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tasks"}),v.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Generiere fehlende Vorschauen/Metadaten (z.B. Duration via meta.json) für schnelle Listenansichten."})]}),v.jsx("div",{className:"shrink-0",children:v.jsx("span",{className:"inline-flex items-center rounded-full bg-gray-100 px-2 py-1 text-[11px] font-medium text-gray-700 dark:bg-white/10 dark:text-gray-200",children:"Utilities"})})]}),v.jsx("div",{className:"mt-3",children:v.jsx(I5,{onFinished:s})})]}),v.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white p-4 shadow-sm dark:border-white/10 dark:bg-gray-950/40",children:[v.jsxs("div",{className:"mb-3",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Pfad-Einstellungen"}),v.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Aufnahme- und Zielverzeichnisse sowie optionaler ffmpeg-Pfad."})]}),v.jsxs("div",{className:"space-y-3",children:[v.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[v.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Aufnahme-Ordner"}),v.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[v.jsx("input",{value:e.recordDir,onChange:y=>t(x=>({...x,recordDir:y.target.value})),placeholder:"records (oder absolut: C:\\records / /mnt/data/records)",className:`min-w-0 flex-1 rounded-lg px-3 py-2 text-sm bg-white text-gray-900 ring-1 ring-gray-200 + focus:outline-none focus:ring-2 focus:ring-indigo-500 + dark:bg-white/10 dark:text-white dark:ring-white/10`}),v.jsx(_i,{variant:"secondary",onClick:()=>p("record"),disabled:i||r!==null,children:"Durchsuchen..."})]})]}),v.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[v.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Fertige Downloads nach"}),v.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[v.jsx("input",{value:e.doneDir,onChange:y=>t(x=>({...x,doneDir:y.target.value})),placeholder:"records/done",className:`min-w-0 flex-1 rounded-lg px-3 py-2 text-sm bg-white text-gray-900 ring-1 ring-gray-200 + focus:outline-none focus:ring-2 focus:ring-indigo-500 + dark:bg-white/10 dark:text-white dark:ring-white/10`}),v.jsx(_i,{variant:"secondary",onClick:()=>p("done"),disabled:i||r!==null,children:"Durchsuchen..."})]})]}),v.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[v.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"ffmpeg.exe"}),v.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[v.jsx("input",{value:e.ffmpegPath??"",onChange:y=>t(x=>({...x,ffmpegPath:y.target.value})),placeholder:"Leer = automatisch (FFMPEG_PATH / ffmpeg im PATH)",className:`min-w-0 flex-1 rounded-lg px-3 py-2 text-sm bg-white text-gray-900 ring-1 ring-gray-200 + focus:outline-none focus:ring-2 focus:ring-indigo-500 + dark:bg-white/10 dark:text-white dark:ring-white/10`}),v.jsx(_i,{variant:"secondary",onClick:()=>p("ffmpeg"),disabled:i||r!==null,children:"Durchsuchen..."})]})]})]})]}),v.jsxs("div",{className:"rounded-2xl border border-gray-200 bg-white p-4 shadow-sm dark:border-white/10 dark:bg-gray-950/40",children:[v.jsxs("div",{className:"mb-3",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Automatisierung & Anzeige"}),v.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Verhalten beim Hinzufügen/Starten sowie Anzeigeoptionen."})]}),v.jsxs("div",{className:"space-y-3",children:[v.jsx(Al,{checked:!!e.autoAddToDownloadList,onChange:y=>t(x=>({...x,autoAddToDownloadList:y,autoStartAddedDownloads:y?x.autoStartAddedDownloads:!1})),label:"Automatisch zur Downloadliste hinzufügen",description:"Neue Links/Modelle werden automatisch in die Downloadliste übernommen."}),v.jsx(Al,{checked:!!e.autoStartAddedDownloads,onChange:y=>t(x=>({...x,autoStartAddedDownloads:y})),disabled:!e.autoAddToDownloadList,label:"Hinzugefügte Downloads automatisch starten",description:"Wenn ein Download hinzugefügt wurde, startet er direkt (sofern möglich)."}),v.jsx(Al,{checked:!!e.useChaturbateApi,onChange:y=>t(x=>({...x,useChaturbateApi:y})),label:"Chaturbate API",description:"Wenn aktiv, pollt das Backend alle paar Sekunden die Online-Rooms API und cached die aktuell online Models."}),v.jsx(Al,{checked:!!e.useMyFreeCamsWatcher,onChange:y=>t(x=>({...x,useMyFreeCamsWatcher:y})),label:"MyFreeCams Auto-Check (watched)",description:"Geht watched MyFreeCams-Models einzeln durch und startet einen Download. Wenn keine Output-Datei entsteht, ist der Stream nicht öffentlich (offline/away/private) und der Job wird wieder entfernt."}),v.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[v.jsx(Al,{checked:!!e.autoDeleteSmallDownloads,onChange:y=>t(x=>({...x,autoDeleteSmallDownloads:y,autoDeleteSmallDownloadsBelowMB:x.autoDeleteSmallDownloadsBelowMB??50})),label:"Kleine Downloads automatisch löschen",description:"Löscht fertige Downloads automatisch, wenn die Datei kleiner als die eingestellte Mindestgröße ist."}),v.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center "+(e.autoDeleteSmallDownloads?"":"opacity-50 pointer-events-none"),children:[v.jsxs("div",{className:"sm:col-span-4",children:[v.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Mindestgröße"}),v.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Alles darunter wird gelöscht."})]}),v.jsx("div",{className:"sm:col-span-8",children:v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("input",{type:"number",min:0,step:1,value:e.autoDeleteSmallDownloadsBelowMB??50,onChange:y=>t(x=>({...x,autoDeleteSmallDownloadsBelowMB:Number(y.target.value||0)})),className:`h-9 w-full rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm + dark:border-white/10 dark:bg-gray-900 dark:text-gray-100`}),v.jsx("span",{className:"shrink-0 text-xs text-gray-600 dark:text-gray-300",children:"MB"})]})})]})]}),v.jsx(Al,{checked:!!e.blurPreviews,onChange:y=>t(x=>({...x,blurPreviews:y})),label:"Vorschaubilder blurren",description:"Weichzeichnet Vorschaubilder/Teaser (praktisch auf mobilen Geräten oder im öffentlichen Umfeld)."}),v.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[v.jsxs("div",{className:"sm:col-span-4",children:[v.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Teaser abspielen"}),v.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Standbild spart Leistung. „Bei Hover (Standard)“: Desktop spielt bei Hover ab, Mobile im Viewport. „Alle“ kann viel CPU ziehen."})]}),v.jsxs("div",{className:"sm:col-span-8",children:[v.jsx("label",{className:"sr-only",htmlFor:"teaserPlayback",children:"Teaser abspielen"}),v.jsxs("select",{id:"teaserPlayback",value:e.teaserPlayback??"hover",onChange:y=>t(x=>({...x,teaserPlayback:y.target.value})),className:`h-9 w-full rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm + dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark]`,children:[v.jsx("option",{value:"still",children:"Standbild"}),v.jsx("option",{value:"hover",children:"Bei Hover (Standard)"}),v.jsx("option",{value:"all",children:"Alle"})]})]})]}),v.jsx(Al,{checked:!!e.teaserAudio,onChange:y=>t(x=>({...x,teaserAudio:y})),label:"Teaser mit Ton",description:"Wenn aktiv, werden Vorschau/Teaser nicht stumm geschaltet."}),v.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Speicherplatz-Notbremse"}),v.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Wenn freier Platz darunter fällt: Autostart pausieren + laufende Downloads stoppen. Resume erfolgt automatisch bei +3 GB."}),v.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[v.jsxs("div",{className:"sm:col-span-4",children:[v.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Pause unter"}),v.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Freier Speicher in GB"})]}),v.jsxs("div",{className:"sm:col-span-8 flex items-center gap-3",children:[v.jsx("input",{type:"range",min:1,max:500,step:1,value:e.lowDiskPauseBelowGB??5,onChange:y=>t(x=>({...x,lowDiskPauseBelowGB:Number(y.target.value)})),className:"w-full"}),v.jsxs("span",{className:"w-16 text-right text-sm tabular-nums text-gray-900 dark:text-gray-100",children:[e.lowDiskPauseBelowGB??5," GB"]})]})]})]})]})]})]})})}function O5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const M5=k.forwardRef(O5);function P5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M11.78 5.22a.75.75 0 0 1 0 1.06L8.06 10l3.72 3.72a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z",clipRule:"evenodd"}))}const B5=k.forwardRef(P5);function F5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M8.22 5.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06-1.06L11.94 10 8.22 6.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const U5=k.forwardRef(F5);function j5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{d:"M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z"}))}const $5=k.forwardRef(j5);function Dn(...s){return s.filter(Boolean).join(" ")}function bS(s){return s==="center"?"text-center":s==="right"?"text-right":"text-left"}function H5(s){return s==="center"?"justify-center":s==="right"?"justify-end":"justify-start"}function TS(s){return s==null?{isNull:!0,kind:"string",value:""}:s instanceof Date?{isNull:!1,kind:"number",value:s.getTime()}:typeof s=="number"?{isNull:!1,kind:"number",value:s}:typeof s=="boolean"?{isNull:!1,kind:"number",value:s?1:0}:typeof s=="bigint"?{isNull:!1,kind:"number",value:Number(s)}:{isNull:!1,kind:"string",value:String(s).toLocaleLowerCase()}}function Ux({columns:s,rows:e,getRowKey:t,title:i,description:n,actions:r,fullWidth:o=!1,card:u=!0,striped:c=!1,stickyHeader:d=!1,compact:f=!1,isLoading:p=!1,emptyLabel:g="Keine Daten vorhanden.",className:y,rowClassName:x,onRowClick:_,onRowContextMenu:w,sort:D,onSortChange:I,defaultSort:L=null}){const B=f?"py-2":"py-4",j=f?"py-3":"py-3.5",V=D!==void 0,[M,z]=k.useState(L),O=V?D:M,N=k.useCallback(Q=>{V||z(Q),I?.(Q)},[V,I]),q=k.useMemo(()=>{if(!O)return e;const Q=s.find(Z=>Z.key===O.key);if(!Q)return e;const Y=O.direction==="asc"?1:-1,re=e.map((Z,H)=>({r:Z,i:H}));return re.sort((Z,H)=>{let K=0;if(Q.sortFn)K=Q.sortFn(Z.r,H.r);else{const ie=Q.sortValue?Q.sortValue(Z.r):Z.r?.[Q.key],te=Q.sortValue?Q.sortValue(H.r):H.r?.[Q.key],ne=TS(ie),$=TS(te);ne.isNull&&!$.isNull?K=1:!ne.isNull&&$.isNull?K=-1:ne.kind==="number"&&$.kind==="number"?K=ne.value<$.value?-1:ne.value>$.value?1:0:K=String(ne.value).localeCompare(String($.value),void 0,{numeric:!0})}return K===0?Z.i-H.i:K*Y}),re.map(Z=>Z.r)},[e,s,O]);return v.jsxs("div",{className:Dn(o?"":"px-4 sm:px-6 lg:px-8",y),children:[(i||n||r)&&v.jsxs("div",{className:"sm:flex sm:items-center",children:[v.jsxs("div",{className:"sm:flex-auto",children:[i&&v.jsx("h1",{className:"text-base font-semibold text-gray-900 dark:text-white",children:i}),n&&v.jsx("p",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:n})]}),r&&v.jsx("div",{className:"mt-4 sm:mt-0 sm:ml-16 sm:flex-none",children:r})]}),v.jsx("div",{className:Dn(i||n||r?"mt-8":""),children:v.jsx("div",{className:"flow-root",children:v.jsx("div",{className:"overflow-x-auto",children:v.jsx("div",{className:Dn("inline-block min-w-full py-2 align-middle",o?"":"sm:px-6 lg:px-8"),children:v.jsx("div",{className:Dn(u&&"overflow-hidden shadow-sm outline-1 outline-black/5 sm:rounded-lg dark:shadow-none dark:-outline-offset-1 dark:outline-white/10"),children:v.jsxs("table",{className:"relative min-w-full divide-y divide-gray-200 dark:divide-white/10",children:[v.jsx("thead",{className:Dn(u&&"bg-gray-50/90 dark:bg-gray-800/70",d&&"sticky top-0 z-10 backdrop-blur-sm shadow-sm"),children:v.jsx("tr",{children:s.map(Q=>{const Y=!!O&&O.key===Q.key,re=Y?O.direction:void 0,Z=Q.sortable&&!Q.srOnlyHeader?Y?re==="asc"?"ascending":"descending":"none":void 0,H=()=>{if(!(!Q.sortable||Q.srOnlyHeader))return N(Y?re==="asc"?{key:Q.key,direction:"desc"}:null:{key:Q.key,direction:"asc"})};return v.jsx("th",{scope:"col","aria-sort":Z,className:Dn(j,"px-3 text-xs font-semibold tracking-wide text-gray-700 dark:text-gray-200 whitespace-nowrap",bS(Q.align),Q.widthClassName,Q.headerClassName),children:Q.srOnlyHeader?v.jsx("span",{className:"sr-only",children:Q.header}):Q.sortable?v.jsxs("button",{type:"button",onClick:H,className:Dn("group inline-flex w-full items-center gap-2 select-none rounded-md px-1.5 py-1 -my-1 hover:bg-gray-100/70 dark:hover:bg-white/5",H5(Q.align)),children:[v.jsx("span",{children:Q.header}),v.jsx("span",{className:Dn("flex-none rounded-sm text-gray-400 dark:text-gray-500",Y?"bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-white":"invisible group-hover:visible group-focus-visible:visible"),children:v.jsx(M5,{"aria-hidden":"true",className:Dn("size-5 transition-transform",Y&&re==="asc"&&"rotate-180")})})]}):Q.header},Q.key)})})}),v.jsx("tbody",{className:Dn("divide-y divide-gray-200 dark:divide-white/10",u?"bg-white dark:bg-gray-800/50":"bg-white dark:bg-gray-900"),children:p?v.jsx("tr",{children:v.jsx("td",{colSpan:s.length,className:Dn(B,"px-3 text-sm text-gray-500 dark:text-gray-400"),children:"Lädt…"})}):q.length===0?v.jsx("tr",{children:v.jsx("td",{colSpan:s.length,className:Dn(B,"px-3 text-sm text-gray-500 dark:text-gray-400"),children:g})}):q.map((Q,Y)=>{const re=t?t(Q,Y):String(Y);return v.jsx("tr",{className:Dn(c&&"even:bg-gray-50 dark:even:bg-gray-800/50",_&&"cursor-pointer",_&&"hover:bg-gray-50 dark:hover:bg-white/5 transition-colors",x?.(Q,Y)),onClick:()=>_?.(Q),onContextMenu:w?Z=>{Z.preventDefault(),w(Q,Z)}:void 0,children:s.map(Z=>{const H=Z.cell?.(Q,Y)??Z.accessor?.(Q)??Q?.[Z.key];return v.jsx("td",{className:Dn(B,"px-3 text-sm whitespace-nowrap",bS(Z.align),Z.className,Z.key===s[0]?.key?"font-medium text-gray-900 dark:text-white":"text-gray-500 dark:text-gray-400"),children:H},Z.key)})},re)})})]})})})})})})]})}function pA({children:s,content:e}){const t=k.useRef(null),i=k.useRef(null),[n,r]=k.useState(!1),[o,u]=k.useState(null),c=k.useRef(null),d=()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)},f=()=>{d(),c.current=window.setTimeout(()=>{r(!1),c.current=null},150)},p=()=>{d(),r(!0)},g=()=>{f()},y=()=>{d(),r(!1)},x=()=>{const w=t.current,D=i.current;if(!w||!D)return;const I=8,L=8,B=w.getBoundingClientRect(),j=D.getBoundingClientRect();let V=B.bottom+I;if(V+j.height>window.innerHeight-L){const O=B.top-j.height-I;O>=L?V=O:V=Math.max(L,window.innerHeight-j.height-L)}let z=B.left;z+j.width>window.innerWidth-L&&(z=window.innerWidth-j.width-L),z=Math.max(L,z),u({left:z,top:V})};k.useLayoutEffect(()=>{if(!n)return;const w=requestAnimationFrame(()=>x());return()=>cancelAnimationFrame(w)},[n]),k.useEffect(()=>{if(!n)return;const w=()=>requestAnimationFrame(()=>x());return window.addEventListener("resize",w),window.addEventListener("scroll",w,!0),()=>{window.removeEventListener("resize",w),window.removeEventListener("scroll",w,!0)}},[n]),k.useEffect(()=>()=>d(),[]);const _=()=>typeof e=="function"?e(n,{close:y}):e;return v.jsxs(v.Fragment,{children:[v.jsx("div",{ref:t,className:"inline-flex",onMouseEnter:p,onMouseLeave:g,children:s}),n&&Sh.createPortal(v.jsx("div",{ref:i,className:"fixed z-50",style:{left:o?.left??-9999,top:o?.top??-9999,visibility:o?"visible":"hidden"},onMouseEnter:p,onMouseLeave:g,children:v.jsx(za,{className:"shadow-lg ring-1 ring-black/10 dark:ring-white/10 max-w-[calc(100vw-16px)]",noBodyPadding:!0,children:_()})}),document.body)]})}const Ym=!1,V5=!1;function gA(s,e){if(!s)return;const t=e?.muted??Ym;s.muted=t,s.defaultMuted=t,s.playsInline=!0,s.setAttribute("playsinline","true")}function jx({job:s,getFileName:e,durationSeconds:t,onDuration:i,animated:n=!1,animatedMode:r="frames",animatedTrigger:o="always",autoTickMs:u=15e3,thumbStepSec:c,thumbSpread:d,thumbSamples:f,clipSeconds:p=1,variant:g="thumb",className:y,showPopover:x=!0,blur:_=!1,inlineVideo:w=!1,inlineNonce:D=0,inlineControls:I=!1,inlineLoop:L=!0,assetNonce:B=0,muted:j=Ym,popoverMuted:V=Ym}){const M=e(s.output||""),z=_?"blur-md":"",O={muted:j,playsInline:!0,preload:"metadata"},[N,q]=k.useState(!0),[Q,Y]=k.useState(!0),[re,Z]=k.useState(!1),[H,K]=k.useState(!1),ie=k.useRef(null),[te,ne]=k.useState(!1),[$,ee]=k.useState(!1),[le,be]=k.useState(0),[fe,_e]=k.useState(!1),Me=w===!0||w==="always"?"always":w==="hover"?"hover":"never",et=Xe=>Xe.startsWith("HOT ")?Xe.slice(4):Xe,Ge=k.useMemo(()=>{const Xe=e(s.output||"");if(!Xe)return"";const Ot=Xe.replace(/\.[^.]+$/,"");return et(Ot).trim()},[s.output,e]),lt=k.useMemo(()=>M?`/api/record/video?file=${encodeURIComponent(M)}`:"",[M]),At=typeof t=="number"&&Number.isFinite(t)&&t>0,mt=g==="fill"?"w-full h-full":"w-20 h-16",Vt=k.useRef(null),Re=k.useRef(null),dt=k.useRef(null),He=Xe=>{if(Xe){try{Xe.pause()}catch{}try{Xe.removeAttribute("src"),Xe.src="",Xe.load()}catch{}}};k.useEffect(()=>{K(!1)},[Ge,B]),k.useEffect(()=>{const Xe=Ot=>{const kt=String(Ot?.detail?.file??"");!kt||kt!==M||(He(Vt.current),He(Re.current),He(dt.current))};return window.addEventListener("player:release",Xe),window.addEventListener("player:close",Xe),()=>{window.removeEventListener("player:release",Xe),window.removeEventListener("player:close",Xe)}},[M]),k.useEffect(()=>{const Xe=ie.current;if(!Xe)return;const Ot=new IntersectionObserver(kt=>{const Xt=!!kt[0]?.isIntersecting;ne(Xt),Xt&&ee(!0)},{threshold:.01,rootMargin:"350px 0px"});return Ot.observe(Xe),()=>Ot.disconnect()},[]),k.useEffect(()=>{if(!n||r!=="frames"||!te||document.hidden)return;const Xe=window.setInterval(()=>be(Ot=>Ot+1),u);return()=>window.clearInterval(Xe)},[n,r,te,u]);const tt=k.useMemo(()=>{if(!n||r!=="frames"||!At)return null;const Xe=t,Ot=Math.max(.25,c??3);if(d){const ni=Math.max(4,Math.min(f??16,Math.floor(Xe))),hi=le%ni,Ai=Math.max(.1,Xe-Ot),Nt=Math.min(.25,Ai*.02),bt=hi/ni*Ai+Nt;return Math.min(Xe-.05,Math.max(.05,bt))}const kt=Math.max(Xe-.1,Ot),Xt=le*Ot%kt;return Math.min(Xe-.05,Math.max(.05,Xt))},[n,r,At,t,le,c,d,f]),nt=B??0,ot=k.useMemo(()=>Ge?tt==null?`/api/record/preview?id=${encodeURIComponent(Ge)}&v=${nt}`:`/api/record/preview?id=${encodeURIComponent(Ge)}&t=${tt}&v=${nt}-${le}`:"",[Ge,tt,le,nt]),Ke=k.useMemo(()=>Ge?`/api/generated/teaser?id=${encodeURIComponent(Ge)}&v=${nt}`:"",[Ge,nt]),pt=Xe=>{if(Z(!0),!i)return;const Ot=Xe.currentTarget.duration;Number.isFinite(Ot)&&Ot>0&&i(s,Ot)};if(!lt)return v.jsx("div",{className:[mt,"rounded bg-gray-100 dark:bg-white/5"].join(" ")});k.useEffect(()=>{q(!0),Y(!0)},[Ge,B]);const yt=Me!=="never"&&te&&Q&&(Me==="always"||Me==="hover"&&fe),Gt=n&&te&&!document.hidden&&Q&&!yt&&(o==="always"||fe)&&(r==="teaser"&&!!Ke||r==="clips"&&At),Ut=Me==="hover"||n&&(r==="clips"||r==="teaser")&&o==="hover",ai=$||Ut&&fe,Zt=k.useMemo(()=>{if(!n)return[];if(r!=="clips")return[];if(!At)return[];const Xe=t,Ot=Math.max(.25,p),kt=Math.max(8,Math.min(f??18,Math.floor(Xe))),Xt=Math.max(.1,Xe-Ot),ni=Math.min(.25,Xt*.02),hi=[];for(let Ai=0;AiZt.map(Xe=>Xe.toFixed(2)).join(","),[Zt]),ct=k.useRef(null),it=k.useRef(0),Tt=k.useRef(0);k.useEffect(()=>{const Xe=Re.current;if(!Xe)return;if(!(Gt&&r==="teaser")){try{Xe.pause()}catch{}return}Xe.muted=!!j,Xe.defaultMuted=!!j,Xe.playsInline=!0,Xe.setAttribute("playsinline",""),Xe.setAttribute("webkit-playsinline","");const kt=Xe.play?.();kt&&typeof kt.catch=="function"&&kt.catch(()=>{})},[Gt,r,Ke,j]),k.useEffect(()=>{const Xe=ct.current;if(!Xe)return;if(!(Gt&&r==="clips")){Gt||Xe.pause();return}if(!Zt.length)return;it.current=it.current%Zt.length,Tt.current=Zt[it.current];const Ot=()=>{try{Xe.currentTime=Tt.current}catch{}const ni=Xe.play();ni&&typeof ni.catch=="function"&&ni.catch(()=>{})},kt=()=>Ot(),Xt=()=>{if(Zt.length&&Xe.currentTime-Tt.current>=p){it.current=(it.current+1)%Zt.length,Tt.current=Zt[it.current];try{Xe.currentTime=Tt.current+.01}catch{}}};return Xe.addEventListener("loadedmetadata",kt),Xe.addEventListener("timeupdate",Xt),Xe.readyState>=1&&Ot(),()=>{Xe.removeEventListener("loadedmetadata",kt),Xe.removeEventListener("timeupdate",Xt),Xe.pause()}},[Gt,r,$e,p,Zt]);const Wt=v.jsxs("div",{ref:ie,className:["rounded bg-gray-100 dark:bg-white/5 overflow-hidden relative",mt,y??""].join(" "),onMouseEnter:Ut?()=>_e(!0):void 0,onMouseLeave:Ut?()=>_e(!1):void 0,onFocus:Ut?()=>_e(!0):void 0,onBlur:Ut?()=>_e(!1):void 0,children:[ai&&ot&&N?v.jsx("img",{src:ot,loading:"lazy",decoding:"async",alt:M,className:["absolute inset-0 w-full h-full object-cover",z].filter(Boolean).join(" "),onError:()=>q(!1)}):v.jsx("div",{className:"absolute inset-0 bg-black/10 dark:bg-white/10"}),yt?k.createElement("video",{...O,ref:Vt,key:`inline-${Ge}-${D}`,src:lt,className:["absolute inset-0 w-full h-full object-cover",z,I?"pointer-events-auto":"pointer-events-none"].filter(Boolean).join(" "),autoPlay:!0,muted:j,controls:I,loop:L,poster:ai&&ot||void 0,onLoadedMetadata:pt,onError:()=>Y(!1)}):null,!yt&&Gt&&r==="teaser"?v.jsx("video",{ref:Re,src:Ke,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",z,H?"opacity-100":"opacity-0","transition-opacity duration-150"].filter(Boolean).join(" "),muted:j,playsInline:!0,autoPlay:!0,loop:!0,preload:"auto",poster:ai&&ot||void 0,onLoadedData:()=>K(!0),onPlaying:()=>K(!0),onError:()=>Y(!1)},`teaser-mp4-${Ge}`):null,!yt&&Gt&&r==="clips"?v.jsx("video",{ref:ct,src:lt,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",z].filter(Boolean).join(" "),muted:j,playsInline:!0,preload:"metadata",poster:ai&&ot||void 0,onError:()=>Y(!1)},`clips-${Ge}-${$e}`):null,te&&i&&!At&&!re&&!yt&&v.jsx("video",{src:lt,preload:"metadata",muted:j,playsInline:!0,className:"hidden",onLoadedMetadata:pt})]});return x?v.jsx(pA,{content:Xe=>Xe&&v.jsx("div",{className:"w-[420px]",children:v.jsx("div",{className:"aspect-video",children:v.jsx("video",{src:lt,className:["w-full h-full bg-black",z].filter(Boolean).join(" "),muted:V,playsInline:!0,preload:"metadata",controls:!0,autoPlay:!0,loop:!0,onClick:Ot=>Ot.stopPropagation(),onMouseDown:Ot=>Ot.stopPropagation()})})}),children:Wt}):Wt}function fy(...s){return s.filter(Boolean).join(" ")}const G5={sm:{btn:"px-2.5 py-1.5 text-sm",icon:"size-5"},md:{btn:"px-3 py-2 text-sm",icon:"size-5"}};function z5({items:s,value:e,onChange:t,size:i="md",className:n,ariaLabel:r="Optionen"}){const o=G5[i];return v.jsx("span",{className:fy("isolate inline-flex rounded-md shadow-xs dark:shadow-none",n),role:"group","aria-label":r,children:s.map((u,c)=>{const d=u.id===e,f=c===0,p=c===s.length-1,g=!u.label&&!!u.icon;return v.jsxs("button",{type:"button",disabled:u.disabled,onClick:()=>t(u.id),"aria-pressed":d,className:fy("relative inline-flex items-center justify-center font-semibold focus:z-10 transition-colors",!f&&"-ml-px",f&&"rounded-l-md",p&&"rounded-r-md",d?"bg-indigo-100 text-indigo-800 inset-ring-1 inset-ring-indigo-300 hover:bg-indigo-200 dark:bg-indigo-500/40 dark:text-indigo-100 dark:inset-ring-indigo-400/50 dark:hover:bg-indigo-500/50":"bg-white text-gray-900 inset-ring-1 inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:inset-ring-gray-700 dark:hover:bg-white/20","disabled:opacity-50 disabled:cursor-not-allowed",g?"px-2 py-2":o.btn),title:typeof u.label=="string"?u.label:u.srLabel,children:[g&&u.srLabel?v.jsx("span",{className:"sr-only",children:u.srLabel}):null,u.icon?v.jsx("span",{className:fy("shrink-0",g?"":"-ml-0.5",d?"text-indigo-600 dark:text-indigo-200":"text-gray-400 dark:text-gray-500"),children:u.icon}):null,u.label?v.jsx("span",{className:u.icon?"ml-1.5":"",children:u.label}):null]},u.id)})})}function q5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13.5 6H5.25A2.25 2.25 0 0 0 3 8.25v10.5A2.25 2.25 0 0 0 5.25 21h10.5A2.25 2.25 0 0 0 18 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"}))}const my=k.forwardRef(q5);function K5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 9V4.5M9 9H4.5M9 9 3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5 5.25 5.25"}))}const Y5=k.forwardRef(K5);function W5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15"}))}const X5=k.forwardRef(W5);function Q5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M16.5 3.75V16.5L12 14.25 7.5 16.5V3.75m9 0H18A2.25 2.25 0 0 1 20.25 6v12A2.25 2.25 0 0 1 18 20.25H6A2.25 2.25 0 0 1 3.75 18V6A2.25 2.25 0 0 1 6 3.75h1.5m9 0h-9"}))}const Mv=k.forwardRef(Q5);function Z5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 0 1 2.25-2.25h13.5A2.25 2.25 0 0 1 21 7.5v11.25m-18 0A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75m-18 0v-7.5A2.25 2.25 0 0 1 5.25 9h13.5A2.25 2.25 0 0 1 21 11.25v7.5m-9-6h.008v.008H12v-.008ZM12 15h.008v.008H12V15Zm0 2.25h.008v.008H12v-.008ZM9.75 15h.008v.008H9.75V15Zm0 2.25h.008v.008H9.75v-.008ZM7.5 15h.008v.008H7.5V15Zm0 2.25h.008v.008H7.5v-.008Zm6.75-4.5h.008v.008h-.008v-.008Zm0 2.25h.008v.008h-.008V15Zm0 2.25h.008v.008h-.008v-.008Zm2.25-4.5h.008v.008H16.5v-.008Zm0 2.25h.008v.008H16.5V15Z"}))}const _S=k.forwardRef(Z5);function J5({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const eO=k.forwardRef(J5);function tO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 12.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 18.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5Z"}))}const iO=k.forwardRef(tO);function sO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"}))}const nO=k.forwardRef(sO);function rO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"}),k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}))}const Pv=k.forwardRef(rO);function aO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.362 5.214A8.252 8.252 0 0 1 12 21 8.25 8.25 0 0 1 6.038 7.047 8.287 8.287 0 0 0 9 9.601a8.983 8.983 0 0 1 3.361-6.867 8.21 8.21 0 0 0 3 2.48Z"}),k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 18a3.75 3.75 0 0 0 .495-7.468 5.99 5.99 0 0 0-1.925 3.547 5.975 5.975 0 0 1-2.133-1.001A3.75 3.75 0 0 0 12 18Z"}))}const SS=k.forwardRef(aO);function oO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z"}))}const Wm=k.forwardRef(oO);function lO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 9h3.75M15 12h3.75M15 15h3.75M4.5 19.5h15a2.25 2.25 0 0 0 2.25-2.25V6.75A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25v10.5A2.25 2.25 0 0 0 4.5 19.5Zm6-10.125a1.875 1.875 0 1 1-3.75 0 1.875 1.875 0 0 1 3.75 0Zm1.294 6.336a6.721 6.721 0 0 1-3.17.789 6.721 6.721 0 0 1-3.168-.789 3.376 3.376 0 0 1 6.338 0Z"}))}const uO=k.forwardRef(lO);function cO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m11.25 11.25.041-.02a.75.75 0 0 1 1.063.852l-.708 2.836a.75.75 0 0 0 1.063.853l.041-.021M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9-3.75h.008v.008H12V8.25Z"}))}const dO=k.forwardRef(cO);function hO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m10.5 21 5.25-11.25L21 21m-9-3h7.5M3 5.621a48.474 48.474 0 0 1 6-.371m0 0c1.12 0 2.233.038 3.334.114M9 5.25V3m3.334 2.364C11.176 10.658 7.69 15.08 3 17.502m9.334-12.138c.896.061 1.785.147 2.666.257m-4.589 8.495a18.023 18.023 0 0 1-3.827-5.802"}))}const fO=k.forwardRef(hO);function mO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244"}))}const pO=k.forwardRef(mO);function gO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"}))}const ES=k.forwardRef(gO);function yO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}),k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1 1 15 0Z"}))}const vO=k.forwardRef(yO);function xO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"}))}const bO=k.forwardRef(xO);function TO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 6.878V6a2.25 2.25 0 0 1 2.25-2.25h7.5A2.25 2.25 0 0 1 18 6v.878m-12 0c.235-.083.487-.128.75-.128h10.5c.263 0 .515.045.75.128m-12 0A2.25 2.25 0 0 0 4.5 9v.878m13.5-3A2.25 2.25 0 0 1 19.5 9v.878m0 0a2.246 2.246 0 0 0-.75-.128H5.25c-.263 0-.515.045-.75.128m15 0A2.25 2.25 0 0 1 21 12v6a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 18v-6c0-.98.626-1.813 1.5-2.122"}))}const _O=k.forwardRef(TO);function SO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.813 15.904 9 18.75l-.813-2.846a4.5 4.5 0 0 0-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 0 0 3.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 0 0 3.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 0 0-3.09 3.09ZM18.259 8.715 18 9.75l-.259-1.035a3.375 3.375 0 0 0-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 0 0 2.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 0 0 2.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 0 0-2.456 2.456ZM16.894 20.567 16.5 21.75l-.394-1.183a2.25 2.25 0 0 0-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 0 0 1.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 0 0 1.423 1.423l1.183.394-1.183.394a2.25 2.25 0 0 0-1.423 1.423Z"}))}const wS=k.forwardRef(SO);function EO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"}))}const wO=k.forwardRef(EO);function AO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M11.48 3.499a.562.562 0 0 1 1.04 0l2.125 5.111a.563.563 0 0 0 .475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 0 0-.182.557l1.285 5.385a.562.562 0 0 1-.84.61l-4.725-2.885a.562.562 0 0 0-.586 0L6.982 20.54a.562.562 0 0 1-.84-.61l1.285-5.386a.562.562 0 0 0-.182-.557l-4.204-3.602a.562.562 0 0 1 .321-.988l5.518-.442a.563.563 0 0 0 .475-.345L11.48 3.5Z"}))}const Bv=k.forwardRef(AO);function CO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.375 19.5h17.25m-17.25 0a1.125 1.125 0 0 1-1.125-1.125M3.375 19.5h7.5c.621 0 1.125-.504 1.125-1.125m-9.75 0V5.625m0 12.75v-1.5c0-.621.504-1.125 1.125-1.125m18.375 2.625V5.625m0 12.75c0 .621-.504 1.125-1.125 1.125m1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125m0 3.75h-7.5A1.125 1.125 0 0 1 12 18.375m9.75-12.75c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125m19.5 0v1.5c0 .621-.504 1.125-1.125 1.125M2.25 5.625v1.5c0 .621.504 1.125 1.125 1.125m0 0h17.25m-17.25 0h7.5c.621 0 1.125.504 1.125 1.125M3.375 8.25c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125m17.25-3.75h-7.5c-.621 0-1.125.504-1.125 1.125m8.625-1.125c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125M12 10.875v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 10.875c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125M13.125 12h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125M20.625 12c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5M12 14.625v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 14.625c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125m0 1.5v-1.5m0 0c0-.621.504-1.125 1.125-1.125m0 0h7.5"}))}const kO=k.forwardRef(CO);function DO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"}))}const Fv=k.forwardRef(DO);function LO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z"}))}const RO=k.forwardRef(LO);function IO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const NO=k.forwardRef(IO);function OO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const $x=k.forwardRef(OO);function nm(...s){return s.filter(Boolean).join(" ")}const MO=k.forwardRef(function({children:e,enabled:t=!0,disabled:i=!1,onTap:n,onSwipeLeft:r,onSwipeRight:o,className:u,leftAction:c={label:v.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[v.jsx(Mv,{className:"h-6 w-6","aria-hidden":"true"}),v.jsx("span",{children:"Behalten"})]}),className:"bg-emerald-500/20 text-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-300"},rightAction:d={label:v.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[v.jsx(Fv,{className:"h-6 w-6","aria-hidden":"true"}),v.jsx("span",{children:"Löschen"})]}),className:"bg-red-500/20 text-red-800 dark:bg-red-500/15 dark:text-red-300"},thresholdPx:f=150,thresholdRatio:p=.25,ignoreFromBottomPx:g=72,ignoreSelector:y="[data-swipe-ignore]",snapMs:x=180,commitMs:_=180,tapIgnoreSelector:w="button,a,input,textarea,select,video[controls],video[controls] *,[data-tap-ignore]"},D){const I=k.useRef(null),L=k.useRef(0),B=k.useRef(null),j=k.useRef(0),V=k.useRef({id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1}),[M,z]=k.useState(0),[O,N]=k.useState(null),[q,Q]=k.useState(0),Y=k.useCallback(()=>{B.current!=null&&(cancelAnimationFrame(B.current),B.current=null),L.current=0,Q(x),z(0),N(null),window.setTimeout(()=>Q(0),x)},[x]),re=k.useCallback(async(Z,H)=>{B.current!=null&&(cancelAnimationFrame(B.current),B.current=null);const ie=I.current?.offsetWidth||360;Q(_),N(Z==="right"?"right":"left");const te=Z==="right"?ie+40:-(ie+40);L.current=te,z(te);let ne=!0;if(H)try{ne=Z==="right"?await o():await r()}catch{ne=!1}return ne===!1?(Q(x),N(null),z(0),window.setTimeout(()=>Q(0),x),!1):!0},[_,r,o,x]);return k.useImperativeHandle(D,()=>({swipeLeft:Z=>re("left",Z?.runAction??!0),swipeRight:Z=>re("right",Z?.runAction??!0),reset:()=>Y()}),[re,Y]),v.jsxs("div",{className:nm("relative overflow-hidden rounded-lg",u),children:[v.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-lg",children:[v.jsx("div",{className:nm("absolute inset-0 transition-opacity duration-200 ease-out",M===0?"opacity-0":"opacity-100",M>0?c.className:d.className)}),v.jsx("div",{className:nm("absolute inset-0 flex items-center transition-all duration-200 ease-out"),style:{transform:`translateX(${Math.max(-24,Math.min(24,M/8))}px)`,opacity:M===0?0:1,justifyContent:M>0?"flex-start":"flex-end",paddingLeft:M>0?16:0,paddingRight:M>0?0:16},children:M>0?c.label:d.label})]}),v.jsx("div",{ref:I,className:"relative",style:{transform:M!==0?`translate3d(${M}px,0,0)`:void 0,transition:q?`transform ${q}ms ease`:void 0,touchAction:"pan-y",willChange:M!==0?"transform":void 0},onPointerDown:Z=>{if(!t||i)return;const H=Z.target,K=!!(w&&H?.closest?.(w));if(y&&H?.closest?.(y))return;const ie=Z.currentTarget,ne=Array.from(ie.querySelectorAll("video")).find(fe=>fe.controls);if(ne){const fe=ne.getBoundingClientRect();if(Z.clientX>=fe.left&&Z.clientX<=fe.right&&Z.clientY>=fe.top&&Z.clientY<=fe.bottom){if(fe.bottom-Z.clientY<=72)return;const Ge=64,lt=Z.clientX-fe.left,At=fe.right-Z.clientX;if(!(lt<=Ge||At<=Ge))return}}const ee=Z.currentTarget.getBoundingClientRect().bottom-Z.clientY;if(g&&ee<=g)return;V.current={id:Z.pointerId,x:Z.clientX,y:Z.clientY,dragging:!1,captured:!1,tapIgnored:K};const be=I.current?.offsetWidth||360;j.current=Math.min(f,be*p),L.current=0},onPointerMove:Z=>{if(!t||i||V.current.id!==Z.pointerId)return;const H=Z.clientX-V.current.x,K=Z.clientY-V.current.y;if(!V.current.dragging){if(Math.abs(K)>Math.abs(H)&&Math.abs(K)>8){V.current.id=null;return}if(Math.abs(H)<12)return;V.current.dragging=!0,Q(0);try{Z.currentTarget.setPointerCapture(Z.pointerId),V.current.captured=!0}catch{V.current.captured=!1}}L.current=H,B.current==null&&(B.current=requestAnimationFrame(()=>{B.current=null,z(L.current)}));const ie=j.current,te=H>ie?"right":H<-ie?"left":null;N(ne=>ne===te?ne:te)},onPointerUp:Z=>{if(!t||i||V.current.id!==Z.pointerId)return;const H=j.current||Math.min(f,(I.current?.offsetWidth||360)*p),K=V.current.dragging,ie=V.current.captured,te=V.current.tapIgnored;if(V.current.id=null,V.current.dragging=!1,V.current.captured=!1,ie)try{Z.currentTarget.releasePointerCapture(Z.pointerId)}catch{}if(!K){if(te){Q(0),z(0),N(null);return}Y(),n?.();return}const ne=L.current;B.current!=null&&(cancelAnimationFrame(B.current),B.current=null),ne>H?re("right",!0):ne<-H?re("left",!0):Y(),L.current=0},onPointerCancel:Z=>{if(!(!t||i)){if(V.current.captured&&V.current.id!=null)try{Z.currentTarget.releasePointerCapture(V.current.id)}catch{}V.current={id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1},B.current!=null&&(cancelAnimationFrame(B.current),B.current=null),L.current=0,Y()}},children:v.jsxs("div",{className:"relative",children:[v.jsx("div",{className:"relative z-10",children:e}),v.jsx("div",{className:nm("absolute inset-0 z-20 pointer-events-none transition-opacity duration-150 rounded-lg",O==="right"&&"bg-emerald-500/20 opacity-100",O==="left"&&"bg-red-500/20 opacity-100",O===null&&"opacity-0")})]})})]})});function PO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{d:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"}),k.createElement("path",{fillRule:"evenodd",d:"M1.323 11.447C2.811 6.976 7.028 3.75 12.001 3.75c4.97 0 9.185 3.223 10.675 7.69.12.362.12.752 0 1.113-1.487 4.471-5.705 7.697-10.677 7.697-4.97 0-9.186-3.223-10.675-7.69a1.762 1.762 0 0 1 0-1.113ZM17.25 12a5.25 5.25 0 1 1-10.5 0 5.25 5.25 0 0 1 10.5 0Z",clipRule:"evenodd"}))}const uh=k.forwardRef(PO);function BO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M12.963 2.286a.75.75 0 0 0-1.071-.136 9.742 9.742 0 0 0-3.539 6.176 7.547 7.547 0 0 1-1.705-1.715.75.75 0 0 0-1.152-.082A9 9 0 1 0 15.68 4.534a7.46 7.46 0 0 1-2.717-2.248ZM15.75 14.25a3.75 3.75 0 1 1-7.313-1.172c.628.465 1.35.81 2.133 1a5.99 5.99 0 0 1 1.925-3.546 3.75 3.75 0 0 1 3.255 3.718Z",clipRule:"evenodd"}))}const AS=k.forwardRef(BO);function FO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{d:"M7.493 18.5c-.425 0-.82-.236-.975-.632A7.48 7.48 0 0 1 6 15.125c0-1.75.599-3.358 1.602-4.634.151-.192.373-.309.6-.397.473-.183.89-.514 1.212-.924a9.042 9.042 0 0 1 2.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 0 0 .322-1.672V2.75A.75.75 0 0 1 15 2a2.25 2.25 0 0 1 2.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 0 1-2.649 7.521c-.388.482-.987.729-1.605.729H14.23c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23h-.777ZM2.331 10.727a11.969 11.969 0 0 0-.831 4.398 12 12 0 0 0 .52 3.507C2.28 19.482 3.105 20 3.994 20H4.9c.445 0 .72-.498.523-.898a8.963 8.963 0 0 1-.924-3.977c0-1.708.476-3.305 1.302-4.666.245-.403-.028-.959-.5-.959H4.25c-.832 0-1.612.453-1.918 1.227Z"}))}const UO=k.forwardRef(FO);function jO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{d:"m11.645 20.91-.007-.003-.022-.012a15.247 15.247 0 0 1-.383-.218 25.18 25.18 0 0 1-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0 1 12 5.052 5.5 5.5 0 0 1 16.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 0 1-4.244 3.17 15.247 15.247 0 0 1-.383.219l-.022.012-.007.004-.003.001a.752.752 0 0 1-.704 0l-.003-.001Z"}))}const mc=k.forwardRef(jO);function $O({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M6.75 5.25a.75.75 0 0 1 .75-.75H9a.75.75 0 0 1 .75.75v13.5a.75.75 0 0 1-.75.75H7.5a.75.75 0 0 1-.75-.75V5.25Zm7.5 0A.75.75 0 0 1 15 4.5h1.5a.75.75 0 0 1 .75.75v13.5a.75.75 0 0 1-.75.75H15a.75.75 0 0 1-.75-.75V5.25Z",clipRule:"evenodd"}))}const HO=k.forwardRef($O);function VO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M4.5 5.653c0-1.427 1.529-2.33 2.779-1.643l11.54 6.347c1.295.712 1.295 2.573 0 3.286L7.28 19.99c-1.25.687-2.779-.217-2.779-1.643V5.653Z",clipRule:"evenodd"}))}const GO=k.forwardRef(VO);function zO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M5.636 4.575a.75.75 0 0 1 0 1.061 9 9 0 0 0 0 12.728.75.75 0 1 1-1.06 1.06c-4.101-4.1-4.101-10.748 0-14.849a.75.75 0 0 1 1.06 0Zm12.728 0a.75.75 0 0 1 1.06 0c4.101 4.1 4.101 10.75 0 14.85a.75.75 0 1 1-1.06-1.061 9 9 0 0 0 0-12.728.75.75 0 0 1 0-1.06ZM7.757 6.697a.75.75 0 0 1 0 1.06 6 6 0 0 0 0 8.486.75.75 0 0 1-1.06 1.06 7.5 7.5 0 0 1 0-10.606.75.75 0 0 1 1.06 0Zm8.486 0a.75.75 0 0 1 1.06 0 7.5 7.5 0 0 1 0 10.606.75.75 0 0 1-1.06-1.06 6 6 0 0 0 0-8.486.75.75 0 0 1 0-1.06ZM9.879 8.818a.75.75 0 0 1 0 1.06 3 3 0 0 0 0 4.243.75.75 0 1 1-1.061 1.061 4.5 4.5 0 0 1 0-6.364.75.75 0 0 1 1.06 0Zm4.242 0a.75.75 0 0 1 1.061 0 4.5 4.5 0 0 1 0 6.364.75.75 0 0 1-1.06-1.06 3 3 0 0 0 0-4.243.75.75 0 0 1 0-1.061ZM10.875 12a1.125 1.125 0 1 1 2.25 0 1.125 1.125 0 0 1-2.25 0Z",clipRule:"evenodd"}))}const qO=k.forwardRef(zO);function KO({title:s,titleId:e,...t},i){return k.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?k.createElement("title",{id:e},s):null,k.createElement("path",{fillRule:"evenodd",d:"M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.006 5.404.434c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.434 2.082-5.005Z",clipRule:"evenodd"}))}const ch=k.forwardRef(KO);function la({tag:s,children:e,title:t,active:i,onClick:n,maxWidthClassName:r="max-w-[11rem]",className:o,stopPropagation:u=!0}){const c=s??(typeof e=="string"||typeof e=="number"?String(e):""),d=Ti("inline-flex items-center truncate rounded-md px-2 py-0.5 text-xs",r,"bg-sky-50 text-sky-700 dark:bg-sky-500/10 dark:text-sky-200"),g=Ti(d,i?"bg-sky-100 text-sky-800 dark:bg-sky-400/20 dark:text-sky-100":"",n?"cursor-pointer hover:bg-sky-100 dark:hover:bg-sky-400/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500":"",o),y=_=>_.stopPropagation(),x=u?{onPointerDown:y,onMouseDown:y}:{};return n?v.jsx("button",{type:"button",className:g,title:t??c,"aria-pressed":!!i,...x,onClick:_=>{u&&(_.preventDefault(),_.stopPropagation()),c&&n(c)},children:e??s}):v.jsx("span",{className:g,title:t??c,...x,onClick:u?y:void 0,children:e??s})}function Si(...s){return s.filter(Boolean).join(" ")}const YO=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",WO=s=>s.startsWith("HOT ")?s.slice(4):s,XO=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function QO(s){const t=WO(YO(s||"")).replace(/\.[^.]+$/,""),i=t.match(XO);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function Ko({job:s,variant:e="overlay",collapseToMenu:t=!1,inlineCount:i,busy:n=!1,compact:r=!1,isHot:o=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,showFavorite:f,showLike:p,showHot:g,showKeep:y,showDelete:x,showWatch:_,showDetails:w,onToggleFavorite:D,onToggleLike:I,onToggleHot:L,onKeep:B,onDelete:j,onToggleWatch:V,order:M,className:z}){const O=e==="overlay"?r?"p-1.5":"p-2":"p-1.5",N=r?"size-4":"size-5",q="h-full w-full",Q=e==="table"?`inline-flex items-center justify-center rounded-md ${O} hover:bg-gray-100/70 dark:hover:bg-white/5 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/60 disabled:opacity-50 disabled:cursor-not-allowed transition-transform active:scale-95`:`inline-flex items-center justify-center rounded-md bg-white/75 ${O} text-gray-900 backdrop-blur ring-1 ring-black/10 hover:bg-white/90 dark:bg-black/40 dark:text-white dark:ring-white/10 dark:hover:bg-black/60 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/60 dark:focus-visible:ring-white/40 disabled:opacity-50 disabled:cursor-not-allowed transition-transform active:scale-95`,Y=e==="table"?{favOn:"text-amber-600 dark:text-amber-300",likeOn:"text-rose-600 dark:text-rose-300",hotOn:"text-amber-600 dark:text-amber-300",off:"text-gray-500 dark:text-gray-300",keep:"text-emerald-600 dark:text-emerald-300",del:"text-red-600 dark:text-red-300",watchOn:"text-sky-600 dark:text-sky-300"}:{favOn:"text-amber-600 dark:text-amber-300",likeOn:"text-rose-600 dark:text-rose-300",hotOn:"text-amber-600 dark:text-amber-300",off:"text-gray-800/90 dark:text-white/90",keep:"text-emerald-600 dark:text-emerald-200",del:"text-red-600 dark:text-red-300",watchOn:"text-sky-600 dark:text-sky-200"},re=f??!!D,Z=p??!!I,H=g??!!L,K=y??!!B,ie=x??!!j,te=_??!!V,ne=w??!0,$=QO(s.output||""),ee=$?`Mehr zu ${$} anzeigen`:"Mehr anzeigen",[le,be]=k.useState(0),[fe,_e]=k.useState(4),Me=Nt=>bt=>{bt.preventDefault(),bt.stopPropagation(),!(n||!Nt)&&Promise.resolve(Nt(s)).catch(()=>{})},et=ne&&$?v.jsxs("button",{type:"button",className:Si(Q),title:ee,"aria-label":ee,disabled:n,onClick:Nt=>{Nt.preventDefault(),Nt.stopPropagation(),!n&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:$}}))},children:[v.jsx("span",{className:Si("inline-flex items-center justify-center",N),children:v.jsx(ES,{className:Si(q,Y.off)})}),v.jsx("span",{className:"sr-only",children:ee})]}):null,Ge=re?v.jsx("button",{type:"button",className:Q,title:u?"Favorit entfernen":"Als Favorit markieren","aria-label":u?"Favorit entfernen":"Als Favorit markieren","aria-pressed":u,disabled:n||!D,onClick:Me(D),children:v.jsxs("span",{className:Si("relative inline-block",N),children:[v.jsx(Bv,{className:Si("absolute inset-0 transition-all duration-200 ease-out motion-reduce:transition-none",u?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",q,Y.off)}),v.jsx(ch,{className:Si("absolute inset-0 transition-all duration-200 ease-out motion-reduce:transition-none",u?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",q,Y.favOn)})]})}):null,lt=Z?v.jsx("button",{type:"button",className:Q,title:c?"Gefällt mir entfernen":"Als Gefällt mir markieren","aria-label":c?"Gefällt mir entfernen":"Als Gefällt mir markieren","aria-pressed":c,disabled:n||!I,onClick:Me(I),children:v.jsxs("span",{className:Si("relative inline-block",N),children:[v.jsx(Wm,{className:Si("absolute inset-0 transition-all duration-200 ease-out motion-reduce:transition-none",c?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",q,Y.off)}),v.jsx(mc,{className:Si("absolute inset-0 transition-all duration-200 ease-out motion-reduce:transition-none",c?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",q,Y.likeOn)})]})}):null,At=H?v.jsx("button",{type:"button",className:Q,title:o?"HOT entfernen":"Als HOT markieren","aria-label":o?"HOT entfernen":"Als HOT markieren","aria-pressed":o,disabled:n||!L,onClick:Me(L),children:v.jsxs("span",{className:Si("relative inline-block",N),children:[v.jsx(SS,{className:Si("absolute inset-0 transition-all duration-200 ease-out",o?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",q,Y.off)}),v.jsx(AS,{className:Si("absolute inset-0 transition-all duration-200 ease-out",o?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",q,Y.hotOn)})]})}):null,mt=te?v.jsx("button",{type:"button",className:Q,title:d?"Watched entfernen":"Als Watched markieren","aria-label":d?"Watched entfernen":"Als Watched markieren","aria-pressed":d,disabled:n||!V,onClick:Me(V),children:v.jsxs("span",{className:Si("relative inline-block",N),children:[v.jsx(Pv,{className:Si("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",q,Y.off)}),v.jsx(uh,{className:Si("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",q,Y.watchOn)})]})}):null,Vt=K?v.jsx("button",{type:"button",className:Q,title:"Behalten (nach keep verschieben)","aria-label":"Behalten",disabled:n||!B,onClick:Me(B),children:v.jsx("span",{className:Si("inline-flex items-center justify-center",N),children:v.jsx(Mv,{className:Si(q,Y.keep)})})}):null,Re=ie?v.jsx("button",{type:"button",className:Q,title:"Löschen","aria-label":"Löschen",disabled:n||!j,onClick:Me(j),children:v.jsx("span",{className:Si("inline-flex items-center justify-center",N),children:v.jsx(Fv,{className:Si(q,Y.del)})})}):null,dt=M??["watch","favorite","like","hot","keep","delete","details"],He={details:et,favorite:Ge,like:lt,watch:mt,hot:At,keep:Vt,delete:Re},tt=t&&e==="overlay",nt=dt.filter(Nt=>!!He[Nt]),ot=tt&&typeof i!="number",yt=(r?16:20)+(e==="overlay"?r?6:8:6)*2,Gt=r?2:3,Ut=k.useMemo(()=>{if(!ot)return i??Gt;const Nt=le||0;if(Nt<=0)return Math.min(nt.length,Gt);for(let bt=nt.length;bt>=0;bt--)if(bt*yt+yt+(bt>0?bt*fe:0)<=Nt)return bt;return 0},[ot,i,Gt,le,nt.length,yt,fe]),ai=tt?nt.slice(0,Ut):nt,Zt=tt?nt.slice(Ut):[],[$e,ct]=k.useState(!1),it=k.useRef(null);k.useLayoutEffect(()=>{const Nt=it.current;if(!Nt||typeof window>"u")return;const bt=()=>{const bi=it.current;if(!bi)return;const G=Math.floor(bi.getBoundingClientRect().width||0);G>0&&be(G);const W=window.getComputedStyle(bi),oe=W.columnGap||W.gap||"0",Ee=parseFloat(oe);Number.isFinite(Ee)&&Ee>=0&&_e(Ee)};bt();const xi=new ResizeObserver(()=>bt());return xi.observe(Nt),window.addEventListener("resize",bt),()=>{window.removeEventListener("resize",bt),xi.disconnect()}},[]);const Tt=k.useRef(null),Wt=k.useRef(null),Xe=208,Ot=4,kt=8,[Xt,ni]=k.useState(null);k.useEffect(()=>{if(!$e)return;const Nt=xi=>{xi.key==="Escape"&&ct(!1)},bt=xi=>{const bi=it.current,G=Wt.current,W=xi.target;bi&&bi.contains(W)||G&&G.contains(W)||ct(!1)};return window.addEventListener("keydown",Nt),window.addEventListener("mousedown",bt),()=>{window.removeEventListener("keydown",Nt),window.removeEventListener("mousedown",bt)}},[$e]),k.useLayoutEffect(()=>{if(!$e){ni(null);return}const Nt=()=>{const bt=Tt.current;if(!bt)return;const xi=bt.getBoundingClientRect(),bi=window.innerWidth,G=window.innerHeight;let W=xi.right-Xe;W=Math.max(kt,Math.min(W,bi-Xe-kt));let oe=xi.bottom+Ot;oe=Math.max(kt,Math.min(oe,G-kt));const Ee=Math.max(120,G-oe-kt);ni({top:oe,left:W,maxH:Ee})};return Nt(),window.addEventListener("resize",Nt),window.addEventListener("scroll",Nt,!0),()=>{window.removeEventListener("resize",Nt),window.removeEventListener("scroll",Nt,!0)}},[$e]);const hi=()=>{$&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:$}}))},Ai=Nt=>Nt==="details"?v.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n,onClick:bt=>{bt.preventDefault(),bt.stopPropagation(),ct(!1),hi()},children:[v.jsx(ES,{className:Si("size-4",Y.off)}),v.jsx("span",{className:"truncate",children:"Details"})]},"details"):Nt==="favorite"?v.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!D,onClick:async bt=>{bt.preventDefault(),bt.stopPropagation(),ct(!1),await D?.(s)},children:[u?v.jsx(ch,{className:Si("size-4",Y.favOn)}):v.jsx(Bv,{className:Si("size-4",Y.off)}),v.jsx("span",{className:"truncate",children:u?"Favorit entfernen":"Als Favorit markieren"})]},"favorite"):Nt==="like"?v.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!I,onClick:async bt=>{bt.preventDefault(),bt.stopPropagation(),ct(!1),await I?.(s)},children:[c?v.jsx(mc,{className:Si("size-4",Y.favOn)}):v.jsx(Wm,{className:Si("size-4",Y.off)}),v.jsx("span",{className:"truncate",children:c?"Gefällt mir entfernen":"Gefällt mir"})]},"like"):Nt==="watch"?v.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!V,onClick:async bt=>{bt.preventDefault(),bt.stopPropagation(),ct(!1),await V?.(s)},children:[d?v.jsx(uh,{className:Si("size-4",Y.favOn)}):v.jsx(Pv,{className:Si("size-4",Y.off)}),v.jsx("span",{className:"truncate",children:d?"Watched entfernen":"Watched"})]},"watch"):Nt==="hot"?v.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!L,onClick:async bt=>{bt.preventDefault(),bt.stopPropagation(),ct(!1),await L?.(s)},children:[o?v.jsx(AS,{className:Si("size-4",Y.favOn)}):v.jsx(SS,{className:Si("size-4",Y.off)}),v.jsx("span",{className:"truncate",children:o?"HOT entfernen":"Als HOT markieren"})]},"hot"):Nt==="keep"?v.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!B,onClick:async bt=>{bt.preventDefault(),bt.stopPropagation(),ct(!1),await B?.(s)},children:[v.jsx(Mv,{className:Si("size-4",Y.keep)}),v.jsx("span",{className:"truncate",children:"Behalten"})]},"keep"):Nt==="delete"?v.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-100/70 dark:hover:bg-white/5 disabled:opacity-50",disabled:n||!j,onClick:async bt=>{bt.preventDefault(),bt.stopPropagation(),ct(!1),await j?.(s)},children:[v.jsx(Fv,{className:Si("size-4",Y.del)}),v.jsx("span",{className:"truncate",children:"Löschen"})]},"delete"):null;return v.jsxs("div",{ref:it,className:Si("relative flex items-center flex-nowrap",z??"gap-2"),children:[ai.map(Nt=>{const bt=He[Nt];return bt?v.jsx(k.Fragment,{children:bt},Nt):null}),tt&&Zt.length>0?v.jsxs("div",{className:"relative",children:[v.jsx("button",{ref:Tt,type:"button",className:Q,"aria-label":"Mehr",title:"Mehr","aria-haspopup":"menu","aria-expanded":$e,disabled:n,onClick:Nt=>{Nt.preventDefault(),Nt.stopPropagation(),!n&&ct(bt=>!bt)},children:v.jsx("span",{className:Si("inline-flex items-center justify-center",N),children:v.jsx(iO,{className:Si(q,Y.off)})})}),$e&&Xt&&typeof document<"u"?Sh.createPortal(v.jsx("div",{ref:Wt,role:"menu",className:"rounded-md bg-white/95 dark:bg-gray-900/95 shadow-lg ring-1 ring-black/10 dark:ring-white/10 p-1 z-[9999] overflow-auto",style:{position:"fixed",top:Xt.top,left:Xt.left,width:Xe,maxHeight:Xt.maxH},onClick:Nt=>Nt.stopPropagation(),children:Zt.map(Ai)}),document.body):null]}):null]})}function Hx({children:s,force:e=!1,rootMargin:t="300px",placeholder:i=null,className:n}){const r=k.useRef(null),[o,u]=k.useState(e);return k.useEffect(()=>{e&&!o&&u(!0)},[e,o]),k.useEffect(()=>{if(o||e)return;const c=r.current;if(!c)return;const d=new IntersectionObserver(f=>{f.some(p=>p.isIntersecting)&&(u(!0),d.disconnect())},{rootMargin:t});return d.observe(c),()=>d.disconnect()},[o,e,t]),v.jsx("div",{ref:r,className:n,children:o?s:i})}function ZO(...s){return s.filter(Boolean).join(" ")}const JO=s=>{const e=String(s??"").trim();if(!e)return[];const t=e.split(/[\n,;|]+/g).map(r=>r.trim()).filter(Boolean),i=new Set,n=[];for(const r of t){const o=r.toLowerCase();i.has(o)||(i.add(o),n.push(r))}return n};function eM({rows:s,isSmall:e,teaserPlayback:t,teaserAudio:i,hoverTeaserKey:n,blurPreviews:r,durations:o,teaserKey:u,inlinePlay:c,setInlinePlay:d,deletingKeys:f,keepingKeys:p,removingKeys:g,swipeRefs:y,keyFor:x,baseName:_,stripHotPrefix:w,modelNameFromOutput:D,runtimeOf:I,sizeBytesOf:L,formatBytes:B,lower:j,onHoverPreviewKeyChange:V,onOpenPlayer:M,openPlayer:z,startInline:O,tryAutoplayInline:N,registerTeaserHost:q,handleDuration:Q,deleteVideo:Y,keepVideo:re,releasePlayingFile:Z,modelsByKey:H,activeTagSet:K,onToggleTagFilter:ie,onToggleHot:te,onToggleFavorite:ne,onToggleLike:$,onToggleWatch:ee}){const[le,be]=k.useState(null),fe=k.useRef(null);return k.useEffect(()=>{if(!le)return;const _e=et=>{et.key==="Escape"&&be(null)},Me=et=>{const Ge=fe.current;Ge&&(Ge.contains(et.target)||be(null))};return document.addEventListener("keydown",_e),document.addEventListener("pointerdown",Me),()=>{document.removeEventListener("keydown",_e),document.removeEventListener("pointerdown",Me)}},[le]),k.useEffect(()=>{if(!le)return;s.some(Me=>x(Me)===le)||be(null)},[s,x,le]),v.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:s.map(_e=>{const Me=x(_e),et=c?.key===Me,lt=!(!!i&&(et||n===Me)),At=et?c?.nonce??0:0,mt=f.has(Me)||p.has(Me)||g.has(Me),Vt=D(_e.output),Re=_(_e.output||""),dt=Re.startsWith("HOT "),He=H[j(Vt)],tt=!!He?.favorite,nt=He?.liked===!0,ot=!!He?.watching,Ke=JO(He?.tags),pt=Ke.slice(0,6),yt=Ke.length-pt.length,Gt=Ke.join(", "),Ut=_e.status==="failed"?"bg-red-500/35":_e.status==="finished"?"bg-emerald-500/35":_e.status==="stopped"?"bg-amber-500/35":"bg-black/40",ai=I(_e),Zt=B(L(_e)),$e=`inline-prev-${encodeURIComponent(Me)}`,ct=v.jsx("div",{role:"button",tabIndex:0,className:["group","transition-all duration-300 ease-in-out","rounded-xl hover:-translate-y-0.5 hover:shadow-md dark:hover:shadow-none","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500",mt&&"pointer-events-none",f.has(Me)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30 animate-pulse",p.has(Me)&&"ring-1 ring-emerald-300 bg-emerald-50/60 dark:bg-emerald-500/10 dark:ring-emerald-500/30 animate-pulse",g.has(Me)&&"opacity-0 translate-y-2 scale-[0.98]"].filter(Boolean).join(" "),onClick:e?void 0:()=>z(_e),onKeyDown:it=>{(it.key==="Enter"||it.key===" ")&&M(_e)},children:v.jsxs(za,{noBodyPadding:!0,className:"overflow-hidden",children:[v.jsxs("div",{id:$e,ref:q(Me),className:"relative aspect-video bg-black/5 dark:bg-white/5",onMouseEnter:()=>V?.(Me),onMouseLeave:()=>V?.(null),onClick:it=>{it.preventDefault(),it.stopPropagation(),!e&&O(Me)},children:[v.jsx(Hx,{force:et||u===Me||n===Me,rootMargin:"500px",placeholder:v.jsx("div",{className:"w-full h-full bg-black/5 dark:bg-white/5 animate-pulse"}),className:"absolute inset-0",children:v.jsx(jx,{job:_e,getFileName:it=>w(_(it)),durationSeconds:o[Me]??_e?.durationSeconds,onDuration:Q,className:"w-full h-full",showPopover:!1,blur:et?!1:r,animated:t==="all"?!0:t==="hover"?u===Me:!1,animatedMode:"teaser",animatedTrigger:"always",inlineVideo:et?"always":!1,inlineNonce:At,inlineControls:et,inlineLoop:!1,muted:lt,popoverMuted:lt})}),v.jsx("div",{className:["pointer-events-none absolute inset-x-0 bottom-0 h-20 bg-gradient-to-t from-black/70 to-transparent","transition-opacity duration-150",et?"opacity-0":"opacity-100"].join(" ")}),v.jsx("div",{className:["pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white","transition-opacity duration-150",et?"opacity-0":"opacity-100"].join(" "),children:v.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] opacity-90",children:[v.jsx("span",{className:ZO("rounded px-1.5 py-0.5 font-semibold",Ut),children:_e.status}),v.jsxs("div",{className:"flex items-center gap-1.5",children:[v.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:ai}),v.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:Zt})]})]})}),!e&&c?.key===Me&&v.jsx("button",{type:"button",className:"absolute left-2 top-2 z-10 rounded-md bg-black/40 px-2 py-1 text-xs font-semibold text-white backdrop-blur hover:bg-black/60",onClick:it=>{it.preventDefault(),it.stopPropagation(),d(Tt=>({key:Me,nonce:Tt?.key===Me?Tt.nonce+1:1}))},title:"Von vorne starten","aria-label":"Von vorne starten",children:"↻"}),v.jsx("div",{className:"absolute right-2 top-2 flex items-center gap-2",onClick:it=>it.stopPropagation(),onMouseDown:it=>it.stopPropagation(),children:v.jsx(Ko,{job:_e,variant:"overlay",busy:mt,isHot:dt,isFavorite:tt,isLiked:nt,isWatching:ot,onToggleWatch:ee,onToggleFavorite:ne,onToggleLike:$,onToggleHot:te?async it=>{const Tt=_(it.output||"");Tt&&(await Z(Tt,{close:!0}),await new Promise(Wt=>setTimeout(Wt,150))),await te(it)}:void 0,showKeep:!e,showDelete:!e,onKeep:re,onDelete:Y,order:["watch","favorite","like","hot","details","keep","delete"],className:"flex items-center gap-2"})})]}),v.jsxs("div",{className:"px-4 py-3 rounded-b-lg border-t border-gray-200/60 bg-white/60 backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:Vt}),v.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[ot?v.jsx(uh,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,nt?v.jsx(mc,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,tt?v.jsx(ch,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),v.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[v.jsx("span",{className:"truncate",children:w(Re)||"—"}),dt?v.jsx("span",{className:"shrink-0 rounded bg-amber-500/15 px-1.5 py-0.5 text-[11px] font-semibold text-amber-800 dark:text-amber-300",children:"HOT"}):null]}),v.jsxs("div",{className:"mt-2 h-6 relative flex items-center gap-1.5",onClick:it=>it.stopPropagation(),onMouseDown:it=>it.stopPropagation(),children:[v.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:v.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:pt.length>0?pt.map(it=>v.jsx(la,{tag:it,active:K.has(j(it)),onClick:ie},it)):v.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),yt>0?v.jsxs("button",{type:"button",className:"shrink-0 inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-700 ring-1 ring-inset ring-gray-200 hover:bg-gray-200/70 dark:bg-white/5 dark:text-gray-200 dark:ring-white/10 dark:hover:bg-white/10",title:Gt,"aria-haspopup":"dialog","aria-expanded":le===Me,onPointerDown:it=>it.stopPropagation(),onClick:it=>{it.preventDefault(),it.stopPropagation(),be(Tt=>Tt===Me?null:Me)},children:["+",yt]}):null,le===Me?v.jsxs("div",{ref:fe,className:"absolute right-0 bottom-8 z-30 w-72 max-w-[calc(100vw-2rem)] overflow-hidden rounded-lg border border-gray-200/70 bg-white/95 shadow-lg ring-1 ring-black/5 backdrop-blur dark:border-white/10 dark:bg-gray-950/90 dark:ring-white/10",onClick:it=>it.stopPropagation(),onMouseDown:it=>it.stopPropagation(),children:[v.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-gray-200/60 px-3 py-2 dark:border-white/10",children:[v.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Tags"}),v.jsx("button",{type:"button",className:"rounded px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-white/10",onClick:()=>be(null),"aria-label":"Schließen",title:"Schließen",children:"✕"})]}),v.jsx("div",{className:"max-h-48 overflow-auto p-2",children:v.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ke.map(it=>v.jsx(la,{tag:it,active:K.has(j(it)),onClick:ie},it))})})]}):null]})]})]})});return e?v.jsx(MO,{ref:it=>{it?y.current.set(Me,it):y.current.delete(Me)},enabled:!0,disabled:mt,ignoreFromBottomPx:110,onTap:()=>{const it=`inline-prev-${encodeURIComponent(Me)}`;O(Me),requestAnimationFrame(()=>{N(it)||requestAnimationFrame(()=>N(it))})},onSwipeLeft:()=>Y(_e),onSwipeRight:()=>re(_e),children:ct},Me):v.jsx(k.Fragment,{children:ct},Me)})})}function tM({rows:s,columns:e,getRowKey:t,sort:i,onSortChange:n,onRowClick:r,rowClassName:o}){return v.jsx(Ux,{rows:s,columns:e,getRowKey:t,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,sort:i,onSortChange:n,onRowClick:r,rowClassName:o})}function iM({rows:s,blurPreviews:e,durations:t,teaserPlayback:i,teaserAudio:n,hoverTeaserKey:r,teaserKey:o,handleDuration:u,keyFor:c,baseName:d,stripHotPrefix:f,modelNameFromOutput:p,runtimeOf:g,sizeBytesOf:y,formatBytes:x,deletingKeys:_,keepingKeys:w,removingKeys:D,deletedKeys:I,registerTeaserHost:L,onHoverPreviewKeyChange:B,onOpenPlayer:j,deleteVideo:V,keepVideo:M,onToggleHot:z,lower:O,modelsByKey:N,activeTagSet:q,onToggleTagFilter:Q,onToggleFavorite:Y,onToggleLike:re,onToggleWatch:Z}){const[H,K]=k.useState(null),ie=k.useRef(null);k.useEffect(()=>{if(!H)return;const ne=ee=>{ee.key==="Escape"&&K(null)},$=ee=>{const le=ie.current;le&&(le.contains(ee.target)||K(null))};return document.addEventListener("keydown",ne),document.addEventListener("pointerdown",$),()=>{document.removeEventListener("keydown",ne),document.removeEventListener("pointerdown",$)}},[H]),k.useEffect(()=>{if(!H)return;s.some($=>c($)===H)||K(null)},[s,c,H]);const te=ne=>{const $=String(ne??"").trim();if(!$)return[];const ee=$.split(/[\n,;|]+/g).map(fe=>fe.trim()).filter(Boolean),le=new Set,be=[];for(const fe of ee){const _e=fe.toLowerCase();le.has(_e)||(le.add(_e),be.push(fe))}return be};return v.jsx(v.Fragment,{children:v.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4",children:s.map(ne=>{const $=c(ne),le=!(!!n&&r===$),be=p(ne.output),fe=O(be),_e=N[fe],Me=!!_e?.favorite,et=_e?.liked===!0,Ge=!!_e?.watching,lt=te(_e?.tags),At=lt.slice(0,6),mt=lt.length-At.length,Vt=lt.join(", "),Re=d(ne.output||""),dt=Re.startsWith("HOT "),He=g(ne),tt=x(y(ne)),nt=_.has($)||w.has($)||D.has($),ot=I.has($);return v.jsxs("div",{role:"button",tabIndex:0,className:["group relative rounded-lg overflow-hidden outline-1 outline-black/5 dark:-outline-offset-1 dark:outline-white/10","bg-white dark:bg-gray-900/40","transition-all duration-200","hover:-translate-y-0.5 hover:shadow-md dark:hover:shadow-none","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500",nt&&"pointer-events-none opacity-70",_.has($)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30",D.has($)&&"opacity-0 translate-y-2 scale-[0.98]",ot&&"hidden"].filter(Boolean).join(" "),onClick:()=>j(ne),onKeyDown:Ke=>{(Ke.key==="Enter"||Ke.key===" ")&&j(ne)},children:[v.jsxs("div",{className:"group relative aspect-video rounded-t-lg bg-black/5 dark:bg-white/5",ref:L($),onMouseEnter:()=>B?.($),onMouseLeave:()=>B?.(null),children:[v.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-t-lg",children:[v.jsx(Hx,{force:o===$||r===$,rootMargin:"500px",placeholder:v.jsx("div",{className:"absolute inset-0 bg-black/5 dark:bg-white/5 animate-pulse"}),className:"absolute inset-0",children:v.jsx(jx,{job:ne,getFileName:Ke=>f(d(Ke)),durationSeconds:t[$]??ne?.durationSeconds,onDuration:u,variant:"fill",showPopover:!1,blur:e,animated:i==="all"?!0:i==="hover"?o===$:!1,animatedMode:"teaser",animatedTrigger:"always",clipSeconds:1,thumbSamples:18,muted:le,popoverMuted:le})}),v.jsx("div",{className:` + pointer-events-none absolute inset-x-0 bottom-0 h-16 + bg-gradient-to-t from-black/65 to-transparent + transition-opacity duration-150 + group-hover:opacity-0 group-focus-within:opacity-0 + `}),v.jsx("div",{className:` + pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white + `,children:v.jsxs("div",{className:"flex items-end justify-between gap-2",children:[v.jsx("div",{className:"min-w-0",children:v.jsx("div",{children:v.jsx("span",{className:["inline-block rounded px-1.5 py-0.5 text-[11px] font-semibold",ne.status==="finished"?"bg-emerald-600/70":ne.status==="stopped"?"bg-amber-600/70":ne.status==="failed"?"bg-red-600/70":"bg-black/50"].join(" "),children:ne.status})})}),v.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[v.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:He}),v.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:tt})]})]})})]}),v.jsx("div",{className:"absolute inset-x-2 top-2 z-10 flex justify-end",onClick:Ke=>Ke.stopPropagation(),children:v.jsx(Ko,{job:ne,variant:"overlay",busy:nt,collapseToMenu:!0,isHot:dt,isFavorite:Me,isLiked:et,isWatching:Ge,onToggleWatch:Z,onToggleFavorite:Y,onToggleLike:re,onToggleHot:z,onKeep:M,onDelete:V,order:["watch","favorite","like","hot","keep","delete","details"],className:"w-full justify-end gap-1"})})]}),v.jsxs("div",{className:"px-4 py-3 rounded-b-lg border-t border-gray-200/60 bg-white/60 backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:be}),v.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[Ge?v.jsx(uh,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,et?v.jsx(mc,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,Me?v.jsx(ch,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),v.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[v.jsx("span",{className:"truncate",children:f(Re)||"—"}),dt?v.jsx("span",{className:"shrink-0 rounded bg-amber-500/15 px-1.5 py-0.5 text-[11px] font-semibold text-amber-800 dark:text-amber-300",children:"HOT"}):null]}),v.jsxs("div",{className:"mt-2 h-6 relative flex items-center gap-1.5",onClick:Ke=>Ke.stopPropagation(),onMouseDown:Ke=>Ke.stopPropagation(),children:[v.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:v.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:At.length>0?At.map(Ke=>v.jsx(la,{tag:Ke,active:q.has(O(Ke)),onClick:Q},Ke)):v.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),mt>0?v.jsxs("button",{type:"button",className:"shrink-0 inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-700 ring-1 ring-inset ring-gray-200 hover:bg-gray-200/70 dark:bg-white/5 dark:text-gray-200 dark:ring-white/10 dark:hover:bg-white/10",title:Vt,"aria-haspopup":"dialog","aria-expanded":H===$,onPointerDown:Ke=>Ke.stopPropagation(),onClick:Ke=>{Ke.preventDefault(),Ke.stopPropagation(),K(pt=>pt===$?null:$)},children:["+",mt]}):null,H===$?v.jsxs("div",{ref:ie,className:"absolute right-0 bottom-8 z-30 w-72 max-w-[calc(100vw-2rem)] overflow-hidden rounded-lg border border-gray-200/70 bg-white/95 shadow-lg ring-1 ring-black/5 backdrop-blur dark:border-white/10 dark:bg-gray-950/90 dark:ring-white/10",onClick:Ke=>Ke.stopPropagation(),onMouseDown:Ke=>Ke.stopPropagation(),children:[v.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-gray-200/60 px-3 py-2 dark:border-white/10",children:[v.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Tags"}),v.jsx("button",{type:"button",className:"rounded px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-white/10",onClick:()=>K(null),"aria-label":"Schließen",title:"Schließen",children:"✕"})]}),v.jsx("div",{className:"max-h-48 overflow-auto p-2",children:v.jsx("div",{className:"flex flex-wrap gap-1.5",children:lt.map(Ke=>v.jsx(la,{tag:Ke,active:q.has(O(Ke)),onClick:Q},Ke))})})]}):null]})]})]},$)})})})}function CS(s,e,t){return Math.max(e,Math.min(t,s))}function py(s,e){const t=[];for(let i=s;i<=e;i++)t.push(i);return t}function sM(s,e,t,i){if(s<=1)return[1];const n=1,r=s,o=py(n,Math.min(t,r)),u=py(Math.max(r-t+1,t+1),r),c=Math.max(Math.min(e-i,r-t-i*2-1),t+1),d=Math.min(Math.max(e+i,t+i*2+2),r-t),f=[];f.push(...o),c>t+1?f.push("ellipsis"):t+1t&&f.push(r-t),f.push(...u);const p=new Set;return f.filter(g=>{const y=String(g);return p.has(y)?!1:(p.add(y),!0)})}function nM({active:s,disabled:e,rounded:t,onClick:i,children:n,title:r}){const o=t==="l"?"rounded-l-md":t==="r"?"rounded-r-md":"";return v.jsx("button",{type:"button",disabled:e,onClick:e?void 0:i,title:r,className:Ti("relative inline-flex items-center px-4 py-2 text-sm font-semibold focus:z-20 focus:outline-offset-0",o,e?"opacity-50 cursor-not-allowed":"cursor-pointer",s?"z-10 bg-indigo-600 text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:focus-visible:outline-indigo-500":"text-gray-900 inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:text-gray-200 dark:inset-ring-gray-700 dark:hover:bg-white/5"),"aria-current":s?"page":void 0,children:n})}function yA({page:s,pageSize:e,totalItems:t,onPageChange:i,siblingCount:n=1,boundaryCount:r=1,showSummary:o=!0,className:u,ariaLabel:c="Pagination",prevLabel:d="Previous",nextLabel:f="Next"}){const p=Math.max(1,Math.ceil((t||0)/Math.max(1,e||1))),g=CS(s||1,1,p);if(p<=1)return null;const y=t===0?0:(g-1)*e+1,x=Math.min(g*e,t),_=sM(p,g,r,n),w=D=>i(CS(D,1,p));return v.jsxs("div",{className:Ti("flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6 dark:border-white/10 dark:bg-transparent",u),children:[v.jsxs("div",{className:"flex flex-1 justify-between sm:hidden",children:[v.jsx("button",{type:"button",onClick:()=>w(g-1),disabled:g<=1,className:"relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-white/10 dark:bg-white/5 dark:text-gray-200 dark:hover:bg-white/10",children:d}),v.jsx("button",{type:"button",onClick:()=>w(g+1),disabled:g>=p,className:"relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-white/10 dark:bg-white/5 dark:text-gray-200 dark:hover:bg-white/10",children:f})]}),v.jsxs("div",{className:"hidden sm:flex sm:flex-1 sm:items-center sm:justify-between",children:[v.jsx("div",{children:o?v.jsxs("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:["Showing ",v.jsx("span",{className:"font-medium",children:y})," to"," ",v.jsx("span",{className:"font-medium",children:x})," of"," ",v.jsx("span",{className:"font-medium",children:t})," results"]}):null}),v.jsx("div",{children:v.jsxs("nav",{"aria-label":c,className:"isolate inline-flex -space-x-px rounded-md shadow-xs dark:shadow-none",children:[v.jsxs("button",{type:"button",onClick:()=>w(g-1),disabled:g<=1,className:"relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 inset-ring inset-ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed dark:inset-ring-gray-700 dark:hover:bg-white/5",children:[v.jsx("span",{className:"sr-only",children:d}),v.jsx(B5,{"aria-hidden":"true",className:"size-5"})]}),_.map((D,I)=>D==="ellipsis"?v.jsx("span",{className:"relative inline-flex items-center px-4 py-2 text-sm font-semibold text-gray-700 inset-ring inset-ring-gray-300 dark:text-gray-400 dark:inset-ring-gray-700",children:"…"},`e-${I}`):v.jsx(nM,{active:D===g,onClick:()=>w(D),rounded:"none",children:D},D)),v.jsxs("button",{type:"button",onClick:()=>w(g+1),disabled:g>=p,className:"relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 inset-ring inset-ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed dark:inset-ring-gray-700 dark:hover:bg-white/5",children:[v.jsx("span",{className:"sr-only",children:f}),v.jsx(U5,{"aria-hidden":"true",className:"size-5"})]})]})})]})]})}const vA=k.createContext(null);function rM(s){switch(s){case"success":return{Icon:eO,cls:"text-emerald-500"};case"error":return{Icon:NO,cls:"text-rose-500"};case"warning":return{Icon:nO,cls:"text-amber-500"};default:return{Icon:dO,cls:"text-sky-500"}}}function aM(s){switch(s){case"success":return"border-emerald-200/70 dark:border-emerald-400/20";case"error":return"border-rose-200/70 dark:border-rose-400/20";case"warning":return"border-amber-200/70 dark:border-amber-400/20";default:return"border-sky-200/70 dark:border-sky-400/20"}}function oM(s){switch(s){case"success":return"Erfolg";case"error":return"Fehler";case"warning":return"Hinweis";default:return"Info"}}function lM(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function uM({children:s,maxToasts:e=3,defaultDurationMs:t=3500,position:i="bottom-right"}){const[n,r]=k.useState([]),o=k.useCallback(y=>{r(x=>x.filter(_=>_.id!==y))},[]),u=k.useCallback(()=>r([]),[]),c=k.useCallback(y=>{const x=lM(),_=y.durationMs??t;return r(w=>[{...y,id:x,durationMs:_},...w].slice(0,Math.max(1,e))),_&&_>0&&window.setTimeout(()=>o(x),_),x},[t,e,o]),d=k.useMemo(()=>({push:c,remove:o,clear:u}),[c,o,u]),f=i==="top-right"||i==="top-left"?"items-start sm:items-start sm:justify-start":"items-end sm:items-end sm:justify-end",p=i.endsWith("left")?"sm:items-start":"sm:items-end",g=i.startsWith("top")?"top-0 bottom-auto":"bottom-0 top-auto";return v.jsxs(vA.Provider,{value:d,children:[s,v.jsx("div",{"aria-live":"assertive",className:["pointer-events-none fixed z-[80] inset-x-0",g].join(" "),children:v.jsx("div",{className:["flex w-full px-4 py-6 sm:p-6",f].join(" "),children:v.jsx("div",{className:["flex w-full flex-col space-y-3",p].join(" "),children:n.map(y=>{const{Icon:x,cls:_}=rM(y.type),w=(y.title||"").trim()||oM(y.type),D=(y.message||"").trim();return v.jsx(Jd,{appear:!0,show:!0,children:v.jsx("div",{className:["pointer-events-auto w-full max-w-sm overflow-hidden rounded-xl","border bg-white/90 shadow-lg backdrop-blur","outline-1 outline-black/5","dark:bg-gray-950/70 dark:-outline-offset-1 dark:outline-white/10",aM(y.type),"transition data-closed:opacity-0 data-enter:transform data-enter:duration-200 data-enter:ease-out","data-closed:data-enter:translate-y-2 sm:data-closed:data-enter:translate-y-0",i.endsWith("right")?"sm:data-closed:data-enter:translate-x-2":"sm:data-closed:data-enter:-translate-x-2"].join(" "),children:v.jsx("div",{className:"p-4",children:v.jsxs("div",{className:"flex items-start gap-3",children:[v.jsx("div",{className:"shrink-0",children:v.jsx(x,{className:["size-6",_].join(" "),"aria-hidden":"true"})}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:w}),D?v.jsx("p",{className:"mt-1 text-sm text-gray-600 dark:text-gray-300 break-words",children:D}):null]}),v.jsxs("button",{type:"button",onClick:()=>o(y.id),className:"shrink-0 rounded-md text-gray-400 hover:text-gray-600 focus:outline-2 focus:outline-offset-2 focus:outline-indigo-600 dark:hover:text-white dark:focus:outline-indigo-500",children:[v.jsx("span",{className:"sr-only",children:"Close"}),v.jsx($5,{"aria-hidden":"true",className:"size-5"})]})]})})})},y.id)})})})})]})}function cM(){const s=k.useContext(vA);if(!s)throw new Error("useToast must be used within ");return s}function xA(){const{push:s,remove:e,clear:t}=cM(),i=n=>(r,o,u)=>s({type:n,title:r,message:o,...u});return{push:s,remove:e,clear:t,success:i("success"),error:i("error"),info:i("info"),warning:i("warning")}}const bA=s=>(s||"").replaceAll("\\","/").trim(),rn=s=>{const t=bA(s).split("/");return t[t.length-1]||""},Ln=s=>rn(s.output||"")||s.id;function kS(s){if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`}function gy(s){if(typeof s!="number"||!Number.isFinite(s)||s<=0)return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=100?0:t>=10?1:2;return`${t.toFixed(n)} ${e[i]}`}function DS(s){const[e,t]=k.useState(!1);return k.useEffect(()=>{const i=window.matchMedia(s),n=()=>t(i.matches);return n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}},[s]),e}const dM=s=>{const e=(s??"").match(/\bHTTP\s+(\d{3})\b/i);return e?`HTTP ${e[1]}`:null},zu=s=>s.startsWith("HOT ")?s.slice(4):s,Ro=s=>{const e=rn(s||""),t=zu(e);if(!t)return"—";const i=t.replace(/\.[^.]+$/,""),n=i.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(n?.[1])return n[1];const r=i.lastIndexOf("_");return r>0?i.slice(0,r):i},dn=s=>(s||"").trim().toLowerCase(),LS=s=>{const e=String(s??"").trim();if(!e)return[];const t=e.split(/[\n,;|]+/g).map(r=>r.trim()).filter(Boolean),i=new Set,n=[];for(const r of t){const o=r.toLowerCase();i.has(o)||(i.add(o),n.push(r))}return n.sort((r,o)=>r.localeCompare(o,void 0,{sensitivity:"base"})),n},rm=s=>{const e=s,t=e.sizeBytes??e.fileSizeBytes??e.bytes??e.size??null;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null};function hM({jobs:s,doneJobs:e,blurPreviews:t,teaserPlayback:i,teaserAudio:n,onOpenPlayer:r,onDeleteJob:o,onToggleHot:u,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,doneTotal:p,page:g,pageSize:y,onPageChange:x,onRefreshDone:_,assetNonce:w,sortMode:D,onSortModeChange:I,modelsByKey:L}){const B=i??"hover",j=DS("(hover: hover) and (pointer: fine)"),V=xA(),M=k.useRef(new Map),[z,O]=k.useState(null),[N,q]=k.useState(null),[Q,Y]=k.useState(()=>new Set),[re,Z]=k.useState(()=>new Set),[H,K]=k.useState({}),[ie,te]=k.useState(null),[ne,$]=k.useState(null),[ee,le]=k.useState(0),be=k.useRef(null),fe=k.useCallback(()=>{be.current&&window.clearTimeout(be.current),be.current=window.setTimeout(()=>le(xe=>xe+1),80)},[]),[_e,Me]=k.useState(null),et="finishedDownloads_view",[Ge,lt]=k.useState("table"),At=k.useRef(new Map),[mt,Vt]=k.useState([]),Re=k.useMemo(()=>new Set(mt.map(dn)),[mt]),dt=k.useMemo(()=>{const xe={},Ne={};for(const[Oe,Fe]of Object.entries(L??{})){const ht=dn(Oe),ve=LS(Fe?.tags);xe[ht]=ve,Ne[ht]=new Set(ve.map(dn))}return{tagsByModelKey:xe,tagSetByModelKey:Ne}},[L]),[He,tt]=k.useState(""),nt=k.useDeferredValue(He),ot=k.useMemo(()=>dn(nt).split(/\s+/g).map(xe=>xe.trim()).filter(Boolean),[nt]),Ke=k.useCallback(()=>tt(""),[]),pt=k.useCallback(xe=>{const Ne=dn(xe);Vt(Oe=>Oe.some(ht=>dn(ht)===Ne)?Oe.filter(ht=>dn(ht)!==Ne):[...Oe,xe])},[]),yt=ot.length>0||Re.size>0,Gt=k.useCallback(async xe=>{const Ne=await fetch(`/api/record/done?all=1&sort=${encodeURIComponent(D)}`,{cache:"no-store",signal:xe});if(!Ne.ok)return;const Oe=await Ne.json().catch(()=>[]),Fe=Array.isArray(Oe)?Oe:[];te(Fe),$(Fe.length)},[D]),Ut=k.useCallback(()=>Vt([]),[]);k.useEffect(()=>{if(!yt)return;const xe=new AbortController,Ne=window.setTimeout(()=>{Gt(xe.signal).catch(()=>{})},250);return()=>{window.clearTimeout(Ne),xe.abort()}},[yt,Gt]),k.useEffect(()=>{if(ee===0)return;if(yt){const Ne=new AbortController;return(async()=>{try{await Gt(Ne.signal)}catch{}})(),()=>Ne.abort()}const xe=new AbortController;return(async()=>{try{const Ne=await fetch("/api/record/done/meta",{cache:"no-store",signal:xe.signal});if(Ne.ok){const Fe=await Ne.json().catch(()=>null),ht=Number(Fe?.count??0);if(Number.isFinite(ht)&&ht>=0){$(ht);const ve=Math.max(1,Math.ceil(ht/y));if(g>ve){x(ve),te(null);return}}}const Oe=await fetch(`/api/record/done?page=${g}&pageSize=${y}&sort=${encodeURIComponent(D)}`,{cache:"no-store",signal:xe.signal});if(Oe.ok){const Fe=await Oe.json().catch(()=>[]);te(Array.isArray(Fe)?Fe:[])}}catch{}})(),()=>xe.abort()},[ee,g,y,x,D,yt,Gt]),k.useEffect(()=>{yt||(te(null),$(null))},[e,p,yt]),k.useEffect(()=>{try{const xe=localStorage.getItem(et);lt(xe==="table"||xe==="cards"||xe==="gallery"?xe:window.matchMedia("(max-width: 639px)").matches?"cards":"table")}catch{lt("table")}},[]),k.useEffect(()=>{try{localStorage.setItem(et,Ge)}catch{}},[Ge]);const[ai,Zt]=k.useState({}),[$e,ct]=k.useState(null),it=!n,Tt=k.useCallback(xe=>{const Oe=document.getElementById(xe)?.querySelector("video");if(!Oe)return!1;gA(Oe,{muted:it});const Fe=Oe.play?.();return Fe&&typeof Fe.catch=="function"&&Fe.catch(()=>{}),!0},[it]),Wt=k.useCallback(xe=>{ct(Ne=>Ne?.key===xe?{key:xe,nonce:Ne.nonce+1}:{key:xe,nonce:1})},[]),Xe=k.useCallback(xe=>{ct(null),r(xe)},[r]),Ot=k.useCallback((xe,Ne)=>{Z(Oe=>{const Fe=new Set(Oe);return Ne?Fe.add(xe):Fe.delete(xe),Fe})},[]),kt=k.useCallback(xe=>{Y(Ne=>{const Oe=new Set(Ne);return Oe.add(xe),Oe})},[]),[Xt,ni]=k.useState(()=>new Set),hi=k.useCallback((xe,Ne)=>{ni(Oe=>{const Fe=new Set(Oe);return Ne?Fe.add(xe):Fe.delete(xe),Fe})},[]),[Ai,Nt]=k.useState(()=>new Set),bt=k.useCallback((xe,Ne)=>{Nt(Oe=>{const Fe=new Set(Oe);return Ne?Fe.add(xe):Fe.delete(xe),Fe})},[]),xi=k.useCallback(xe=>{bt(xe,!0),window.setTimeout(()=>{kt(xe),bt(xe,!1),fe(),_?.(g)},320)},[kt,bt,fe,_,g]),bi=k.useCallback(async(xe,Ne)=>{window.dispatchEvent(new CustomEvent("player:release",{detail:{file:xe}})),Ne?.close&&window.dispatchEvent(new CustomEvent("player:close",{detail:{file:xe}})),await new Promise(Oe=>window.setTimeout(Oe,250))},[]),G=k.useCallback(async xe=>{const Ne=rn(xe.output||""),Oe=Ln(xe);if(!Ne)return V.error("Löschen nicht möglich","Kein Dateiname gefunden – kann nicht löschen."),!1;if(re.has(Oe))return!1;Ot(Oe,!0);try{if(await bi(Ne,{close:!0}),o)return await o(xe),fe(),!0;const Fe=await fetch(`/api/record/delete?file=${encodeURIComponent(Ne)}`,{method:"POST"});if(!Fe.ok){const ht=await Fe.text().catch(()=>"");throw new Error(ht||`HTTP ${Fe.status}`)}return xi(Oe),!0}catch(Fe){return V.error("Löschen fehlgeschlagen",String(Fe?.message||Fe)),!1}finally{Ot(Oe,!1)}},[re,Ot,bi,o,xi,fe,V]),W=k.useCallback(async xe=>{const Ne=rn(xe.output||""),Oe=Ln(xe);if(!Ne)return V.error("Keep nicht möglich","Kein Dateiname gefunden – kann nicht behalten."),!1;if(Xt.has(Oe)||re.has(Oe))return!1;hi(Oe,!0);try{await bi(Ne,{close:!0});const Fe=await fetch(`/api/record/keep?file=${encodeURIComponent(Ne)}`,{method:"POST"});if(!Fe.ok){const ht=await Fe.text().catch(()=>"");throw new Error(ht||`HTTP ${Fe.status}`)}return xi(Oe),!0}catch(Fe){return V.error("Keep fehlgeschlagen",String(Fe?.message||Fe)),!1}finally{hi(Oe,!1)}},[Xt,re,hi,bi,xi,V]),oe=k.useCallback(async xe=>{const Ne=rn(xe.output||"");if(!Ne){V.error("HOT nicht möglich","Kein Dateiname gefunden – kann nicht HOT togglen.");return}try{if(await bi(Ne,{close:!0}),u){await u(xe);return}const Oe=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(Ne)}`,{method:"POST"});if(!Oe.ok){const Ce=await Oe.text().catch(()=>"");throw new Error(Ce||`HTTP ${Oe.status}`)}const Fe=await Oe.json().catch(()=>null),ht=typeof Fe?.oldFile=="string"&&Fe.oldFile?Fe.oldFile:Ne,ve=typeof Fe?.newFile=="string"&&Fe.newFile?Fe.newFile:"";ve&&(K(Ce=>({...Ce,[ht]:ve})),Zt(Ce=>{const he=Ce[ht];if(typeof he!="number")return Ce;const{[ht]:ye,...me}=Ce;return{...me,[ve]:he}}))}catch(Oe){V.error("HOT umbenennen fehlgeschlagen",String(Oe?.message||Oe))}},[rn,bi,u,V]),Ee=k.useCallback(xe=>{const Ne=xe?.durationSeconds;if(typeof Ne=="number"&&Number.isFinite(Ne)&&Ne>0)return Ne;const Oe=Date.parse(String(xe?.startedAt||"")),Fe=Date.parse(String(xe?.endedAt||""));if(Number.isFinite(Oe)&&Number.isFinite(Fe)&&Fe>Oe){const ht=(Fe-Oe)/1e3;if(ht>=1&&ht<=1440*60)return ht}return Number.POSITIVE_INFINITY},[]),Ze=k.useCallback(xe=>{const Ne=bA(xe.output||""),Oe=rn(Ne),Fe=H[Oe];if(!Fe)return xe;const ht=Ne.lastIndexOf("/"),ve=ht>=0?Ne.slice(0,ht+1):"";return{...xe,output:ve+Fe}},[H,rn]),Et=ie??e,Jt=ne??p,Li=k.useMemo(()=>{const xe=new Map;for(const Oe of Et){const Fe=Ze(Oe);xe.set(Ln(Fe),Fe)}for(const Oe of s){const Fe=Ze(Oe),ht=Ln(Fe);xe.has(ht)&&xe.set(ht,{...xe.get(ht),...Fe})}return Array.from(xe.values()).filter(Oe=>Q.has(Ln(Oe))?!1:Oe.status==="finished"||Oe.status==="failed"||Oe.status==="stopped")},[s,Et,Q,Ze]),Ji=Li;k.useEffect(()=>{const xe=Ne=>{const Oe=Ne.detail;if(!Oe?.file)return;const Fe=Oe.file;Oe.phase==="start"?(Ot(Fe,!0),Ge==="cards"?window.setTimeout(()=>{kt(Fe),_?.(g)},320):xi(Fe)):Oe.phase==="error"?(Ot(Fe,!1),Ge==="cards"&&At.current.get(Fe)?.reset()):Oe.phase==="success"&&(Ot(Fe,!1),fe(),_?.(g))};return window.addEventListener("finished-downloads:delete",xe),()=>window.removeEventListener("finished-downloads:delete",xe)},[xi,Ot,kt,Ge,_,g,fe]);const Ci=k.useMemo(()=>{const xe=Ji.filter(Oe=>!Q.has(Ln(Oe))),Ne=ot.length?xe.filter(Oe=>{const Fe=rn(Oe.output||""),ht=Ro(Oe.output),ve=dn(ht),Ce=dt.tagsByModelKey[ve]??[],he=dn([Fe,zu(Fe),ht,Oe.id,Oe.status,Ce.join(" ")].join(" "));for(const ye of ot)if(!he.includes(ye))return!1;return!0}):xe;return Re.size===0?Ne:Ne.filter(Oe=>{const Fe=dn(Ro(Oe.output)),ht=dt.tagSetByModelKey[Fe];if(!ht||ht.size===0)return!1;for(const ve of Re)if(!ht.has(ve))return!1;return!0})},[Ji,Q,Re,dt,ot]),ss=yt?Ci.length:Jt,Hi=k.useMemo(()=>{if(!yt)return Ci;const xe=(g-1)*y,Ne=xe+y;return Ci.slice(Math.max(0,xe),Math.max(0,Ne))},[yt,Ci,g,y]);k.useEffect(()=>{if(!yt)return;const xe=Math.max(1,Math.ceil(Ci.length/y));g>xe&&x(xe)},[yt,Ci.length,g,y,x]),k.useEffect(()=>{if(!j&&N!==null&&q(null),!!(B==="hover"&&j&&(Ge==="cards"||Ge==="gallery"||Ge==="table"))){if(Ge==="cards"&&$e?.key){O($e.key);return}O(N)}},[B,j,Ge,N,$e?.key]),k.useEffect(()=>{if(!(B==="hover"&&!j&&(Ge==="cards"||Ge==="gallery"||Ge==="table"))){O(null);return}if(Ge==="cards"&&$e?.key){O($e.key);return}let Ne=0;const Oe=()=>{Ne||(Ne=requestAnimationFrame(()=>{Ne=0;const Fe=window.innerWidth/2,ht=window.innerHeight/2;let ve=null,Ce=Number.POSITIVE_INFINITY;for(const[he,ye]of M.current){const me=ye.getBoundingClientRect();if(me.bottom<=0||me.top>=window.innerHeight)continue;const Qe=me.left+me.width/2,Ie=me.top+me.height/2,Ye=Math.hypot(Qe-Fe,Ie-ht);Yehe===ve?he:ve)}))};return Oe(),window.addEventListener("scroll",Oe,{passive:!0}),window.addEventListener("resize",Oe),()=>{Ne&&cancelAnimationFrame(Ne),window.removeEventListener("scroll",Oe),window.removeEventListener("resize",Oe)}},[Ge,Ci.length,$e?.key,B,j]);const fi=xe=>{const Ne=Ln(xe),Oe=ai[Ne]??xe?.durationSeconds;if(typeof Oe=="number"&&Number.isFinite(Oe)&&Oe>0)return kS(Oe*1e3);const Fe=Date.parse(String(xe.startedAt||"")),ht=Date.parse(String(xe.endedAt||""));return Number.isFinite(Fe)&&Number.isFinite(ht)&&ht>Fe?kS(ht-Fe):"—"},ns=k.useCallback(xe=>Ne=>{Ne?M.current.set(xe,Ne):M.current.delete(xe)},[]),es=k.useCallback((xe,Ne)=>{if(!Number.isFinite(Ne)||Ne<=0)return;const Oe=Ln(xe);Zt(Fe=>{const ht=Fe[Oe];return typeof ht=="number"&&Math.abs(ht-Ne)<.5?Fe:{...Fe,[Oe]:Ne}})},[]),Pi=[{key:"preview",header:"Vorschau",widthClassName:"w-[140px]",cell:xe=>{const Ne=Ln(xe),Fe=!(!!n&&N===Ne);return v.jsx("div",{ref:ns(Ne),className:"py-1",onClick:ht=>ht.stopPropagation(),onMouseDown:ht=>ht.stopPropagation(),onMouseEnter:()=>{j&&q(Ne)},onMouseLeave:()=>{j&&q(null)},children:v.jsx(Hx,{force:z===Ne||N===Ne,rootMargin:"400px",placeholder:v.jsx("div",{className:"w-28 h-16 rounded-md ring-1 ring-black/5 dark:ring-white/10 bg-black/5 dark:bg-white/5 animate-pulse"}),children:v.jsx(jx,{job:xe,getFileName:rn,durationSeconds:ai[Ne],muted:Fe,popoverMuted:Fe,onDuration:es,className:"w-28 h-16 rounded-md ring-1 ring-black/5 dark:ring-white/10",showPopover:!1,blur:t,animated:i==="all"?!0:i==="hover"?z===Ne:!1,animatedMode:"teaser",animatedTrigger:"always",assetNonce:w})})})}},{key:"Model",header:"Model",sortable:!0,sortValue:xe=>{const Ne=rn(xe.output||""),Oe=Ne.startsWith("HOT "),Fe=Ro(xe.output),ht=zu(Ne);return`${Fe} ${Oe?"HOT":""} ${ht}`.trim()},cell:xe=>{const Ne=rn(xe.output||""),Oe=Ne.startsWith("HOT "),Fe=Ro(xe.output),ht=zu(Ne),ve=dn(Ro(xe.output)),Ce=LS(L[ve]?.tags),he=Ce.slice(0,6),ye=Ce.length-he.length,me=Ce.join(", ");return v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:Fe}),v.jsxs("div",{className:"mt-0.5 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[v.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[v.jsx("span",{className:"truncate",title:ht,children:ht||"—"}),Oe?v.jsx("span",{className:"shrink-0 rounded-md bg-amber-500/15 px-1.5 py-0.5 text-[11px] font-semibold text-amber-800 dark:text-amber-300",children:"HOT"}):null]}),he.length>0?v.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 min-w-0",children:[he.map(Qe=>v.jsx(la,{tag:Qe,active:Re.has(dn(Qe)),onClick:pt},Qe)),ye>0?v.jsxs("span",{className:"inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-700 ring-1 ring-inset ring-gray-200 dark:bg-white/5 dark:text-gray-200 dark:ring-white/10",title:me,children:["+",ye]}):null]}):null]})]})}},{key:"status",header:"Status",sortable:!0,sortValue:xe=>xe.status==="finished"?0:xe.status==="stopped"?1:xe.status==="failed"?2:9,cell:xe=>{const Ne="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold ring-1 ring-inset";if(xe.status==="failed"){const Oe=dM(xe.error),Fe=Oe?`failed (${Oe})`:"failed";return v.jsx("span",{className:`${Ne} bg-red-50 text-red-700 ring-red-200 dark:bg-red-500/10 dark:text-red-300 dark:ring-red-500/30`,title:xe.error||"",children:Fe})}return xe.status==="finished"?v.jsx("span",{className:`${Ne} bg-emerald-50 text-emerald-800 ring-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-300 dark:ring-emerald-500/30`,children:"finished"}):xe.status==="stopped"?v.jsx("span",{className:`${Ne} bg-amber-50 text-amber-800 ring-amber-200 dark:bg-amber-500/10 dark:text-amber-300 dark:ring-amber-500/30`,children:"stopped"}):v.jsx("span",{className:`${Ne} bg-gray-50 text-gray-700 ring-gray-200 dark:bg-white/5 dark:text-gray-300 dark:ring-white/10`,children:xe.status})}},{key:"completedAt",header:"Fertiggestellt am",sortable:!0,widthClassName:"w-[150px]",sortValue:xe=>{const Ne=Date.parse(String(xe.endedAt||""));return Number.isFinite(Ne)?Ne:Number.NEGATIVE_INFINITY},cell:xe=>{const Ne=Date.parse(String(xe.endedAt||""));if(!Number.isFinite(Ne))return v.jsx("span",{className:"text-xs text-gray-400",children:"—"});const Oe=new Date(Ne),Fe=Oe.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),ht=Oe.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"});return v.jsxs("time",{dateTime:Oe.toISOString(),title:`${Fe} ${ht}`,className:"tabular-nums whitespace-nowrap text-sm text-gray-900 dark:text-white",children:[v.jsx("span",{className:"font-medium",children:Fe}),v.jsx("span",{className:"mx-1 text-gray-400 dark:text-gray-600",children:"·"}),v.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:ht})]})}},{key:"runtime",header:"Dauer",align:"right",sortable:!0,sortValue:xe=>Ee(xe),cell:xe=>v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:fi(xe)})},{key:"size",header:"Größe",align:"right",sortable:!0,sortValue:xe=>{const Ne=rm(xe);return typeof Ne=="number"?Ne:Number.NEGATIVE_INFINITY},cell:xe=>v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:gy(rm(xe))})},{key:"actions",header:"Aktionen",align:"right",srOnlyHeader:!0,cell:xe=>{const Ne=Ln(xe),Oe=re.has(Ne)||Xt.has(Ne)||Ai.has(Ne),ht=rn(xe.output||"").startsWith("HOT "),ve=dn(Ro(xe.output)),Ce=L[ve],he=!!Ce?.favorite,ye=Ce?.liked===!0,me=!!Ce?.watching;return v.jsx(Ko,{job:xe,variant:"table",busy:Oe,isHot:ht,isFavorite:he,isLiked:ye,isWatching:me,onToggleWatch:f,onToggleFavorite:c,onToggleLike:d,onToggleHot:oe,onKeep:W,onDelete:G,order:["watch","favorite","like","hot","details","keep","delete"],className:"flex items-center justify-end gap-1"})}}],oi=xe=>{if(!xe)return"completed_desc";const Ne=xe,Oe=String(Ne.key??Ne.columnKey??Ne.id??""),Fe=String(Ne.dir??Ne.direction??Ne.order??"").toLowerCase(),ht=Fe==="asc"||Fe==="1"||Fe==="true";return Oe==="completedAt"?ht?"completed_asc":"completed_desc":Oe==="runtime"?ht?"duration_asc":"duration_desc":Oe==="size"?ht?"size_asc":"size_desc":Oe==="video"?ht?"file_asc":"file_desc":ht?"completed_asc":"completed_desc"},ei=xe=>{Me(xe);const Ne=oi(xe);I(Ne),g!==1&&x(1)},Ht=DS("(max-width: 639px)");k.useEffect(()=>{Ht||(At.current=new Map)},[Ht]);const Rs=Li.length===0&&Jt===0,Zs=!Rs&&Ci.length===0;return v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"sticky top-[56px] z-20",children:v.jsxs("div",{className:` + rounded-xl border border-gray-200/70 bg-white/80 shadow-sm + backdrop-blur supports-[backdrop-filter]:bg-white/60 + dark:border-white/10 dark:bg-gray-950/60 dark:supports-[backdrop-filter]:bg-gray-950/40 + `,children:[v.jsxs("div",{className:"flex items-center justify-between gap-2 p-3",children:[v.jsxs("div",{className:"sm:hidden flex items-center gap-2 min-w-0",children:[v.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),v.jsx("span",{className:"shrink-0 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:ss})]}),v.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0",children:[v.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),v.jsx("span",{className:"rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:ss})]}),v.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[Ge!=="table"&&v.jsxs("div",{className:"hidden sm:block",children:[v.jsx("label",{className:"sr-only",htmlFor:"finished-sort",children:"Sortierung"}),v.jsxs("select",{id:"finished-sort",value:D,onChange:xe=>{const Ne=xe.target.value;I(Ne),g!==1&&x(1)},className:` + h-9 rounded-md border border-gray-200 bg-white px-2 text-sm text-gray-900 shadow-sm + dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark] + `,children:[v.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),v.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),v.jsx("option",{value:"model_asc",children:"Modelname A→Z"}),v.jsx("option",{value:"model_desc",children:"Modelname Z→A"}),v.jsx("option",{value:"file_asc",children:"Dateiname A→Z"}),v.jsx("option",{value:"file_desc",children:"Dateiname Z→A"}),v.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),v.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),v.jsx("option",{value:"size_desc",children:"Größe ↓"}),v.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}),v.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0",children:[v.jsx("input",{value:He,onChange:xe=>tt(xe.target.value),placeholder:"Suchen…",className:` + h-9 w-56 md:w-72 rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm + focus:outline-none focus:ring-2 focus:ring-indigo-500 + dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark] + `}),(He||"").trim()!==""?v.jsx(_i,{size:"sm",variant:"soft",onClick:Ke,children:"Clear"}):null]}),v.jsx(z5,{value:Ge,onChange:xe=>lt(xe),size:"md",ariaLabel:"Ansicht",items:[{id:"table",icon:v.jsx(kO,{className:"size-5"}),label:Ht?void 0:"Tabelle",srLabel:"Tabelle"},{id:"cards",icon:v.jsx(_O,{className:"size-5"}),label:Ht?void 0:"Cards",srLabel:"Cards"},{id:"gallery",icon:v.jsx(wO,{className:"size-5"}),label:Ht?void 0:"Galerie",srLabel:"Galerie"}]})]})]}),v.jsx("div",{className:"sm:hidden border-t border-gray-200/60 dark:border-white/10 p-3 pt-2",children:v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("input",{value:He,onChange:xe=>tt(xe.target.value),placeholder:"Suchen…",className:` + w-full h-9 rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm + focus:outline-none focus:ring-2 focus:ring-indigo-500 + dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark] + `}),(He||"").trim()!==""?v.jsx(_i,{size:"sm",variant:"soft",onClick:Ke,children:"Clear"}):null]})}),Ge!=="table"&&v.jsxs("div",{className:"sm:hidden border-t border-gray-200/60 dark:border-white/10 p-3 pt-2",children:[v.jsx("label",{className:"sr-only",htmlFor:"finished-sort-mobile",children:"Sortierung"}),v.jsxs("select",{id:"finished-sort-mobile",value:D,onChange:xe=>{const Ne=xe.target.value;I(Ne),g!==1&&x(1)},className:` + w-full h-9 rounded-md border border-gray-200 bg-white px-2 text-sm text-gray-900 shadow-sm + dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark] + `,children:[v.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),v.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),v.jsx("option",{value:"model_asc",children:"Modelname A→Z"}),v.jsx("option",{value:"model_desc",children:"Modelname Z→A"}),v.jsx("option",{value:"file_asc",children:"Dateiname A→Z"}),v.jsx("option",{value:"file_desc",children:"Dateiname Z→A"}),v.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),v.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),v.jsx("option",{value:"size_desc",children:"Größe ↓"}),v.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}),mt.length>0?v.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 px-3 py-2",children:v.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[v.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),v.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[mt.map(xe=>v.jsx(la,{tag:xe,active:!0,onClick:pt},xe)),v.jsx(_i,{className:` + ml-1 inline-flex items-center rounded-md px-2 py-1 text-xs font-medium + text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-white/10 + `,size:"sm",variant:"soft",onClick:Ut,children:"Zurücksetzen"})]})]})}):null]})}),Rs?v.jsx(za,{grayBody:!0,children:v.jsxs("div",{className:"flex items-center gap-3",children:[v.jsx("div",{className:"grid h-10 w-10 place-items-center rounded-xl bg-white/70 ring-1 ring-gray-200 dark:bg-white/5 dark:ring-white/10",children:v.jsx("span",{className:"text-lg",children:"📁"})}),v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine abgeschlossenen Downloads"}),v.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Im Zielordner ist aktuell nichts vorhanden."})]})]})}):Zs?v.jsxs(za,{grayBody:!0,children:[v.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Treffer für die aktuellen Filter."}),mt.length>0||(He||"").trim()!==""?v.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[mt.length>0?v.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:Ut,children:"Tag-Filter zurücksetzen"}):null,(He||"").trim()!==""?v.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:Ke,children:"Suche zurücksetzen"}):null]}):null]}):v.jsxs(v.Fragment,{children:[Ge==="cards"&&v.jsx(eM,{rows:Hi,isSmall:Ht,blurPreviews:t,durations:ai,teaserKey:z,teaserPlayback:B,teaserAudio:n,hoverTeaserKey:N,inlinePlay:$e,setInlinePlay:ct,deletingKeys:re,keepingKeys:Xt,removingKeys:Ai,swipeRefs:At,keyFor:Ln,baseName:rn,stripHotPrefix:zu,modelNameFromOutput:Ro,runtimeOf:fi,sizeBytesOf:rm,formatBytes:gy,lower:dn,onOpenPlayer:r,openPlayer:Xe,startInline:Wt,tryAutoplayInline:Tt,registerTeaserHost:ns,handleDuration:es,deleteVideo:G,keepVideo:W,releasePlayingFile:bi,modelsByKey:L,onToggleHot:oe,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:Re,onToggleTagFilter:pt,onHoverPreviewKeyChange:q}),Ge==="table"&&v.jsx(tM,{rows:Hi,columns:Pi,getRowKey:xe=>Ln(xe),sort:_e,onSortChange:ei,onRowClick:r,rowClassName:xe=>{const Ne=Ln(xe);return["transition-all duration-300",(re.has(Ne)||Ai.has(Ne))&&"bg-red-50/60 dark:bg-red-500/10 pointer-events-none",re.has(Ne)&&"animate-pulse",(Xt.has(Ne)||Ai.has(Ne))&&"pointer-events-none",Xt.has(Ne)&&"bg-emerald-50/60 dark:bg-emerald-500/10 animate-pulse",Ai.has(Ne)&&"opacity-0"].filter(Boolean).join(" ")}}),Ge==="gallery"&&v.jsx(iM,{rows:Hi,blurPreviews:t,durations:ai,handleDuration:es,teaserKey:z,teaserPlayback:B,teaserAudio:n,hoverTeaserKey:N,keyFor:Ln,baseName:rn,stripHotPrefix:zu,modelNameFromOutput:Ro,runtimeOf:fi,sizeBytesOf:rm,formatBytes:gy,deletingKeys:re,keepingKeys:Xt,removingKeys:Ai,deletedKeys:Q,registerTeaserHost:ns,onOpenPlayer:r,deleteVideo:G,keepVideo:W,onToggleHot:oe,lower:dn,modelsByKey:L,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:Re,onToggleTagFilter:pt,onHoverPreviewKeyChange:q}),v.jsx(yA,{page:g,pageSize:y,totalItems:ss,onPageChange:xe=>{Sh.flushSync(()=>{ct(null),O(null),q(null)});for(const Ne of Hi){const Oe=rn(Ne.output||"");Oe&&(window.dispatchEvent(new CustomEvent("player:release",{detail:{file:Oe}})),window.dispatchEvent(new CustomEvent("player:close",{detail:{file:Oe}})))}window.scrollTo({top:0,behavior:"auto"}),x(xe)},showSummary:!1,prevLabel:"Zurück",nextLabel:"Weiter",className:"mt-4"})]})]})}var yy,RS;function Fp(){if(RS)return yy;RS=1;var s;return typeof window<"u"?s=window:typeof Gm<"u"?s=Gm:typeof self<"u"?s=self:s={},yy=s,yy}var fM=Fp();const ue=Cc(fM),mM={},pM=Object.freeze(Object.defineProperty({__proto__:null,default:mM},Symbol.toStringTag,{value:"Module"})),gM=oI(pM);var vy,IS;function TA(){if(IS)return vy;IS=1;var s=typeof Gm<"u"?Gm:typeof window<"u"?window:{},e=gM,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),vy=t,vy}var yM=TA();const st=Cc(yM);var am={exports:{}},xy={exports:{}},NS;function vM(){return NS||(NS=1,(function(s){function e(){return s.exports=e=Object.assign?Object.assign.bind():function(t){for(var i=1;i=n.length?{done:!0}:{done:!1,value:n[u++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function e(n,r){if(n){if(typeof n=="string")return t(n,r);var o=Object.prototype.toString.call(n).slice(8,-1);if(o==="Object"&&n.constructor&&(o=n.constructor.name),o==="Map"||o==="Set")return Array.from(n);if(o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o))return t(n,r)}}function t(n,r){(r==null||r>n.length)&&(r=n.length);for(var o=0,u=new Array(r);o=400&&u.statusCode<=599){var d=c;if(r)if(s.TextDecoder){var f=t(u.headers&&u.headers["content-type"]);try{d=new TextDecoder(f).decode(c)}catch{}}else d=String.fromCharCode.apply(null,new Uint8Array(c));n({cause:d});return}n(null,c)}};function t(i){return i===void 0&&(i=""),i.toLowerCase().split(";").reduce(function(n,r){var o=r.split("="),u=o[0],c=o[1];return u.trim()==="charset"?c.trim():n},"utf-8")}return Sy=e,Sy}var FS;function SM(){if(FS)return am.exports;FS=1;var s=Fp(),e=vM(),t=xM(),i=bM(),n=TM();d.httpHandler=_M(),d.requestInterceptorsStorage=new i,d.responseInterceptorsStorage=new i,d.retryManager=new n;var r=function(x){var _={};return x&&x.trim().split(` +`).forEach(function(w){var D=w.indexOf(":"),I=w.slice(0,D).trim().toLowerCase(),L=w.slice(D+1).trim();typeof _[I]>"u"?_[I]=L:Array.isArray(_[I])?_[I].push(L):_[I]=[_[I],L]}),_};am.exports=d,am.exports.default=d,d.XMLHttpRequest=s.XMLHttpRequest||g,d.XDomainRequest="withCredentials"in new d.XMLHttpRequest?d.XMLHttpRequest:s.XDomainRequest,o(["get","put","post","patch","head","delete"],function(y){d[y==="delete"?"del":y]=function(x,_,w){return _=c(x,_,w),_.method=y.toUpperCase(),f(_)}});function o(y,x){for(var _=0;_"u")throw new Error("callback argument missing");if(y.requestType&&d.requestInterceptorsStorage.getIsEnabled()){var x={uri:y.uri||y.url,headers:y.headers||{},body:y.body,metadata:y.metadata||{},retry:y.retry,timeout:y.timeout},_=d.requestInterceptorsStorage.execute(y.requestType,x);y.uri=_.uri,y.headers=_.headers,y.body=_.body,y.metadata=_.metadata,y.retry=_.retry,y.timeout=_.timeout}var w=!1,D=function(ie,te,ne){w||(w=!0,y.callback(ie,te,ne))};function I(){V.readyState===4&&!d.responseInterceptorsStorage.getIsEnabled()&&setTimeout(j,0)}function L(){var K=void 0;if(V.response?K=V.response:K=V.responseText||p(V),re)try{K=JSON.parse(K)}catch{}return K}function B(K){if(clearTimeout(Z),clearTimeout(y.retryTimeout),K instanceof Error||(K=new Error(""+(K||"Unknown XMLHttpRequest Error"))),K.statusCode=0,!z&&d.retryManager.getIsEnabled()&&y.retry&&y.retry.shouldRetry()){y.retryTimeout=setTimeout(function(){y.retry.moveToNextAttempt(),y.xhr=V,f(y)},y.retry.getCurrentFuzzedDelay());return}if(y.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var ie={headers:H.headers||{},body:H.body,responseUrl:V.responseURL,responseType:V.responseType},te=d.responseInterceptorsStorage.execute(y.requestType,ie);H.body=te.body,H.headers=te.headers}return D(K,H)}function j(){if(!z){var K;clearTimeout(Z),clearTimeout(y.retryTimeout),y.useXDR&&V.status===void 0?K=200:K=V.status===1223?204:V.status;var ie=H,te=null;if(K!==0?(ie={body:L(),statusCode:K,method:N,headers:{},url:O,rawRequest:V},V.getAllResponseHeaders&&(ie.headers=r(V.getAllResponseHeaders()))):te=new Error("Internal XMLHttpRequest Error"),y.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var ne={headers:ie.headers||{},body:ie.body,responseUrl:V.responseURL,responseType:V.responseType},$=d.responseInterceptorsStorage.execute(y.requestType,ne);ie.body=$.body,ie.headers=$.headers}return D(te,ie,ie.body)}}var V=y.xhr||null;V||(y.cors||y.useXDR?V=new d.XDomainRequest:V=new d.XMLHttpRequest);var M,z,O=V.url=y.uri||y.url,N=V.method=y.method||"GET",q=y.body||y.data,Q=V.headers=y.headers||{},Y=!!y.sync,re=!1,Z,H={body:void 0,headers:{},statusCode:0,method:N,url:O,rawRequest:V};if("json"in y&&y.json!==!1&&(re=!0,Q.accept||Q.Accept||(Q.Accept="application/json"),N!=="GET"&&N!=="HEAD"&&(Q["content-type"]||Q["Content-Type"]||(Q["Content-Type"]="application/json"),q=JSON.stringify(y.json===!0?q:y.json))),V.onreadystatechange=I,V.onload=j,V.onerror=B,V.onprogress=function(){},V.onabort=function(){z=!0,clearTimeout(y.retryTimeout)},V.ontimeout=B,V.open(N,O,!Y,y.username,y.password),Y||(V.withCredentials=!!y.withCredentials),!Y&&y.timeout>0&&(Z=setTimeout(function(){if(!z){z=!0,V.abort("timeout");var K=new Error("XMLHttpRequest timeout");K.code="ETIMEDOUT",B(K)}},y.timeout)),V.setRequestHeader)for(M in Q)Q.hasOwnProperty(M)&&V.setRequestHeader(M,Q[M]);else if(y.headers&&!u(y.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in y&&(V.responseType=y.responseType),"beforeSend"in y&&typeof y.beforeSend=="function"&&y.beforeSend(V),V.send(q||null),V}function p(y){try{if(y.responseType==="document")return y.responseXML;var x=y.responseXML&&y.responseXML.documentElement.nodeName==="parsererror";if(y.responseType===""&&!x)return y.responseXML}catch{}return null}function g(){}return am.exports}var EM=SM();const _A=Cc(EM);var Ey={exports:{}},wy,US;function wM(){if(US)return wy;US=1;var s=TA(),e=Object.create||(function(){function O(){}return function(N){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return O.prototype=N,new O}})();function t(O,N){this.name="ParsingError",this.code=O.code,this.message=N||O.message}t.prototype=e(Error.prototype),t.prototype.constructor=t,t.Errors={BadSignature:{code:0,message:"Malformed WebVTT signature."},BadTimeStamp:{code:1,message:"Malformed time stamp."}};function i(O){function N(Q,Y,re,Z){return(Q|0)*3600+(Y|0)*60+(re|0)+(Z|0)/1e3}var q=O.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return q?q[3]?N(q[1],q[2],q[3].replace(":",""),q[4]):q[1]>59?N(q[1],q[2],0,q[4]):N(0,q[1],q[2],q[4]):null}function n(){this.values=e(null)}n.prototype={set:function(O,N){!this.get(O)&&N!==""&&(this.values[O]=N)},get:function(O,N,q){return q?this.has(O)?this.values[O]:N[q]:this.has(O)?this.values[O]:N},has:function(O){return O in this.values},alt:function(O,N,q){for(var Q=0;Q=0&&N<=100)?(this.set(O,N),!0):!1}};function r(O,N,q,Q){var Y=Q?O.split(Q):[O];for(var re in Y)if(typeof Y[re]=="string"){var Z=Y[re].split(q);if(Z.length===2){var H=Z[0].trim(),K=Z[1].trim();N(H,K)}}}function o(O,N,q){var Q=O;function Y(){var H=i(O);if(H===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+Q);return O=O.replace(/^[^\sa-zA-Z-]+/,""),H}function re(H,K){var ie=new n;r(H,function(te,ne){switch(te){case"region":for(var $=q.length-1;$>=0;$--)if(q[$].id===ne){ie.set(te,q[$].region);break}break;case"vertical":ie.alt(te,ne,["rl","lr"]);break;case"line":var ee=ne.split(","),le=ee[0];ie.integer(te,le),ie.percent(te,le)&&ie.set("snapToLines",!1),ie.alt(te,le,["auto"]),ee.length===2&&ie.alt("lineAlign",ee[1],["start","center","end"]);break;case"position":ee=ne.split(","),ie.percent(te,ee[0]),ee.length===2&&ie.alt("positionAlign",ee[1],["start","center","end"]);break;case"size":ie.percent(te,ne);break;case"align":ie.alt(te,ne,["start","center","end","left","right"]);break}},/:/,/\s/),K.region=ie.get("region",null),K.vertical=ie.get("vertical","");try{K.line=ie.get("line","auto")}catch{}K.lineAlign=ie.get("lineAlign","start"),K.snapToLines=ie.get("snapToLines",!0),K.size=ie.get("size",100);try{K.align=ie.get("align","center")}catch{K.align=ie.get("align","middle")}try{K.position=ie.get("position","auto")}catch{K.position=ie.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},K.align)}K.positionAlign=ie.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},K.align)}function Z(){O=O.replace(/^\s+/,"")}if(Z(),N.startTime=Y(),Z(),O.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+Q);O=O.substr(3),Z(),N.endTime=Y(),Z(),re(O,N)}var u=s.createElement&&s.createElement("textarea"),c={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},d={white:"rgba(255,255,255,1)",lime:"rgba(0,255,0,1)",cyan:"rgba(0,255,255,1)",red:"rgba(255,0,0,1)",yellow:"rgba(255,255,0,1)",magenta:"rgba(255,0,255,1)",blue:"rgba(0,0,255,1)",black:"rgba(0,0,0,1)"},f={v:"title",lang:"lang"},p={rt:"ruby"};function g(O,N){function q(){if(!N)return null;function le(fe){return N=N.substr(fe.length),fe}var be=N.match(/^([^<]*)(<[^>]*>?)?/);return le(be[1]?be[1]:be[2])}function Q(le){return u.innerHTML=le,le=u.textContent,u.textContent="",le}function Y(le,be){return!p[be.localName]||p[be.localName]===le.localName}function re(le,be){var fe=c[le];if(!fe)return null;var _e=O.document.createElement(fe),Me=f[le];return Me&&be&&(_e[Me]=be.trim()),_e}for(var Z=O.document.createElement("div"),H=Z,K,ie=[];(K=q())!==null;){if(K[0]==="<"){if(K[1]==="/"){ie.length&&ie[ie.length-1]===K.substr(2).replace(">","")&&(ie.pop(),H=H.parentNode);continue}var te=i(K.substr(1,K.length-2)),ne;if(te){ne=O.document.createProcessingInstruction("timestamp",te),H.appendChild(ne);continue}var $=K.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!$||(ne=re($[1],$[3]),!ne)||!Y(H,ne))continue;if($[2]){var ee=$[2].split(".");ee.forEach(function(le){var be=/^bg_/.test(le),fe=be?le.slice(3):le;if(d.hasOwnProperty(fe)){var _e=be?"background-color":"color",Me=d[fe];ne.style[_e]=Me}}),ne.className=ee.join(" ")}ie.push($[1]),H.appendChild(ne),H=ne;continue}H.appendChild(O.document.createTextNode(Q(K)))}return Z}var y=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[2084,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578],[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];function x(O){for(var N=0;N=q[0]&&O<=q[1])return!0}return!1}function _(O){var N=[],q="",Q;if(!O||!O.childNodes)return"ltr";function Y(H,K){for(var ie=K.childNodes.length-1;ie>=0;ie--)H.push(K.childNodes[ie])}function re(H){if(!H||!H.length)return null;var K=H.pop(),ie=K.textContent||K.innerText;if(ie){var te=ie.match(/^.*(\n|\r)/);return te?(H.length=0,te[0]):ie}if(K.tagName==="ruby")return re(H);if(K.childNodes)return Y(H,K),re(H)}for(Y(N,O);q=re(N);)for(var Z=0;Z=0&&O.line<=100))return O.line;if(!O.track||!O.track.textTrackList||!O.track.textTrackList.mediaElement)return-1;for(var N=O.track,q=N.textTrackList,Q=0,Y=0;YO.left&&this.topO.top},L.prototype.overlapsAny=function(O){for(var N=0;N=O.top&&this.bottom<=O.bottom&&this.left>=O.left&&this.right<=O.right},L.prototype.overlapsOppositeAxis=function(O,N){switch(N){case"+x":return this.leftO.right;case"+y":return this.topO.bottom}},L.prototype.intersectPercentage=function(O){var N=Math.max(0,Math.min(this.right,O.right)-Math.max(this.left,O.left)),q=Math.max(0,Math.min(this.bottom,O.bottom)-Math.max(this.top,O.top)),Q=N*q;return Q/(this.height*this.width)},L.prototype.toCSSCompatValues=function(O){return{top:this.top-O.top,bottom:O.bottom-this.bottom,left:this.left-O.left,right:O.right-this.right,height:this.height,width:this.width}},L.getSimpleBoxPosition=function(O){var N=O.div?O.div.offsetHeight:O.tagName?O.offsetHeight:0,q=O.div?O.div.offsetWidth:O.tagName?O.offsetWidth:0,Q=O.div?O.div.offsetTop:O.tagName?O.offsetTop:0;O=O.div?O.div.getBoundingClientRect():O.tagName?O.getBoundingClientRect():O;var Y={left:O.left,right:O.right,top:O.top||Q,height:O.height||N,bottom:O.bottom||Q+(O.height||N),width:O.width||q};return Y};function B(O,N,q,Q){function Y(fe,_e){for(var Me,et=new L(fe),Ge=1,lt=0;lt<_e.length;lt++){for(;fe.overlapsOppositeAxis(q,_e[lt])||fe.within(q)&&fe.overlapsAny(Q);)fe.move(_e[lt]);if(fe.within(q))return fe;var At=fe.intersectPercentage(q);Ge>At&&(Me=new L(fe),Ge=At),fe=new L(et)}return Me||et}var re=new L(N),Z=N.cue,H=w(Z),K=[];if(Z.snapToLines){var ie;switch(Z.vertical){case"":K=["+y","-y"],ie="height";break;case"rl":K=["+x","-x"],ie="width";break;case"lr":K=["-x","+x"],ie="width";break}var te=re.lineHeight,ne=te*Math.round(H),$=q[ie]+te,ee=K[0];Math.abs(ne)>$&&(ne=ne<0?-1:1,ne*=Math.ceil($/te)*te),H<0&&(ne+=Z.vertical===""?q.height:q.width,K=K.reverse()),re.move(ee,ne)}else{var le=re.lineHeight/q.height*100;switch(Z.lineAlign){case"center":H-=le/2;break;case"end":H-=le;break}switch(Z.vertical){case"":N.applyStyles({top:N.formatStyle(H,"%")});break;case"rl":N.applyStyles({left:N.formatStyle(H,"%")});break;case"lr":N.applyStyles({right:N.formatStyle(H,"%")});break}K=["+y","-x","+x","-y"],re=new L(N)}var be=Y(re,K);N.move(be.toCSSCompatValues(q))}function j(){}j.StringDecoder=function(){return{decode:function(O){if(!O)return"";if(typeof O!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(O))}}},j.convertCueToDOMTree=function(O,N){return!O||!N?null:g(O,N)};var V=.05,M="sans-serif",z="1.5%";return j.processCues=function(O,N,q){if(!O||!N||!q)return null;for(;q.firstChild;)q.removeChild(q.firstChild);var Q=O.document.createElement("div");Q.style.position="absolute",Q.style.left="0",Q.style.right="0",Q.style.top="0",Q.style.bottom="0",Q.style.margin=z,q.appendChild(Q);function Y(te){for(var ne=0;ne")===-1){N.cue.id=Z;continue}case"CUE":try{o(Z,N.cue,N.regionList)}catch(te){N.reportOrThrowError(te),N.cue=null,N.state="BADCUE";continue}N.state="CUETEXT";continue;case"CUETEXT":var ie=Z.indexOf("-->")!==-1;if(!Z||ie&&(K=!0)){N.oncue&&N.oncue(N.cue),N.cue=null,N.state="ID";continue}N.cue.text&&(N.cue.text+=` +`),N.cue.text+=Z.replace(/\u2028/g,` +`).replace(/u2029/g,` +`);continue;case"BADCUE":Z||(N.state="ID");continue}}}catch(te){N.reportOrThrowError(te),N.state==="CUETEXT"&&N.cue&&N.oncue&&N.oncue(N.cue),N.cue=null,N.state=N.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var O=this;try{if(O.buffer+=O.decoder.decode(),(O.cue||O.state==="HEADER")&&(O.buffer+=` + +`,O.parse()),O.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(N){O.reportOrThrowError(N)}return O.onflush&&O.onflush(),this}},wy=j,wy}var Ay,jS;function AM(){if(jS)return Ay;jS=1;var s="auto",e={"":1,lr:1,rl:1},t={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function i(o){if(typeof o!="string")return!1;var u=e[o.toLowerCase()];return u?o.toLowerCase():!1}function n(o){if(typeof o!="string")return!1;var u=t[o.toLowerCase()];return u?o.toLowerCase():!1}function r(o,u,c){this.hasBeenReset=!1;var d="",f=!1,p=o,g=u,y=c,x=null,_="",w=!0,D="auto",I="start",L="auto",B="auto",j=100,V="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return d},set:function(M){d=""+M}},pauseOnExit:{enumerable:!0,get:function(){return f},set:function(M){f=!!M}},startTime:{enumerable:!0,get:function(){return p},set:function(M){if(typeof M!="number")throw new TypeError("Start time must be set to a number.");p=M,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return g},set:function(M){if(typeof M!="number")throw new TypeError("End time must be set to a number.");g=M,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return y},set:function(M){y=""+M,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return x},set:function(M){x=M,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return _},set:function(M){var z=i(M);if(z===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");_=z,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return w},set:function(M){w=!!M,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return D},set:function(M){if(typeof M!="number"&&M!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");D=M,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return I},set:function(M){var z=n(M);z?(I=z,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return L},set:function(M){if(M<0||M>100)throw new Error("Position must be between 0 and 100.");L=M,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return B},set:function(M){var z=n(M);z?(B=z,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return j},set:function(M){if(M<0||M>100)throw new Error("Size must be between 0 and 100.");j=M,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return V},set:function(M){var z=n(M);if(!z)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");V=z,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},Ay=r,Ay}var Cy,$S;function CM(){if($S)return Cy;$S=1;var s={"":!0,up:!0};function e(n){if(typeof n!="string")return!1;var r=s[n.toLowerCase()];return r?n.toLowerCase():!1}function t(n){return typeof n=="number"&&n>=0&&n<=100}function i(){var n=100,r=3,o=0,u=100,c=0,d=100,f="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return n},set:function(p){if(!t(p))throw new Error("Width must be between 0 and 100.");n=p}},lines:{enumerable:!0,get:function(){return r},set:function(p){if(typeof p!="number")throw new TypeError("Lines must be set to a number.");r=p}},regionAnchorY:{enumerable:!0,get:function(){return u},set:function(p){if(!t(p))throw new Error("RegionAnchorX must be between 0 and 100.");u=p}},regionAnchorX:{enumerable:!0,get:function(){return o},set:function(p){if(!t(p))throw new Error("RegionAnchorY must be between 0 and 100.");o=p}},viewportAnchorY:{enumerable:!0,get:function(){return d},set:function(p){if(!t(p))throw new Error("ViewportAnchorY must be between 0 and 100.");d=p}},viewportAnchorX:{enumerable:!0,get:function(){return c},set:function(p){if(!t(p))throw new Error("ViewportAnchorX must be between 0 and 100.");c=p}},scroll:{enumerable:!0,get:function(){return f},set:function(p){var g=e(p);g===!1?console.warn("Scroll: an invalid or illegal string was specified."):f=g}}})}return Cy=i,Cy}var HS;function kM(){if(HS)return Ey.exports;HS=1;var s=Fp(),e=Ey.exports={WebVTT:wM(),VTTCue:AM(),VTTRegion:CM()};s.vttjs=e,s.WebVTT=e.WebVTT;var t=e.VTTCue,i=e.VTTRegion,n=s.VTTCue,r=s.VTTRegion;return e.shim=function(){s.VTTCue=t,s.VTTRegion=i},e.restore=function(){s.VTTCue=n,s.VTTRegion=r},s.VTTCue||e.shim(),Ey.exports}var DM=kM();const VS=Cc(DM);function Es(){return Es=Object.assign?Object.assign.bind():function(s){for(var e=1;e-1},e.trigger=function(i){var n=this.listeners[i];if(n)if(arguments.length===2)for(var r=n.length,o=0;o-1;t=this.buffer.indexOf(` +`))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const IM=" ",ky=function(s){const e=/([0-9.]*)?@?([0-9.]*)?/.exec(s||""),t={};return e[1]&&(t.length=parseInt(e[1],10)),e[2]&&(t.offset=parseInt(e[2],10)),t},NM=function(){const t="(?:"+"[^=]*"+")=(?:"+'"[^"]*"|[^,]*'+")";return new RegExp("(?:^|,)("+t+")")},hn=function(s){const e={};if(!s)return e;const t=s.split(NM());let i=t.length,n;for(;i--;)t[i]!==""&&(n=/([^=]*)=(.*)/.exec(t[i]).slice(1),n[0]=n[0].replace(/^\s+|\s+$/g,""),n[1]=n[1].replace(/^\s+|\s+$/g,""),n[1]=n[1].replace(/^['"](.*)['"]$/g,"$1"),e[n[0]]=n[1]);return e},zS=s=>{const e=s.split("x"),t={};return e[0]&&(t.width=parseInt(e[0],10)),e[1]&&(t.height=parseInt(e[1],10)),t};class OM extends Vx{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,i;if(e=e.trim(),e.length===0)return;if(e[0]!=="#"){this.trigger("data",{type:"uri",uri:e});return}this.tagMappers.reduce((r,o)=>{const u=o(e);return u===e?r:r.concat([u])},[e]).forEach(r=>{for(let o=0;or),this.customParsers.push(r=>{if(e.exec(r))return this.trigger("data",{type:"custom",data:i(r),customType:t,segment:n}),!0})}addTagMapper({expression:e,map:t}){const i=n=>e.test(n)?t(n):n;this.tagMappers.push(i)}}const MM=s=>s.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),Io=function(s){const e={};return Object.keys(s).forEach(function(t){e[MM(t)]=s[t]}),e},Dy=function(s){const{serverControl:e,targetDuration:t,partTargetDuration:i}=s;if(!e)return;const n="#EXT-X-SERVER-CONTROL",r="holdBack",o="partHoldBack",u=t&&t*3,c=i&&i*2;t&&!e.hasOwnProperty(r)&&(e[r]=u,this.trigger("info",{message:`${n} defaulting HOLD-BACK to targetDuration * 3 (${u}).`})),u&&e[r]{n.uri||!n.parts&&!n.preloadHints||(!n.map&&r&&(n.map=r),!n.key&&o&&(n.key=o),!n.timeline&&typeof p=="number"&&(n.timeline=p),this.manifest.preloadSegment=n)}),this.parseStream.on("data",function(_){let w,D;if(t.manifest.definitions){for(const I in t.manifest.definitions)if(_.uri&&(_.uri=_.uri.replace(`{$${I}}`,t.manifest.definitions[I])),_.attributes)for(const L in _.attributes)typeof _.attributes[L]=="string"&&(_.attributes[L]=_.attributes[L].replace(`{$${I}}`,t.manifest.definitions[I]))}({tag(){({version(){_.version&&(this.manifest.version=_.version)},"allow-cache"(){this.manifest.allowCache=_.allowed,"allowed"in _||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const I={};"length"in _&&(n.byterange=I,I.length=_.length,"offset"in _||(_.offset=g)),"offset"in _&&(n.byterange=I,I.offset=_.offset),g=I.offset+I.length},endlist(){this.manifest.endList=!0},inf(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),"discontinuitySequence"in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger("info",{message:"defaulting discontinuity sequence to zero"})),_.title&&(n.title=_.title),_.duration>0&&(n.duration=_.duration),_.duration===0&&(n.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=i},key(){if(!_.attributes){this.trigger("warn",{message:"ignoring key declaration without attribute list"});return}if(_.attributes.METHOD==="NONE"){o=null;return}if(!_.attributes.URI){this.trigger("warn",{message:"ignoring key declaration without URI"});return}if(_.attributes.KEYFORMAT==="com.apple.streamingkeydelivery"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:_.attributes};return}if(_.attributes.KEYFORMAT==="com.microsoft.playready"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.microsoft.playready"]={uri:_.attributes.URI};return}if(_.attributes.KEYFORMAT===f){if(["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(_.attributes.METHOD)===-1){this.trigger("warn",{message:"invalid key method provided for Widevine"});return}if(_.attributes.METHOD==="SAMPLE-AES-CENC"&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),_.attributes.URI.substring(0,23)!=="data:text/plain;base64,"){this.trigger("warn",{message:"invalid key URI provided for Widevine"});return}if(!(_.attributes.KEYID&&_.attributes.KEYID.substring(0,2)==="0x")){this.trigger("warn",{message:"invalid key ID provided for Widevine"});return}this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:_.attributes.KEYFORMAT,keyId:_.attributes.KEYID.substring(2)},pssh:SA(_.attributes.URI.split(",")[1])};return}_.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),o={method:_.attributes.METHOD||"AES-128",uri:_.attributes.URI},typeof _.attributes.IV<"u"&&(o.iv=_.attributes.IV)},"media-sequence"(){if(!isFinite(_.number)){this.trigger("warn",{message:"ignoring invalid media sequence: "+_.number});return}this.manifest.mediaSequence=_.number},"discontinuity-sequence"(){if(!isFinite(_.number)){this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+_.number});return}this.manifest.discontinuitySequence=_.number,p=_.number},"playlist-type"(){if(!/VOD|EVENT/.test(_.playlistType)){this.trigger("warn",{message:"ignoring unknown playlist type: "+_.playlist});return}this.manifest.playlistType=_.playlistType},map(){r={},_.uri&&(r.uri=_.uri),_.byterange&&(r.byterange=_.byterange),o&&(r.key=o)},"stream-inf"(){if(this.manifest.playlists=i,this.manifest.mediaGroups=this.manifest.mediaGroups||d,!_.attributes){this.trigger("warn",{message:"ignoring empty stream-inf attributes"});return}n.attributes||(n.attributes={}),Es(n.attributes,_.attributes)},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||d,!(_.attributes&&_.attributes.TYPE&&_.attributes["GROUP-ID"]&&_.attributes.NAME)){this.trigger("warn",{message:"ignoring incomplete or missing media group"});return}const I=this.manifest.mediaGroups[_.attributes.TYPE];I[_.attributes["GROUP-ID"]]=I[_.attributes["GROUP-ID"]]||{},w=I[_.attributes["GROUP-ID"]],D={default:/yes/i.test(_.attributes.DEFAULT)},D.default?D.autoselect=!0:D.autoselect=/yes/i.test(_.attributes.AUTOSELECT),_.attributes.LANGUAGE&&(D.language=_.attributes.LANGUAGE),_.attributes.URI&&(D.uri=_.attributes.URI),_.attributes["INSTREAM-ID"]&&(D.instreamId=_.attributes["INSTREAM-ID"]),_.attributes.CHARACTERISTICS&&(D.characteristics=_.attributes.CHARACTERISTICS),_.attributes.FORCED&&(D.forced=/yes/i.test(_.attributes.FORCED)),w[_.attributes.NAME]=D},discontinuity(){p+=1,n.discontinuity=!0,this.manifest.discontinuityStarts.push(i.length)},"program-date-time"(){typeof this.manifest.dateTimeString>"u"&&(this.manifest.dateTimeString=_.dateTimeString,this.manifest.dateTimeObject=_.dateTimeObject),n.dateTimeString=_.dateTimeString,n.dateTimeObject=_.dateTimeObject;const{lastProgramDateTime:I}=this;this.lastProgramDateTime=new Date(_.dateTimeString).getTime(),I===null&&this.manifest.segments.reduceRight((L,B)=>(B.programDateTime=L-B.duration*1e3,B.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(_.duration)||_.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+_.duration});return}this.manifest.targetDuration=_.duration,Dy.call(this,this.manifest)},start(){if(!_.attributes||isNaN(_.attributes["TIME-OFFSET"])){this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"});return}this.manifest.start={timeOffset:_.attributes["TIME-OFFSET"],precise:_.attributes.PRECISE}},"cue-out"(){n.cueOut=_.data},"cue-out-cont"(){n.cueOutCont=_.data},"cue-in"(){n.cueIn=_.data},skip(){this.manifest.skip=Io(_.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",_.attributes,["SKIPPED-SEGMENTS"])},part(){u=!0;const I=this.manifest.segments.length,L=Io(_.attributes);n.parts=n.parts||[],n.parts.push(L),L.byterange&&(L.byterange.hasOwnProperty("offset")||(L.byterange.offset=y),y=L.byterange.offset+L.byterange.length);const B=n.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${B} for segment #${I}`,_.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((j,V)=>{j.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${V} lacks required attribute(s): LAST-PART`})})},"server-control"(){const I=this.manifest.serverControl=Io(_.attributes);I.hasOwnProperty("canBlockReload")||(I.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),Dy.call(this,this.manifest),I.canSkipDateranges&&!I.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint"(){const I=this.manifest.segments.length,L=Io(_.attributes),B=L.type&&L.type==="PART";n.preloadHints=n.preloadHints||[],n.preloadHints.push(L),L.byterange&&(L.byterange.hasOwnProperty("offset")||(L.byterange.offset=B?y:0,B&&(y=L.byterange.offset+L.byterange.length)));const j=n.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${j} for segment #${I}`,_.attributes,["TYPE","URI"]),!!L.type)for(let V=0;VV.id===L.id);this.manifest.dateRanges[j]=Es(this.manifest.dateRanges[j],L),x[L.id]=Es(x[L.id],L),this.manifest.dateRanges.pop()}},"independent-segments"(){this.manifest.independentSegments=!0},"i-frames-only"(){this.manifest.iFramesOnly=!0,this.requiredCompatibilityversion(this.manifest.version,4)},"content-steering"(){this.manifest.contentSteering=Io(_.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",_.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const I=(L,B)=>{if(L in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${L}`});return}this.manifest.definitions[L]=B};if("QUERYPARAM"in _.attributes){if("NAME"in _.attributes||"IMPORT"in _.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}const L=this.params.get(_.attributes.QUERYPARAM);if(!L){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${_.attributes.QUERYPARAM}`});return}I(_.attributes.QUERYPARAM,decodeURIComponent(L));return}if("NAME"in _.attributes){if("IMPORT"in _.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}if(!("VALUE"in _.attributes)||typeof _.attributes.VALUE!="string"){this.trigger("error",{message:`EXT-X-DEFINE: No value for ${_.attributes.NAME}`});return}I(_.attributes.NAME,_.attributes.VALUE);return}if("IMPORT"in _.attributes){if(!this.mainDefinitions[_.attributes.IMPORT]){this.trigger("error",{message:`EXT-X-DEFINE: No value ${_.attributes.IMPORT} to import, or IMPORT used on main playlist`});return}I(_.attributes.IMPORT,this.mainDefinitions[_.attributes.IMPORT]);return}this.trigger("error",{message:"EXT-X-DEFINE: No attribute"})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:_.attributes,uri:_.uri,timeline:p}),this.warnOnMissingAttributes_("#EXT-X-I-FRAME-STREAM-INF",_.attributes,["BANDWIDTH","URI"])}}[_.tagType]||c).call(t)},uri(){n.uri=_.uri,i.push(n),this.manifest.targetDuration&&!("duration"in n)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),n.duration=this.manifest.targetDuration),o&&(n.key=o),n.timeline=p,r&&(n.map=r),y=0,this.lastProgramDateTime!==null&&(n.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=n.duration*1e3),n={}},comment(){},custom(){_.segment?(n.custom=n.custom||{},n.custom[_.customType]=_.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[_.customType]=_.data)}})[_.type].call(t)})}requiredCompatibilityversion(e,t){(ep&&(f-=p,f-=p,f-=Ws(2))}return Number(f)},KM=function(e,t){var i={},n=i.le,r=n===void 0?!1:n;(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&e!==e)&&(e=0),e=Ws(e);for(var o=GM(e),u=new Uint8Array(new ArrayBuffer(o)),c=0;c=t.length&&d.call(t,function(f,p){var g=c[p]?c[p]&e[o+p]:e[o+p];return f===g})},WM=function(e,t,i){t.forEach(function(n){for(var r in e.mediaGroups[n])for(var o in e.mediaGroups[n][r]){var u=e.mediaGroups[n][r][o];i(u,n,r,o)}})},Md={},Oa={},Cl={},YS;function jp(){if(YS)return Cl;YS=1;function s(r,o,u){if(u===void 0&&(u=Array.prototype),r&&typeof u.find=="function")return u.find.call(r,o);for(var c=0;c=0&&G=0){for(var Ze=W.length-1;Ee0},lookupPrefix:function(G){for(var W=this;W;){var oe=W._nsMap;if(oe){for(var Ee in oe)if(Object.prototype.hasOwnProperty.call(oe,Ee)&&oe[Ee]===G)return Ee}W=W.nodeType==g?W.ownerDocument:W.parentNode}return null},lookupNamespaceURI:function(G){for(var W=this;W;){var oe=W._nsMap;if(oe&&Object.prototype.hasOwnProperty.call(oe,G))return oe[G];W=W.nodeType==g?W.ownerDocument:W.parentNode}return null},isDefaultNamespace:function(G){var W=this.lookupPrefix(G);return W==null}};function ee(G){return G=="<"&&"<"||G==">"&&">"||G=="&"&&"&"||G=='"'&&"""||"&#"+G.charCodeAt()+";"}c(f,$),c(f,$.prototype);function le(G,W){if(W(G))return!0;if(G=G.firstChild)do if(le(G,W))return!0;while(G=G.nextSibling)}function be(){this.ownerDocument=this}function fe(G,W,oe){G&&G._inc++;var Ee=oe.namespaceURI;Ee===t.XMLNS&&(W._nsMap[oe.prefix?oe.localName:""]=oe.value)}function _e(G,W,oe,Ee){G&&G._inc++;var Ze=oe.namespaceURI;Ze===t.XMLNS&&delete W._nsMap[oe.prefix?oe.localName:""]}function Me(G,W,oe){if(G&&G._inc){G._inc++;var Ee=W.childNodes;if(oe)Ee[Ee.length++]=oe;else{for(var Ze=W.firstChild,Et=0;Ze;)Ee[Et++]=Ze,Ze=Ze.nextSibling;Ee.length=Et,delete Ee[Ee.length]}}}function et(G,W){var oe=W.previousSibling,Ee=W.nextSibling;return oe?oe.nextSibling=Ee:G.firstChild=Ee,Ee?Ee.previousSibling=oe:G.lastChild=oe,W.parentNode=null,W.previousSibling=null,W.nextSibling=null,Me(G.ownerDocument,G),W}function Ge(G){return G&&(G.nodeType===$.DOCUMENT_NODE||G.nodeType===$.DOCUMENT_FRAGMENT_NODE||G.nodeType===$.ELEMENT_NODE)}function lt(G){return G&&(mt(G)||Vt(G)||At(G)||G.nodeType===$.DOCUMENT_FRAGMENT_NODE||G.nodeType===$.COMMENT_NODE||G.nodeType===$.PROCESSING_INSTRUCTION_NODE)}function At(G){return G&&G.nodeType===$.DOCUMENT_TYPE_NODE}function mt(G){return G&&G.nodeType===$.ELEMENT_NODE}function Vt(G){return G&&G.nodeType===$.TEXT_NODE}function Re(G,W){var oe=G.childNodes||[];if(e(oe,mt)||At(W))return!1;var Ee=e(oe,At);return!(W&&Ee&&oe.indexOf(Ee)>oe.indexOf(W))}function dt(G,W){var oe=G.childNodes||[];function Ee(Et){return mt(Et)&&Et!==W}if(e(oe,Ee))return!1;var Ze=e(oe,At);return!(W&&Ze&&oe.indexOf(Ze)>oe.indexOf(W))}function He(G,W,oe){if(!Ge(G))throw new Q(O,"Unexpected parent node type "+G.nodeType);if(oe&&oe.parentNode!==G)throw new Q(N,"child not in parent");if(!lt(W)||At(W)&&G.nodeType!==$.DOCUMENT_NODE)throw new Q(O,"Unexpected node type "+W.nodeType+" for parent node type "+G.nodeType)}function tt(G,W,oe){var Ee=G.childNodes||[],Ze=W.childNodes||[];if(W.nodeType===$.DOCUMENT_FRAGMENT_NODE){var Et=Ze.filter(mt);if(Et.length>1||e(Ze,Vt))throw new Q(O,"More than one element or text in fragment");if(Et.length===1&&!Re(G,oe))throw new Q(O,"Element in fragment can not be inserted before doctype")}if(mt(W)&&!Re(G,oe))throw new Q(O,"Only one element can be added and only after doctype");if(At(W)){if(e(Ee,At))throw new Q(O,"Only one doctype is allowed");var Jt=e(Ee,mt);if(oe&&Ee.indexOf(Jt)1||e(Ze,Vt))throw new Q(O,"More than one element or text in fragment");if(Et.length===1&&!dt(G,oe))throw new Q(O,"Element in fragment can not be inserted before doctype")}if(mt(W)&&!dt(G,oe))throw new Q(O,"Only one element can be added and only after doctype");if(At(W)){let Ji=function(Ci){return At(Ci)&&Ci!==oe};var Li=Ji;if(e(Ee,Ji))throw new Q(O,"Only one doctype is allowed");var Jt=e(Ee,mt);if(oe&&Ee.indexOf(Jt)0&&le(oe.documentElement,function(Ze){if(Ze!==oe&&Ze.nodeType===p){var Et=Ze.getAttribute("class");if(Et){var Jt=G===Et;if(!Jt){var Li=o(Et);Jt=W.every(u(Li))}Jt&&Ee.push(Ze)}}}),Ee})},createElement:function(G){var W=new yt;W.ownerDocument=this,W.nodeName=G,W.tagName=G,W.localName=G,W.childNodes=new Y;var oe=W.attributes=new H;return oe._ownerElement=W,W},createDocumentFragment:function(){var G=new Xe;return G.ownerDocument=this,G.childNodes=new Y,G},createTextNode:function(G){var W=new ai;return W.ownerDocument=this,W.appendData(G),W},createComment:function(G){var W=new Zt;return W.ownerDocument=this,W.appendData(G),W},createCDATASection:function(G){var W=new $e;return W.ownerDocument=this,W.appendData(G),W},createProcessingInstruction:function(G,W){var oe=new Ot;return oe.ownerDocument=this,oe.tagName=oe.nodeName=oe.target=G,oe.nodeValue=oe.data=W,oe},createAttribute:function(G){var W=new Gt;return W.ownerDocument=this,W.name=G,W.nodeName=G,W.localName=G,W.specified=!0,W},createEntityReference:function(G){var W=new Wt;return W.ownerDocument=this,W.nodeName=G,W},createElementNS:function(G,W){var oe=new yt,Ee=W.split(":"),Ze=oe.attributes=new H;return oe.childNodes=new Y,oe.ownerDocument=this,oe.nodeName=W,oe.tagName=W,oe.namespaceURI=G,Ee.length==2?(oe.prefix=Ee[0],oe.localName=Ee[1]):oe.localName=W,Ze._ownerElement=oe,oe},createAttributeNS:function(G,W){var oe=new Gt,Ee=W.split(":");return oe.ownerDocument=this,oe.nodeName=W,oe.name=W,oe.namespaceURI=G,oe.specified=!0,Ee.length==2?(oe.prefix=Ee[0],oe.localName=Ee[1]):oe.localName=W,oe}},d(be,$);function yt(){this._nsMap={}}yt.prototype={nodeType:p,hasAttribute:function(G){return this.getAttributeNode(G)!=null},getAttribute:function(G){var W=this.getAttributeNode(G);return W&&W.value||""},getAttributeNode:function(G){return this.attributes.getNamedItem(G)},setAttribute:function(G,W){var oe=this.ownerDocument.createAttribute(G);oe.value=oe.nodeValue=""+W,this.setAttributeNode(oe)},removeAttribute:function(G){var W=this.getAttributeNode(G);W&&this.removeAttributeNode(W)},appendChild:function(G){return G.nodeType===j?this.insertBefore(G,null):pt(this,G)},setAttributeNode:function(G){return this.attributes.setNamedItem(G)},setAttributeNodeNS:function(G){return this.attributes.setNamedItemNS(G)},removeAttributeNode:function(G){return this.attributes.removeNamedItem(G.nodeName)},removeAttributeNS:function(G,W){var oe=this.getAttributeNodeNS(G,W);oe&&this.removeAttributeNode(oe)},hasAttributeNS:function(G,W){return this.getAttributeNodeNS(G,W)!=null},getAttributeNS:function(G,W){var oe=this.getAttributeNodeNS(G,W);return oe&&oe.value||""},setAttributeNS:function(G,W,oe){var Ee=this.ownerDocument.createAttributeNS(G,W);Ee.value=Ee.nodeValue=""+oe,this.setAttributeNode(Ee)},getAttributeNodeNS:function(G,W){return this.attributes.getNamedItemNS(G,W)},getElementsByTagName:function(G){return new re(this,function(W){var oe=[];return le(W,function(Ee){Ee!==W&&Ee.nodeType==p&&(G==="*"||Ee.tagName==G)&&oe.push(Ee)}),oe})},getElementsByTagNameNS:function(G,W){return new re(this,function(oe){var Ee=[];return le(oe,function(Ze){Ze!==oe&&Ze.nodeType===p&&(G==="*"||Ze.namespaceURI===G)&&(W==="*"||Ze.localName==W)&&Ee.push(Ze)}),Ee})}},be.prototype.getElementsByTagName=yt.prototype.getElementsByTagName,be.prototype.getElementsByTagNameNS=yt.prototype.getElementsByTagNameNS,d(yt,$);function Gt(){}Gt.prototype.nodeType=g,d(Gt,$);function Ut(){}Ut.prototype={data:"",substringData:function(G,W){return this.data.substring(G,G+W)},appendData:function(G){G=this.data+G,this.nodeValue=this.data=G,this.length=G.length},insertData:function(G,W){this.replaceData(G,0,W)},appendChild:function(G){throw new Error(z[O])},deleteData:function(G,W){this.replaceData(G,W,"")},replaceData:function(G,W,oe){var Ee=this.data.substring(0,G),Ze=this.data.substring(G+W);oe=Ee+oe+Ze,this.nodeValue=this.data=oe,this.length=oe.length}},d(Ut,$);function ai(){}ai.prototype={nodeName:"#text",nodeType:y,splitText:function(G){var W=this.data,oe=W.substring(G);W=W.substring(0,G),this.data=this.nodeValue=W,this.length=W.length;var Ee=this.ownerDocument.createTextNode(oe);return this.parentNode&&this.parentNode.insertBefore(Ee,this.nextSibling),Ee}},d(ai,Ut);function Zt(){}Zt.prototype={nodeName:"#comment",nodeType:I},d(Zt,Ut);function $e(){}$e.prototype={nodeName:"#cdata-section",nodeType:x},d($e,Ut);function ct(){}ct.prototype.nodeType=B,d(ct,$);function it(){}it.prototype.nodeType=V,d(it,$);function Tt(){}Tt.prototype.nodeType=w,d(Tt,$);function Wt(){}Wt.prototype.nodeType=_,d(Wt,$);function Xe(){}Xe.prototype.nodeName="#document-fragment",Xe.prototype.nodeType=j,d(Xe,$);function Ot(){}Ot.prototype.nodeType=D,d(Ot,$);function kt(){}kt.prototype.serializeToString=function(G,W,oe){return Xt.call(G,W,oe)},$.prototype.toString=Xt;function Xt(G,W){var oe=[],Ee=this.nodeType==9&&this.documentElement||this,Ze=Ee.prefix,Et=Ee.namespaceURI;if(Et&&Ze==null){var Ze=Ee.lookupPrefix(Et);if(Ze==null)var Jt=[{namespace:Et,prefix:null}]}return Ai(this,oe,G,W,Jt),oe.join("")}function ni(G,W,oe){var Ee=G.prefix||"",Ze=G.namespaceURI;if(!Ze||Ee==="xml"&&Ze===t.XML||Ze===t.XMLNS)return!1;for(var Et=oe.length;Et--;){var Jt=oe[Et];if(Jt.prefix===Ee)return Jt.namespace!==Ze}return!0}function hi(G,W,oe){G.push(" ",W,'="',oe.replace(/[<>&"\t\n\r]/g,ee),'"')}function Ai(G,W,oe,Ee,Ze){if(Ze||(Ze=[]),Ee)if(G=Ee(G),G){if(typeof G=="string"){W.push(G);return}}else return;switch(G.nodeType){case p:var Et=G.attributes,Jt=Et.length,ei=G.firstChild,Li=G.tagName;oe=t.isHTML(G.namespaceURI)||oe;var Ji=Li;if(!oe&&!G.prefix&&G.namespaceURI){for(var Ci,ss=0;ss=0;Hi--){var fi=Ze[Hi];if(fi.prefix===""&&fi.namespace===G.namespaceURI){Ci=fi.namespace;break}}if(Ci!==G.namespaceURI)for(var Hi=Ze.length-1;Hi>=0;Hi--){var fi=Ze[Hi];if(fi.namespace===G.namespaceURI){fi.prefix&&(Ji=fi.prefix+":"+Li);break}}}W.push("<",Ji);for(var ns=0;ns"),oe&&/^script$/i.test(Li))for(;ei;)ei.data?W.push(ei.data):Ai(ei,W,oe,Ee,Ze.slice()),ei=ei.nextSibling;else for(;ei;)Ai(ei,W,oe,Ee,Ze.slice()),ei=ei.nextSibling;W.push("")}else W.push("/>");return;case L:case j:for(var ei=G.firstChild;ei;)Ai(ei,W,oe,Ee,Ze.slice()),ei=ei.nextSibling;return;case g:return hi(W,G.name,G.value);case y:return W.push(G.data.replace(/[<&>]/g,ee));case x:return W.push("");case I:return W.push("");case B:var Ht=G.publicId,Rs=G.systemId;if(W.push("");else if(Rs&&Rs!=".")W.push(" SYSTEM ",Rs,">");else{var Zs=G.internalSubset;Zs&&W.push(" [",Zs,"]"),W.push(">")}return;case D:return W.push("");case _:return W.push("&",G.nodeName,";");default:W.push("??",G.nodeName)}}function Nt(G,W,oe){var Ee;switch(W.nodeType){case p:Ee=W.cloneNode(!1),Ee.ownerDocument=G;case j:break;case g:oe=!0;break}if(Ee||(Ee=W.cloneNode(!1)),Ee.ownerDocument=G,Ee.parentNode=null,oe)for(var Ze=W.firstChild;Ze;)Ee.appendChild(Nt(G,Ze,oe)),Ze=Ze.nextSibling;return Ee}function bt(G,W,oe){var Ee=new W.constructor;for(var Ze in W)if(Object.prototype.hasOwnProperty.call(W,Ze)){var Et=W[Ze];typeof Et!="object"&&Et!=Ee[Ze]&&(Ee[Ze]=Et)}switch(W.childNodes&&(Ee.childNodes=new Y),Ee.ownerDocument=G,Ee.nodeType){case p:var Jt=W.attributes,Li=Ee.attributes=new H,Ji=Jt.length;Li._ownerElement=Ee;for(var Ci=0;Ci",lt:"<",quot:'"'}),s.HTML_ENTITIES=e({Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"⁡",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"ℭ",cfr:"𝔠",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"𝕔",coprod:"∐",Coproduct:"∐",COPY:"©",copy:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"𝒻",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",Gt:"≫",GT:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"𝔥",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"𝕙",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"𝒽",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"ℑ",ifr:"𝔦",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"ℐ",iscr:"𝒾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"𝓁",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",Lt:"≪",LT:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",Mscr:"ℳ",mscr:"𝓂",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:` +`,nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",nopf:"𝕟",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"𝕡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",Qopf:"ℚ",qopf:"𝕢",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"𝔯",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"𝓇",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:" ",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}),s.entityMap=s.HTML_ENTITIES})(Ry)),Ry}var om={},QS;function QM(){if(QS)return om;QS=1;var s=jp().NAMESPACE,e=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,t=new RegExp("[\\-\\.0-9"+e.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),i=new RegExp("^"+e.source+t.source+"*(?::"+e.source+t.source+"*)?$"),n=0,r=1,o=2,u=3,c=4,d=5,f=6,p=7;function g(O,N){this.message=O,this.locator=N,Error.captureStackTrace&&Error.captureStackTrace(this,g)}g.prototype=new Error,g.prototype.name=g.name;function y(){}y.prototype={parse:function(O,N,q){var Q=this.domBuilder;Q.startDocument(),B(N,N={}),x(O,N,q,Q,this.errorHandler),Q.endDocument()}};function x(O,N,q,Q,Y){function re(pt){if(pt>65535){pt-=65536;var yt=55296+(pt>>10),Gt=56320+(pt&1023);return String.fromCharCode(yt,Gt)}else return String.fromCharCode(pt)}function Z(pt){var yt=pt.slice(1,-1);return Object.hasOwnProperty.call(q,yt)?q[yt]:yt.charAt(0)==="#"?re(parseInt(yt.substr(1).replace("x","0x"))):(Y.error("entity not found:"+pt),pt)}function H(pt){if(pt>be){var yt=O.substring(be,pt).replace(/&#?\w+;/g,Z);$&&K(be),Q.characters(yt,0,pt-be),be=pt}}function K(pt,yt){for(;pt>=te&&(yt=ne.exec(O));)ie=yt.index,te=ie+yt[0].length,$.lineNumber++;$.columnNumber=pt-ie+1}for(var ie=0,te=0,ne=/.*(?:\r\n?|\n)|.*$/g,$=Q.locator,ee=[{currentNSMap:N}],le={},be=0;;){try{var fe=O.indexOf("<",be);if(fe<0){if(!O.substr(be).match(/^\s*$/)){var _e=Q.doc,Me=_e.createTextNode(O.substr(be));_e.appendChild(Me),Q.currentElement=Me}return}switch(fe>be&&H(fe),O.charAt(fe+1)){case"/":var He=O.indexOf(">",fe+3),et=O.substring(fe+2,He).replace(/[ \t\n\r]+$/g,""),Ge=ee.pop();He<0?(et=O.substring(fe+2).replace(/[\s<].*/,""),Y.error("end tag name: "+et+" is not complete:"+Ge.tagName),He=fe+1+et.length):et.match(/\sbe?be=He:H(Math.max(fe,be)+1)}}function _(O,N){return N.lineNumber=O.lineNumber,N.columnNumber=O.columnNumber,N}function w(O,N,q,Q,Y,re){function Z($,ee,le){q.attributeNames.hasOwnProperty($)&&re.fatalError("Attribute "+$+" redefined"),q.addValue($,ee.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,Y),le)}for(var H,K,ie=++N,te=n;;){var ne=O.charAt(ie);switch(ne){case"=":if(te===r)H=O.slice(N,ie),te=u;else if(te===o)te=u;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(te===u||te===r)if(te===r&&(re.warning('attribute value must after "="'),H=O.slice(N,ie)),N=ie+1,ie=O.indexOf(ne,N),ie>0)K=O.slice(N,ie),Z(H,K,N-1),te=d;else throw new Error("attribute value no end '"+ne+"' match");else if(te==c)K=O.slice(N,ie),Z(H,K,N),re.warning('attribute "'+H+'" missed start quot('+ne+")!!"),N=ie+1,te=d;else throw new Error('attribute value must after "="');break;case"/":switch(te){case n:q.setTagName(O.slice(N,ie));case d:case f:case p:te=p,q.closed=!0;case c:case r:break;case o:q.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return re.error("unexpected end of input"),te==n&&q.setTagName(O.slice(N,ie)),ie;case">":switch(te){case n:q.setTagName(O.slice(N,ie));case d:case f:case p:break;case c:case r:K=O.slice(N,ie),K.slice(-1)==="/"&&(q.closed=!0,K=K.slice(0,-1));case o:te===o&&(K=H),te==c?(re.warning('attribute "'+K+'" missed quot(")!'),Z(H,K,N)):((!s.isHTML(Q[""])||!K.match(/^(?:disabled|checked|selected)$/i))&&re.warning('attribute "'+K+'" missed value!! "'+K+'" instead!!'),Z(K,K,N));break;case u:throw new Error("attribute value missed!!")}return ie;case"€":ne=" ";default:if(ne<=" ")switch(te){case n:q.setTagName(O.slice(N,ie)),te=f;break;case r:H=O.slice(N,ie),te=o;break;case c:var K=O.slice(N,ie);re.warning('attribute "'+K+'" missed quot(")!!'),Z(H,K,N);case d:te=f;break}else switch(te){case o:q.tagName,(!s.isHTML(Q[""])||!H.match(/^(?:disabled|checked|selected)$/i))&&re.warning('attribute "'+H+'" missed value!! "'+H+'" instead2!!'),Z(H,H,N),N=ie,te=r;break;case d:re.warning('attribute space is required"'+H+'"!!');case f:te=r,N=ie;break;case u:te=c,N=ie;break;case p:throw new Error("elements closed character '/' and '>' must be connected to")}}ie++}}function D(O,N,q){for(var Q=O.tagName,Y=null,ne=O.length;ne--;){var re=O[ne],Z=re.qName,H=re.value,$=Z.indexOf(":");if($>0)var K=re.prefix=Z.slice(0,$),ie=Z.slice($+1),te=K==="xmlns"&&ie;else ie=Z,K=null,te=Z==="xmlns"&&"";re.localName=ie,te!==!1&&(Y==null&&(Y={},B(q,q={})),q[te]=Y[te]=H,re.uri=s.XMLNS,N.startPrefixMapping(te,H))}for(var ne=O.length;ne--;){re=O[ne];var K=re.prefix;K&&(K==="xml"&&(re.uri=s.XML),K!=="xmlns"&&(re.uri=q[K||""]))}var $=Q.indexOf(":");$>0?(K=O.prefix=Q.slice(0,$),ie=O.localName=Q.slice($+1)):(K=null,ie=O.localName=Q);var ee=O.uri=q[K||""];if(N.startElement(ee,ie,Q,O),O.closed){if(N.endElement(ee,ie,Q),Y)for(K in Y)Object.prototype.hasOwnProperty.call(Y,K)&&N.endPrefixMapping(K)}else return O.currentNSMap=q,O.localNSMap=Y,!0}function I(O,N,q,Q,Y){if(/^(?:script|textarea)$/i.test(q)){var re=O.indexOf("",N),Z=O.substring(N+1,re);if(/[&<]/.test(Z))return/^script$/i.test(q)?(Y.characters(Z,0,Z.length),re):(Z=Z.replace(/&#?\w+;/g,Q),Y.characters(Z,0,Z.length),re)}return N+1}function L(O,N,q,Q){var Y=Q[q];return Y==null&&(Y=O.lastIndexOf(""),Y",N+4);return re>N?(q.comment(O,N+4,re-N-4),re+3):(Q.error("Unclosed comment"),-1)}else return-1;default:if(O.substr(N+3,6)=="CDATA["){var re=O.indexOf("]]>",N+9);return q.startCDATA(),q.characters(O,N+9,re-N-9),q.endCDATA(),re+3}var Z=z(O,N),H=Z.length;if(H>1&&/!doctype/i.test(Z[0][0])){var K=Z[1][0],ie=!1,te=!1;H>3&&(/^public$/i.test(Z[2][0])?(ie=Z[3][0],te=H>4&&Z[4][0]):/^system$/i.test(Z[2][0])&&(te=Z[3][0]));var ne=Z[H-1];return q.startDTD(K,ie,te),q.endDTD(),ne.index+ne[0].length}}return-1}function V(O,N,q){var Q=O.indexOf("?>",N);if(Q){var Y=O.substring(N,Q).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return Y?(Y[0].length,q.processingInstruction(Y[1],Y[2]),Q+2):-1}return-1}function M(){this.attributeNames={}}M.prototype={setTagName:function(O){if(!i.test(O))throw new Error("invalid tagName:"+O);this.tagName=O},addValue:function(O,N,q){if(!i.test(O))throw new Error("invalid attribute:"+O);this.attributeNames[O]=this.length,this[this.length++]={qName:O,value:N,offset:q}},length:0,getLocalName:function(O){return this[O].localName},getLocator:function(O){return this[O].locator},getQName:function(O){return this[O].qName},getURI:function(O){return this[O].uri},getValue:function(O){return this[O].value}};function z(O,N){var q,Q=[],Y=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(Y.lastIndex=N,Y.exec(O);q=Y.exec(O);)if(Q.push(q),q[1])return Q}return om.XMLReader=y,om.ParseError=g,om}var ZS;function ZM(){if(ZS)return Pd;ZS=1;var s=jp(),e=DA(),t=XM(),i=QM(),n=e.DOMImplementation,r=s.NAMESPACE,o=i.ParseError,u=i.XMLReader;function c(w){return w.replace(/\r[\n\u0085]/g,` +`).replace(/[\r\u0085\u2028]/g,` +`)}function d(w){this.options=w||{locator:{}}}d.prototype.parseFromString=function(w,D){var I=this.options,L=new u,B=I.domBuilder||new p,j=I.errorHandler,V=I.locator,M=I.xmlns||{},z=/\/x?html?$/.test(D),O=z?t.HTML_ENTITIES:t.XML_ENTITIES;V&&B.setDocumentLocator(V),L.errorHandler=f(j,B,V),L.domBuilder=I.domBuilder||B,z&&(M[""]=r.HTML),M.xml=M.xml||r.XML;var N=I.normalizeLineEndings||c;return w&&typeof w=="string"?L.parse(N(w),M,O):L.errorHandler.error("invalid doc source"),B.doc};function f(w,D,I){if(!w){if(D instanceof p)return D;w=D}var L={},B=w instanceof Function;I=I||{};function j(V){var M=w[V];!M&&B&&(M=w.length==2?function(z){w(V,z)}:w),L[V]=M&&function(z){M("[xmldom "+V+"] "+z+y(I))}||function(){}}return j("warning"),j("error"),j("fatalError"),L}function p(){this.cdata=!1}function g(w,D){D.lineNumber=w.lineNumber,D.columnNumber=w.columnNumber}p.prototype={startDocument:function(){this.doc=new n().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(w,D,I,L){var B=this.doc,j=B.createElementNS(w,I||D),V=L.length;_(this,j),this.currentElement=j,this.locator&&g(this.locator,j);for(var M=0;M=D+I||D?new java.lang.String(w,D,I)+"":w}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(w){p.prototype[w]=function(){return null}});function _(w,D){w.currentElement?w.currentElement.appendChild(D):w.doc.appendChild(D)}return Pd.__DOMHandler=p,Pd.normalizeLineEndings=c,Pd.DOMParser=d,Pd}var JS;function JM(){if(JS)return Md;JS=1;var s=DA();return Md.DOMImplementation=s.DOMImplementation,Md.XMLSerializer=s.XMLSerializer,Md.DOMParser=ZM().DOMParser,Md}var eP=JM();const eE=s=>!!s&&typeof s=="object",Hs=(...s)=>s.reduce((e,t)=>(typeof t!="object"||Object.keys(t).forEach(i=>{Array.isArray(e[i])&&Array.isArray(t[i])?e[i]=e[i].concat(t[i]):eE(e[i])&&eE(t[i])?e[i]=Hs(e[i],t[i]):e[i]=t[i]}),e),{}),LA=s=>Object.keys(s).map(e=>s[e]),tP=(s,e)=>{const t=[];for(let i=s;is.reduce((e,t)=>e.concat(t),[]),RA=s=>{if(!s.length)return[];const e=[];for(let t=0;ts.reduce((t,i,n)=>(i[e]&&t.push(n),t),[]),sP=(s,e)=>LA(s.reduce((t,i)=>(i.forEach(n=>{t[e(n)]=n}),t),{}));var yc={INVALID_NUMBER_OF_PERIOD:"INVALID_NUMBER_OF_PERIOD",DASH_EMPTY_MANIFEST:"DASH_EMPTY_MANIFEST",DASH_INVALID_XML:"DASH_INVALID_XML",NO_BASE_URL:"NO_BASE_URL",SEGMENT_TIME_UNSPECIFIED:"SEGMENT_TIME_UNSPECIFIED",UNSUPPORTED_UTC_TIMING_SCHEME:"UNSUPPORTED_UTC_TIMING_SCHEME"};const dh=({baseUrl:s="",source:e="",range:t="",indexRange:i=""})=>{const n={uri:e,resolvedUri:Up(s||"",e)};if(t||i){const o=(t||i).split("-");let u=ue.BigInt?ue.BigInt(o[0]):parseInt(o[0],10),c=ue.BigInt?ue.BigInt(o[1]):parseInt(o[1],10);u{let e;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=ue.BigInt(s.offset)+ue.BigInt(s.length)-ue.BigInt(1):e=s.offset+s.length-1,`${s.offset}-${e}`},tE=s=>(s&&typeof s!="number"&&(s=parseInt(s,10)),isNaN(s)?null:s),rP={static(s){const{duration:e,timescale:t=1,sourceDuration:i,periodDuration:n}=s,r=tE(s.endNumber),o=e/t;return typeof r=="number"?{start:0,end:r}:typeof n=="number"?{start:0,end:n/o}:{start:0,end:i/o}},dynamic(s){const{NOW:e,clientOffset:t,availabilityStartTime:i,timescale:n=1,duration:r,periodStart:o=0,minimumUpdatePeriod:u=0,timeShiftBufferDepth:c=1/0}=s,d=tE(s.endNumber),f=(e+t)/1e3,p=i+o,y=f+u-p,x=Math.ceil(y*n/r),_=Math.floor((f-p-c)*n/r),w=Math.floor((f-p)*n/r);return{start:Math.max(0,_),end:typeof d=="number"?d:Math.min(x,w)}}},aP=s=>e=>{const{duration:t,timescale:i=1,periodStart:n,startNumber:r=1}=s;return{number:r+e,duration:t/i,timeline:n,time:e*t}},Gx=s=>{const{type:e,duration:t,timescale:i=1,periodDuration:n,sourceDuration:r}=s,{start:o,end:u}=rP[e](s),c=tP(o,u).map(aP(s));if(e==="static"){const d=c.length-1,f=typeof n=="number"?n:r;c[d].duration=f-t/i*d}return c},IA=s=>{const{baseUrl:e,initialization:t={},sourceDuration:i,indexRange:n="",periodStart:r,presentationTime:o,number:u=0,duration:c}=s;if(!e)throw new Error(yc.NO_BASE_URL);const d=dh({baseUrl:e,source:t.sourceURL,range:t.range}),f=dh({baseUrl:e,source:e,indexRange:n});if(f.map=d,c){const p=Gx(s);p.length&&(f.duration=p[0].duration,f.timeline=p[0].timeline)}else i&&(f.duration=i,f.timeline=r);return f.presentationTime=o||r,f.number=u,[f]},zx=(s,e,t)=>{const i=s.sidx.map?s.sidx.map:null,n=s.sidx.duration,r=s.timeline||0,o=s.sidx.byterange,u=o.offset+o.length,c=e.timescale,d=e.references.filter(w=>w.referenceType!==1),f=[],p=s.endList?"static":"dynamic",g=s.sidx.timeline;let y=g,x=s.mediaSequence||0,_;typeof e.firstOffset=="bigint"?_=ue.BigInt(u)+e.firstOffset:_=u+e.firstOffset;for(let w=0;wsP(s,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),uP=(s,e)=>{for(let t=0;t{let e=[];return WM(s,oP,(t,i,n,r)=>{e=e.concat(t.playlists||[])}),e},sE=({playlist:s,mediaSequence:e})=>{s.mediaSequence=e,s.segments.forEach((t,i)=>{t.number=s.mediaSequence+i})},cP=({oldPlaylists:s,newPlaylists:e,timelineStarts:t})=>{e.forEach(i=>{i.discontinuitySequence=t.findIndex(function({timeline:c}){return c===i.timeline});const n=uP(s,i.attributes.NAME);if(!n||i.sidx)return;const r=i.segments[0],o=n.segments.findIndex(function(c){return Math.abs(c.presentationTime-r.presentationTime)n.timeline||n.segments.length&&i.timeline>n.segments[n.segments.length-1].timeline)&&i.discontinuitySequence--;return}n.segments[o].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,i.discontinuityStarts.unshift(0),i.discontinuitySequence--),sE({playlist:i,mediaSequence:n.segments[o].number})})},dP=({oldManifest:s,newManifest:e})=>{const t=s.playlists.concat(iE(s)),i=e.playlists.concat(iE(e));return e.timelineStarts=NA([s.timelineStarts,e.timelineStarts]),cP({oldPlaylists:t,newPlaylists:i,timelineStarts:e.timelineStarts}),e},$p=s=>s&&s.uri+"-"+nP(s.byterange),Iy=s=>{const e=s.reduce(function(i,n){return i[n.attributes.baseUrl]||(i[n.attributes.baseUrl]=[]),i[n.attributes.baseUrl].push(n),i},{});let t=[];return Object.values(e).forEach(i=>{const n=LA(i.reduce((r,o)=>{const u=o.attributes.id+(o.attributes.lang||"");return r[u]?(o.segments&&(o.segments[0]&&(o.segments[0].discontinuity=!0),r[u].segments.push(...o.segments)),o.attributes.contentProtection&&(r[u].attributes.contentProtection=o.attributes.contentProtection)):(r[u]=o,r[u].attributes.timelineStarts=[]),r[u].attributes.timelineStarts.push({start:o.attributes.periodStart,timeline:o.attributes.periodStart}),r},{}));t=t.concat(n)}),t.map(i=>(i.discontinuityStarts=iP(i.segments||[],"discontinuity"),i))},qx=(s,e)=>{const t=$p(s.sidx),i=t&&e[t]&&e[t].sidx;return i&&zx(s,i,s.sidx.resolvedUri),s},hP=(s,e={})=>{if(!Object.keys(e).length)return s;for(const t in s)s[t]=qx(s[t],e);return s},fP=({attributes:s,segments:e,sidx:t,mediaSequence:i,discontinuitySequence:n,discontinuityStarts:r},o)=>{const u={attributes:{NAME:s.id,BANDWIDTH:s.bandwidth,CODECS:s.codecs,"PROGRAM-ID":1},uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,discontinuitySequence:n,discontinuityStarts:r,timelineStarts:s.timelineStarts,mediaSequence:i,segments:e};return s.contentProtection&&(u.contentProtection=s.contentProtection),s.serviceLocation&&(u.attributes.serviceLocation=s.serviceLocation),t&&(u.sidx=t),o&&(u.attributes.AUDIO="audio",u.attributes.SUBTITLES="subs"),u},mP=({attributes:s,segments:e,mediaSequence:t,discontinuityStarts:i,discontinuitySequence:n})=>{typeof e>"u"&&(e=[{uri:s.baseUrl,timeline:s.periodStart,resolvedUri:s.baseUrl||"",duration:s.sourceDuration,number:0}],s.duration=s.sourceDuration);const r={NAME:s.id,BANDWIDTH:s.bandwidth,"PROGRAM-ID":1};s.codecs&&(r.CODECS=s.codecs);const o={attributes:r,uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,timelineStarts:s.timelineStarts,discontinuityStarts:i,discontinuitySequence:n,mediaSequence:t,segments:e};return s.serviceLocation&&(o.attributes.serviceLocation=s.serviceLocation),o},pP=(s,e={},t=!1)=>{let i;const n=s.reduce((r,o)=>{const u=o.attributes.role&&o.attributes.role.value||"",c=o.attributes.lang||"";let d=o.attributes.label||"main";if(c&&!o.attributes.label){const p=u?` (${u})`:"";d=`${o.attributes.lang}${p}`}r[d]||(r[d]={language:c,autoselect:!0,default:u==="main",playlists:[],uri:""});const f=qx(fP(o,t),e);return r[d].playlists.push(f),typeof i>"u"&&u==="main"&&(i=o,i.default=!0),r},{});if(!i){const r=Object.keys(n)[0];n[r].default=!0}return n},gP=(s,e={})=>s.reduce((t,i)=>{const n=i.attributes.label||i.attributes.lang||"text",r=i.attributes.lang||"und";return t[n]||(t[n]={language:r,default:!1,autoselect:!1,playlists:[],uri:""}),t[n].playlists.push(qx(mP(i),e)),t},{}),yP=s=>s.reduce((e,t)=>(t&&t.forEach(i=>{const{channel:n,language:r}=i;e[r]={autoselect:!1,default:!1,instreamId:n,language:r},i.hasOwnProperty("aspectRatio")&&(e[r].aspectRatio=i.aspectRatio),i.hasOwnProperty("easyReader")&&(e[r].easyReader=i.easyReader),i.hasOwnProperty("3D")&&(e[r]["3D"]=i["3D"])}),e),{}),vP=({attributes:s,segments:e,sidx:t,discontinuityStarts:i})=>{const n={attributes:{NAME:s.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:s.width,height:s.height},CODECS:s.codecs,BANDWIDTH:s.bandwidth,"PROGRAM-ID":1},uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,discontinuityStarts:i,timelineStarts:s.timelineStarts,segments:e};return s.frameRate&&(n.attributes["FRAME-RATE"]=s.frameRate),s.contentProtection&&(n.contentProtection=s.contentProtection),s.serviceLocation&&(n.attributes.serviceLocation=s.serviceLocation),t&&(n.sidx=t),n},xP=({attributes:s})=>s.mimeType==="video/mp4"||s.mimeType==="video/webm"||s.contentType==="video",bP=({attributes:s})=>s.mimeType==="audio/mp4"||s.mimeType==="audio/webm"||s.contentType==="audio",TP=({attributes:s})=>s.mimeType==="text/vtt"||s.contentType==="text",_P=(s,e)=>{s.forEach(t=>{t.mediaSequence=0,t.discontinuitySequence=e.findIndex(function({timeline:i}){return i===t.timeline}),t.segments&&t.segments.forEach((i,n)=>{i.number=n})})},nE=s=>s?Object.keys(s).reduce((e,t)=>{const i=s[t];return e.concat(i.playlists)},[]):[],SP=({dashPlaylists:s,locations:e,contentSteering:t,sidxMapping:i={},previousManifest:n,eventStream:r})=>{if(!s.length)return{};const{sourceDuration:o,type:u,suggestedPresentationDelay:c,minimumUpdatePeriod:d}=s[0].attributes,f=Iy(s.filter(xP)).map(vP),p=Iy(s.filter(bP)),g=Iy(s.filter(TP)),y=s.map(B=>B.attributes.captionServices).filter(Boolean),x={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:o,playlists:hP(f,i)};d>=0&&(x.minimumUpdatePeriod=d*1e3),e&&(x.locations=e),t&&(x.contentSteering=t),u==="dynamic"&&(x.suggestedPresentationDelay=c),r&&r.length>0&&(x.eventStream=r);const _=x.playlists.length===0,w=p.length?pP(p,i,_):null,D=g.length?gP(g,i):null,I=f.concat(nE(w),nE(D)),L=I.map(({timelineStarts:B})=>B);return x.timelineStarts=NA(L),_P(I,x.timelineStarts),w&&(x.mediaGroups.AUDIO.audio=w),D&&(x.mediaGroups.SUBTITLES.subs=D),y.length&&(x.mediaGroups["CLOSED-CAPTIONS"].cc=yP(y)),n?dP({oldManifest:n,newManifest:x}):x},EP=(s,e,t)=>{const{NOW:i,clientOffset:n,availabilityStartTime:r,timescale:o=1,periodStart:u=0,minimumUpdatePeriod:c=0}=s,d=(i+n)/1e3,f=r+u,g=d+c-f;return Math.ceil((g*o-e)/t)},OA=(s,e)=>{const{type:t,minimumUpdatePeriod:i=0,media:n="",sourceDuration:r,timescale:o=1,startNumber:u=1,periodStart:c}=s,d=[];let f=-1;for(let p=0;pf&&(f=_);let w;if(x<0){const L=p+1;L===e.length?t==="dynamic"&&i>0&&n.indexOf("$Number$")>0?w=EP(s,f,y):w=(r*o-f)/y:w=(e[L].t-f)/y}else w=x+1;const D=u+d.length+w;let I=u+d.length;for(;I(e,t,i,n)=>{if(e==="$$")return"$";if(typeof s[t]>"u")return e;const r=""+s[t];return t==="RepresentationID"||(i?n=parseInt(n,10):n=1,r.length>=n)?r:`${new Array(n-r.length+1).join("0")}${r}`},rE=(s,e)=>s.replace(wP,AP(e)),CP=(s,e)=>!s.duration&&!e?[{number:s.startNumber||1,duration:s.sourceDuration,time:0,timeline:s.periodStart}]:s.duration?Gx(s):OA(s,e),kP=(s,e)=>{const t={RepresentationID:s.id,Bandwidth:s.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=s,n=dh({baseUrl:s.baseUrl,source:rE(i.sourceURL,t),range:i.range});return CP(s,e).map(o=>{t.Number=o.number,t.Time=o.time;const u=rE(s.media||"",t),c=s.timescale||1,d=s.presentationTimeOffset||0,f=s.periodStart+(o.time-d)/c;return{uri:u,timeline:o.timeline,duration:o.duration,resolvedUri:Up(s.baseUrl||"",u),map:n,number:o.number,presentationTime:f}})},DP=(s,e)=>{const{baseUrl:t,initialization:i={}}=s,n=dh({baseUrl:t,source:i.sourceURL,range:i.range}),r=dh({baseUrl:t,source:e.media,range:e.mediaRange});return r.map=n,r},LP=(s,e)=>{const{duration:t,segmentUrls:i=[],periodStart:n}=s;if(!t&&!e||t&&e)throw new Error(yc.SEGMENT_TIME_UNSPECIFIED);const r=i.map(c=>DP(s,c));let o;return t&&(o=Gx(s)),e&&(o=OA(s,e)),o.map((c,d)=>{if(r[d]){const f=r[d],p=s.timescale||1,g=s.presentationTimeOffset||0;return f.timeline=c.timeline,f.duration=c.duration,f.number=c.number,f.presentationTime=n+(c.time-g)/p,f}}).filter(c=>c)},RP=({attributes:s,segmentInfo:e})=>{let t,i;e.template?(i=kP,t=Hs(s,e.template)):e.base?(i=IA,t=Hs(s,e.base)):e.list&&(i=LP,t=Hs(s,e.list));const n={attributes:s};if(!i)return n;const r=i(t,e.segmentTimeline);if(t.duration){const{duration:o,timescale:u=1}=t;t.duration=o/u}else r.length?t.duration=r.reduce((o,u)=>Math.max(o,Math.ceil(u.duration)),0):t.duration=0;return n.attributes=t,n.segments=r,e.base&&t.indexRange&&(n.sidx=r[0],n.segments=[]),n},IP=s=>s.map(RP),ls=(s,e)=>RA(s.childNodes).filter(({tagName:t})=>t===e),Ch=s=>s.textContent.trim(),NP=s=>parseFloat(s.split("/").reduce((e,t)=>e/t)),Pu=s=>{const u=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(s);if(!u)return 0;const[c,d,f,p,g,y]=u.slice(1);return parseFloat(c||0)*31536e3+parseFloat(d||0)*2592e3+parseFloat(f||0)*86400+parseFloat(p||0)*3600+parseFloat(g||0)*60+parseFloat(y||0)},OP=s=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(s)&&(s+="Z"),Date.parse(s)),aE={mediaPresentationDuration(s){return Pu(s)},availabilityStartTime(s){return OP(s)/1e3},minimumUpdatePeriod(s){return Pu(s)},suggestedPresentationDelay(s){return Pu(s)},type(s){return s},timeShiftBufferDepth(s){return Pu(s)},start(s){return Pu(s)},width(s){return parseInt(s,10)},height(s){return parseInt(s,10)},bandwidth(s){return parseInt(s,10)},frameRate(s){return NP(s)},startNumber(s){return parseInt(s,10)},timescale(s){return parseInt(s,10)},presentationTimeOffset(s){return parseInt(s,10)},duration(s){const e=parseInt(s,10);return isNaN(e)?Pu(s):e},d(s){return parseInt(s,10)},t(s){return parseInt(s,10)},r(s){return parseInt(s,10)},presentationTime(s){return parseInt(s,10)},DEFAULT(s){return s}},Ls=s=>s&&s.attributes?RA(s.attributes).reduce((e,t)=>{const i=aE[t.name]||aE.DEFAULT;return e[t.name]=i(t.value),e},{}):{},MP={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime","urn:mpeg:dash:mp4protection:2011":"mp4protection"},Hp=(s,e)=>e.length?gc(s.map(function(t){return e.map(function(i){const n=Ch(i),r=Up(t.baseUrl,n),o=Hs(Ls(i),{baseUrl:r});return r!==n&&!o.serviceLocation&&t.serviceLocation&&(o.serviceLocation=t.serviceLocation),o})})):s,Kx=s=>{const e=ls(s,"SegmentTemplate")[0],t=ls(s,"SegmentList")[0],i=t&&ls(t,"SegmentURL").map(p=>Hs({tag:"SegmentURL"},Ls(p))),n=ls(s,"SegmentBase")[0],r=t||e,o=r&&ls(r,"SegmentTimeline")[0],u=t||n||e,c=u&&ls(u,"Initialization")[0],d=e&&Ls(e);d&&c?d.initialization=c&&Ls(c):d&&d.initialization&&(d.initialization={sourceURL:d.initialization});const f={template:d,segmentTimeline:o&&ls(o,"S").map(p=>Ls(p)),list:t&&Hs(Ls(t),{segmentUrls:i,initialization:Ls(c)}),base:n&&Hs(Ls(n),{initialization:Ls(c)})};return Object.keys(f).forEach(p=>{f[p]||delete f[p]}),f},PP=(s,e,t)=>i=>{const n=ls(i,"BaseURL"),r=Hp(e,n),o=Hs(s,Ls(i)),u=Kx(i);return r.map(c=>({segmentInfo:Hs(t,u),attributes:Hs(o,c)}))},BP=s=>s.reduce((e,t)=>{const i=Ls(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=MP[i.schemeIdUri];if(n){e[n]={attributes:i};const r=ls(t,"cenc:pssh")[0];if(r){const o=Ch(r);e[n].pssh=o&&SA(o)}}return e},{}),FP=s=>{if(s.schemeIdUri==="urn:scte:dash:cc:cea-608:2015")return(typeof s.value!="string"?[]:s.value.split(";")).map(t=>{let i,n;return n=t,/^CC\d=/.test(t)?[i,n]=t.split("="):/^CC\d$/.test(t)&&(i=t),{channel:i,language:n}});if(s.schemeIdUri==="urn:scte:dash:cc:cea-708:2015")return(typeof s.value!="string"?[]:s.value.split(";")).map(t=>{const i={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(t)){const[n,r=""]=t.split("=");i.channel=n,i.language=t,r.split(",").forEach(o=>{const[u,c]=o.split(":");u==="lang"?i.language=c:u==="er"?i.easyReader=Number(c):u==="war"?i.aspectRatio=Number(c):u==="3D"&&(i["3D"]=Number(c))})}else i.language=t;return i.channel&&(i.channel="SERVICE"+i.channel),i})},UP=s=>gc(ls(s.node,"EventStream").map(e=>{const t=Ls(e),i=t.schemeIdUri;return ls(e,"Event").map(n=>{const r=Ls(n),o=r.presentationTime||0,u=t.timescale||1,c=r.duration||0,d=o/u+s.attributes.start;return{schemeIdUri:i,value:t.value,id:r.id,start:d,end:d+c/u,messageData:Ch(n)||r.messageData,contentEncoding:t.contentEncoding,presentationTimeOffset:t.presentationTimeOffset||0}})})),jP=(s,e,t)=>i=>{const n=Ls(i),r=Hp(e,ls(i,"BaseURL")),o=ls(i,"Role")[0],u={role:Ls(o)};let c=Hs(s,n,u);const d=ls(i,"Accessibility")[0],f=FP(Ls(d));f&&(c=Hs(c,{captionServices:f}));const p=ls(i,"Label")[0];if(p&&p.childNodes.length){const w=p.childNodes[0].nodeValue.trim();c=Hs(c,{label:w})}const g=BP(ls(i,"ContentProtection"));Object.keys(g).length&&(c=Hs(c,{contentProtection:g}));const y=Kx(i),x=ls(i,"Representation"),_=Hs(t,y);return gc(x.map(PP(c,r,_)))},$P=(s,e)=>(t,i)=>{const n=Hp(e,ls(t.node,"BaseURL")),r=Hs(s,{periodStart:t.attributes.start});typeof t.attributes.duration=="number"&&(r.periodDuration=t.attributes.duration);const o=ls(t.node,"AdaptationSet"),u=Kx(t.node);return gc(o.map(jP(r,n,u)))},HP=(s,e)=>{if(s.length>1&&e({type:"warn",message:"The MPD manifest should contain no more than one ContentSteering tag"}),!s.length)return null;const t=Hs({serverURL:Ch(s[0])},Ls(s[0]));return t.queryBeforeStart=t.queryBeforeStart==="true",t},VP=({attributes:s,priorPeriodAttributes:e,mpdType:t})=>typeof s.start=="number"?s.start:e&&typeof e.start=="number"&&typeof e.duration=="number"?e.start+e.duration:!e&&t==="static"?0:null,GP=(s,e={})=>{const{manifestUri:t="",NOW:i=Date.now(),clientOffset:n=0,eventHandler:r=function(){}}=e,o=ls(s,"Period");if(!o.length)throw new Error(yc.INVALID_NUMBER_OF_PERIOD);const u=ls(s,"Location"),c=Ls(s),d=Hp([{baseUrl:t}],ls(s,"BaseURL")),f=ls(s,"ContentSteering");c.type=c.type||"static",c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=i,c.clientOffset=n,u.length&&(c.locations=u.map(Ch));const p=[];return o.forEach((g,y)=>{const x=Ls(g),_=p[y-1];x.start=VP({attributes:x,priorPeriodAttributes:_?_.attributes:null,mpdType:c.type}),p.push({node:g,attributes:x})}),{locations:c.locations,contentSteeringInfo:HP(f,r),representationInfo:gc(p.map($P(c,d))),eventStream:gc(p.map(UP))}},MA=s=>{if(s==="")throw new Error(yc.DASH_EMPTY_MANIFEST);const e=new eP.DOMParser;let t,i;try{t=e.parseFromString(s,"application/xml"),i=t&&t.documentElement.tagName==="MPD"?t.documentElement:null}catch{}if(!i||i&&i.getElementsByTagName("parsererror").length>0)throw new Error(yc.DASH_INVALID_XML);return i},zP=s=>{const e=ls(s,"UTCTiming")[0];if(!e)return null;const t=Ls(e);switch(t.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":t.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":t.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":t.method="DIRECT",t.value=Date.parse(t.value);break;default:throw new Error(yc.UNSUPPORTED_UTC_TIMING_SCHEME)}return t},qP=(s,e={})=>{const t=GP(MA(s),e),i=IP(t.representationInfo);return SP({dashPlaylists:i,locations:t.locations,contentSteering:t.contentSteeringInfo,sidxMapping:e.sidxMapping,previousManifest:e.previousManifest,eventStream:t.eventStream})},KP=s=>zP(MA(s));var Ny,oE;function YP(){if(oE)return Ny;oE=1;var s=Math.pow(2,32),e=function(t){var i=new DataView(t.buffer,t.byteOffset,t.byteLength),n;return i.getBigUint64?(n=i.getBigUint64(0),n0;r+=12,o--)n.references.push({referenceType:(t[r]&128)>>>7,referencedSize:i.getUint32(r)&2147483647,subsegmentDuration:i.getUint32(r+4),startsWithSap:!!(t[r+8]&128),sapType:(t[r+8]&112)>>>4,sapDeltaTime:i.getUint32(r+8)&268435455});return n};return Oy=e,Oy}var XP=WP();const QP=Cc(XP);var ZP=Ft([73,68,51]),JP=function(e,t){t===void 0&&(t=0),e=Ft(e);var i=e[t+5],n=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9],r=(i&16)>>4;return r?n+20:n+10},qd=function s(e,t){return t===void 0&&(t=0),e=Ft(e),e.length-t<10||!os(e,ZP,{offset:t})?t:(t+=JP(e,t),s(e,t))},uE=function(e){return typeof e=="string"?kA(e):e},e3=function(e){return Array.isArray(e)?e.map(function(t){return uE(t)}):[uE(e)]},t3=function s(e,t,i){i===void 0&&(i=!1),t=e3(t),e=Ft(e);var n=[];if(!t.length)return n;for(var r=0;r>>0,u=e.subarray(r+4,r+8);if(o===0)break;var c=r+o;if(c>e.length){if(i)break;c=e.length}var d=e.subarray(r+8,c);os(u,t[0])&&(t.length===1?n.push(d):n.push.apply(n,s(d,t.slice(1),i))),r=c}return n},lm={EBML:Ft([26,69,223,163]),DocType:Ft([66,130]),Segment:Ft([24,83,128,103]),SegmentInfo:Ft([21,73,169,102]),Tracks:Ft([22,84,174,107]),Track:Ft([174]),TrackNumber:Ft([215]),DefaultDuration:Ft([35,227,131]),TrackEntry:Ft([174]),TrackType:Ft([131]),FlagDefault:Ft([136]),CodecID:Ft([134]),CodecPrivate:Ft([99,162]),VideoTrack:Ft([224]),AudioTrack:Ft([225]),Cluster:Ft([31,67,182,117]),Timestamp:Ft([231]),TimestampScale:Ft([42,215,177]),BlockGroup:Ft([160]),BlockDuration:Ft([155]),Block:Ft([161]),SimpleBlock:Ft([163])},jv=[128,64,32,16,8,4,2,1],i3=function(e){for(var t=1,i=0;i=t.length)return t.length;var n=Xm(t,i,!1);if(os(e.bytes,n.bytes))return i;var r=Xm(t,i+n.length);return s(e,t,i+r.length+r.value+n.length)},dE=function s(e,t){t=s3(t),e=Ft(e);var i=[];if(!t.length)return i;for(var n=0;ne.length?e.length:u+o.value,d=e.subarray(u,c);os(t[0],r.bytes)&&(t.length===1?i.push(d):i=i.concat(s(d,t.slice(1))));var f=r.length+o.length+d.length;n+=f}return i},r3=Ft([0,0,0,1]),a3=Ft([0,0,1]),o3=Ft([0,0,3]),l3=function(e){for(var t=[],i=1;i>1&63),i.indexOf(d)!==-1&&(o=r+c),r+=c+(t==="h264"?1:2)}return e.subarray(0,0)},u3=function(e,t,i){return PA(e,"h264",t,i)},c3=function(e,t,i){return PA(e,"h265",t,i)},fn={webm:Ft([119,101,98,109]),matroska:Ft([109,97,116,114,111,115,107,97]),flac:Ft([102,76,97,67]),ogg:Ft([79,103,103,83]),ac3:Ft([11,119]),riff:Ft([82,73,70,70]),avi:Ft([65,86,73]),wav:Ft([87,65,86,69]),"3gp":Ft([102,116,121,112,51,103]),mp4:Ft([102,116,121,112]),fmp4:Ft([115,116,121,112]),mov:Ft([102,116,121,112,113,116]),moov:Ft([109,111,111,118]),moof:Ft([109,111,111,102])},vc={aac:function(e){var t=qd(e);return os(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=qd(e);return os(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=dE(e,[lm.EBML,lm.DocType])[0];return os(t,fn.webm)},mkv:function(e){var t=dE(e,[lm.EBML,lm.DocType])[0];return os(t,fn.matroska)},mp4:function(e){if(vc["3gp"](e)||vc.mov(e))return!1;if(os(e,fn.mp4,{offset:4})||os(e,fn.fmp4,{offset:4})||os(e,fn.moof,{offset:4})||os(e,fn.moov,{offset:4}))return!0},mov:function(e){return os(e,fn.mov,{offset:4})},"3gp":function(e){return os(e,fn["3gp"],{offset:4})},ac3:function(e){var t=qd(e);return os(e,fn.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+1880},My,hE;function f3(){if(hE)return My;hE=1;var s=9e4,e,t,i,n,r,o,u;return e=function(c){return c*s},t=function(c,d){return c*d},i=function(c){return c/s},n=function(c,d){return c/d},r=function(c,d){return e(n(c,d))},o=function(c,d){return t(i(c),d)},u=function(c,d,f){return i(f?c:c-d)},My={ONE_SECOND_IN_TS:s,secondsToVideoTs:e,secondsToAudioTs:t,videoTsToSeconds:i,audioTsToSeconds:n,audioTsToVideoTs:r,videoTsToAudioTs:o,metadataTsToSeconds:u},My}var Bl=f3();var Hv="8.23.4";const ja={},Yo=function(s,e){return ja[s]=ja[s]||[],e&&(ja[s]=ja[s].concat(e)),ja[s]},m3=function(s,e){Yo(s,e)},BA=function(s,e){const t=Yo(s).indexOf(e);return t<=-1?!1:(ja[s]=ja[s].slice(),ja[s].splice(t,1),!0)},p3=function(s,e){Yo(s,[].concat(e).map(t=>{const i=(...n)=>(BA(s,i),t(...n));return i}))},Qm={prefixed:!0},Im=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],fE=Im[0];let Kd;for(let s=0;s(i,n,r)=>{const o=e.levels[n],u=new RegExp(`^(${o})$`);let c=s;if(i!=="log"&&r.unshift(i.toUpperCase()+":"),t&&(c=`%c${s}`,r.unshift(t)),r.unshift(c+":"),In){In.push([].concat(r));const f=In.length-1e3;In.splice(0,f>0?f:0)}if(!ue.console)return;let d=ue.console[i];!d&&i==="debug"&&(d=ue.console.info||ue.console.log),!(!d||!o||!u.test(i))&&d[Array.isArray(r)?"apply":"call"](ue.console,r)};function Vv(s,e=":",t=""){let i="info",n;function r(...o){n("log",i,o)}return n=g3(s,r,t),r.createLogger=(o,u,c)=>{const d=u!==void 0?u:e,f=c!==void 0?c:t,p=`${s} ${d} ${o}`;return Vv(p,d,f)},r.createNewLogger=(o,u,c)=>Vv(o,u,c),r.levels={all:"debug|log|warn|error",off:"",debug:"debug|log|warn|error",info:"log|warn|error",warn:"warn|error",error:"error",DEFAULT:i},r.level=o=>{if(typeof o=="string"){if(!r.levels.hasOwnProperty(o))throw new Error(`"${o}" in not a valid log level`);i=o}return i},r.history=()=>In?[].concat(In):[],r.history.filter=o=>(In||[]).filter(u=>new RegExp(`.*${o}.*`).test(u[0])),r.history.clear=()=>{In&&(In.length=0)},r.history.disable=()=>{In!==null&&(In.length=0,In=null)},r.history.enable=()=>{In===null&&(In=[])},r.error=(...o)=>n("error",i,o),r.warn=(...o)=>n("warn",i,o),r.debug=(...o)=>n("debug",i,o),r}const ui=Vv("VIDEOJS"),FA=ui.createLogger,y3=Object.prototype.toString,UA=function(s){return ua(s)?Object.keys(s):[]};function ec(s,e){UA(s).forEach(t=>e(s[t],t))}function jA(s,e,t=0){return UA(s).reduce((i,n)=>e(i,s[n],n),t)}function ua(s){return!!s&&typeof s=="object"}function xc(s){return ua(s)&&y3.call(s)==="[object Object]"&&s.constructor===Object}function ji(...s){const e={};return s.forEach(t=>{t&&ec(t,(i,n)=>{if(!xc(i)){e[n]=i;return}xc(e[n])||(e[n]={}),e[n]=ji(e[n],i)})}),e}function $A(s={}){const e=[];for(const t in s)if(s.hasOwnProperty(t)){const i=s[t];e.push(i)}return e}function Vp(s,e,t,i=!0){const n=o=>Object.defineProperty(s,e,{value:o,enumerable:!0,writable:!0}),r={configurable:!0,enumerable:!0,get(){const o=t();return n(o),o}};return i&&(r.set=n),Object.defineProperty(s,e,r)}var v3=Object.freeze({__proto__:null,each:ec,reduce:jA,isObject:ua,isPlain:xc,merge:ji,values:$A,defineLazyProperty:Vp});let Wx=!1,HA=null,Dr=!1,VA,GA=!1,tc=!1,ic=!1,ca=!1,Xx=null,Gp=null;const x3=!!(ue.cast&&ue.cast.framework&&ue.cast.framework.CastReceiverContext);let zA=null,Zm=!1,zp=!1,Jm=!1,qp=!1,ep=!1,tp=!1,ip=!1;const hh=!!(kc()&&("ontouchstart"in ue||ue.navigator.maxTouchPoints||ue.DocumentTouch&&ue.document instanceof ue.DocumentTouch)),No=ue.navigator&&ue.navigator.userAgentData;No&&No.platform&&No.brands&&(Dr=No.platform==="Android",tc=!!No.brands.find(s=>s.brand==="Microsoft Edge"),ic=!!No.brands.find(s=>s.brand==="Chromium"),ca=!tc&&ic,Xx=Gp=(No.brands.find(s=>s.brand==="Chromium")||{}).version||null,zp=No.platform==="Windows");if(!ic){const s=ue.navigator&&ue.navigator.userAgent||"";Wx=/iPod/i.test(s),HA=(function(){const e=s.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null})(),Dr=/Android/i.test(s),VA=(function(){const e=s.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);return t&&i?parseFloat(e[1]+"."+e[2]):t||null})(),GA=/Firefox/i.test(s),tc=/Edg/i.test(s),ic=/Chrome/i.test(s)||/CriOS/i.test(s),ca=!tc&&ic,Xx=Gp=(function(){const e=s.match(/(Chrome|CriOS)\/(\d+)/);return e&&e[2]?parseFloat(e[2]):null})(),zA=(function(){const e=/MSIE\s(\d+)\.\d/.exec(s);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(s)&&/rv:11.0/.test(s)&&(t=11),t})(),ep=/Tizen/i.test(s),tp=/Web0S/i.test(s),ip=ep||tp,Zm=/Safari/i.test(s)&&!ca&&!Dr&&!tc&&!ip,zp=/Windows/i.test(s),Jm=/iPad/i.test(s)||Zm&&hh&&!/iPhone/i.test(s),qp=/iPhone/i.test(s)&&!Jm}const an=qp||Jm||Wx,Kp=(Zm||an)&&!ca;var qA=Object.freeze({__proto__:null,get IS_IPOD(){return Wx},get IOS_VERSION(){return HA},get IS_ANDROID(){return Dr},get ANDROID_VERSION(){return VA},get IS_FIREFOX(){return GA},get IS_EDGE(){return tc},get IS_CHROMIUM(){return ic},get IS_CHROME(){return ca},get CHROMIUM_VERSION(){return Xx},get CHROME_VERSION(){return Gp},IS_CHROMECAST_RECEIVER:x3,get IE_VERSION(){return zA},get IS_SAFARI(){return Zm},get IS_WINDOWS(){return zp},get IS_IPAD(){return Jm},get IS_IPHONE(){return qp},get IS_TIZEN(){return ep},get IS_WEBOS(){return tp},get IS_SMART_TV(){return ip},TOUCH_ENABLED:hh,IS_IOS:an,IS_ANY_SAFARI:Kp});function mE(s){return typeof s=="string"&&!!s.trim()}function b3(s){if(s.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function kc(){return st===ue.document}function Dc(s){return ua(s)&&s.nodeType===1}function KA(){try{return ue.parent!==ue.self}catch{return!0}}function YA(s){return function(e,t){if(!mE(e))return st[s](null);mE(t)&&(t=st.querySelector(t));const i=Dc(t)?t:st;return i[s]&&i[s](e)}}function $t(s="div",e={},t={},i){const n=st.createElement(s);return Object.getOwnPropertyNames(e).forEach(function(r){const o=e[r];r==="textContent"?Zo(n,o):(n[r]!==o||r==="tabIndex")&&(n[r]=o)}),Object.getOwnPropertyNames(t).forEach(function(r){n.setAttribute(r,t[r])}),i&&Qx(n,i),n}function Zo(s,e){return typeof s.textContent>"u"?s.innerText=e:s.textContent=e,s}function Gv(s,e){e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)}function th(s,e){return b3(e),s.classList.contains(e)}function jl(s,...e){return s.classList.add(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s}function Yp(s,...e){return s?(s.classList.remove(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s):(ui.warn("removeClass was called with an element that doesn't exist"),null)}function WA(s,e,t){return typeof t=="function"&&(t=t(s,e)),typeof t!="boolean"&&(t=void 0),e.split(/\s+/).forEach(i=>s.classList.toggle(i,t)),s}function XA(s,e){Object.getOwnPropertyNames(e).forEach(function(t){const i=e[t];i===null||typeof i>"u"||i===!1?s.removeAttribute(t):s.setAttribute(t,i===!0?"":i)})}function Fo(s){const e={},t=["autoplay","controls","playsinline","loop","muted","default","defaultMuted"];if(s&&s.attributes&&s.attributes.length>0){const i=s.attributes;for(let n=i.length-1;n>=0;n--){const r=i[n].name;let o=i[n].value;t.includes(r)&&(o=o!==null),e[r]=o}}return e}function QA(s,e){return s.getAttribute(e)}function bc(s,e,t){s.setAttribute(e,t)}function Wp(s,e){s.removeAttribute(e)}function ZA(){st.body.focus(),st.onselectstart=function(){return!1}}function JA(){st.onselectstart=function(){return!0}}function Tc(s){if(s&&s.getBoundingClientRect&&s.parentNode){const e=s.getBoundingClientRect(),t={};return["bottom","height","left","right","top","width"].forEach(i=>{e[i]!==void 0&&(t[i]=e[i])}),t.height||(t.height=parseFloat(_c(s,"height"))),t.width||(t.width=parseFloat(_c(s,"width"))),t}}function fh(s){if(!s||s&&!s.offsetParent)return{left:0,top:0,width:0,height:0};const e=s.offsetWidth,t=s.offsetHeight;let i=0,n=0;for(;s.offsetParent&&s!==st[Qm.fullscreenElement];)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;return{left:i,top:n,width:e,height:t}}function Xp(s,e){const t={x:0,y:0};if(an){let f=s;for(;f&&f.nodeName.toLowerCase()!=="html";){const p=_c(f,"transform");if(/^matrix/.test(p)){const g=p.slice(7,-1).split(/,\s/).map(Number);t.x+=g[4],t.y+=g[5]}else if(/^matrix3d/.test(p)){const g=p.slice(9,-1).split(/,\s/).map(Number);t.x+=g[12],t.y+=g[13]}if(f.assignedSlot&&f.assignedSlot.parentElement&&ue.WebKitCSSMatrix){const g=ue.getComputedStyle(f.assignedSlot.parentElement).transform,y=new ue.WebKitCSSMatrix(g);t.x+=y.m41,t.y+=y.m42}f=f.parentNode||f.host}}const i={},n=fh(e.target),r=fh(s),o=r.width,u=r.height;let c=e.offsetY-(r.top-n.top),d=e.offsetX-(r.left-n.left);return e.changedTouches&&(d=e.changedTouches[0].pageX-r.left,c=e.changedTouches[0].pageY+r.top,an&&(d-=t.x,c-=t.y)),i.y=1-Math.max(0,Math.min(1,c/u)),i.x=Math.max(0,Math.min(1,d/o)),i}function eC(s){return ua(s)&&s.nodeType===3}function Qp(s){for(;s.firstChild;)s.removeChild(s.firstChild);return s}function tC(s){return typeof s=="function"&&(s=s()),(Array.isArray(s)?s:[s]).map(e=>{if(typeof e=="function"&&(e=e()),Dc(e)||eC(e))return e;if(typeof e=="string"&&/\S/.test(e))return st.createTextNode(e)}).filter(e=>e)}function Qx(s,e){return tC(e).forEach(t=>s.appendChild(t)),s}function iC(s,e){return Qx(Qp(s),e)}function mh(s){return s.button===void 0&&s.buttons===void 0||s.button===0&&s.buttons===void 0||s.type==="mouseup"&&s.button===0&&s.buttons===0||s.type==="mousedown"&&s.button===0&&s.buttons===0?!0:!(s.button!==0||s.buttons!==1)}const Wo=YA("querySelector"),sC=YA("querySelectorAll");function _c(s,e){if(!s||!e)return"";if(typeof ue.getComputedStyle=="function"){let t;try{t=ue.getComputedStyle(s)}catch{return""}return t?t.getPropertyValue(e)||t[e]:""}return""}function nC(s){[...st.styleSheets].forEach(e=>{try{const t=[...e.cssRules].map(n=>n.cssText).join(""),i=st.createElement("style");i.textContent=t,s.document.head.appendChild(i)}catch{const i=st.createElement("link");i.rel="stylesheet",i.type=e.type,i.media=e.media.mediaText,i.href=e.href,s.document.head.appendChild(i)}})}var rC=Object.freeze({__proto__:null,isReal:kc,isEl:Dc,isInFrame:KA,createEl:$t,textContent:Zo,prependTo:Gv,hasClass:th,addClass:jl,removeClass:Yp,toggleClass:WA,setAttributes:XA,getAttributes:Fo,getAttribute:QA,setAttribute:bc,removeAttribute:Wp,blockTextSelection:ZA,unblockTextSelection:JA,getBoundingClientRect:Tc,findPosition:fh,getPointerPosition:Xp,isTextNode:eC,emptyEl:Qp,normalizeContent:tC,appendContent:Qx,insertContent:iC,isSingleLeftClick:mh,$:Wo,$$:sC,computedStyle:_c,copyStyleSheetsToWindow:nC});let aC=!1,zv;const T3=function(){if(zv.options.autoSetup===!1)return;const s=Array.prototype.slice.call(st.getElementsByTagName("video")),e=Array.prototype.slice.call(st.getElementsByTagName("audio")),t=Array.prototype.slice.call(st.getElementsByTagName("video-js")),i=s.concat(e,t);if(i&&i.length>0)for(let n=0,r=i.length;n-1&&(n={passive:!0}),s.addEventListener(e,i.dispatcher,n)}else s.attachEvent&&s.attachEvent("on"+e,i.dispatcher)}function on(s,e,t){if(!gn.has(s))return;const i=gn.get(s);if(!i.handlers)return;if(Array.isArray(e))return Zx(on,s,e,t);const n=function(o,u){i.handlers[u]=[],pE(o,u)};if(e===void 0){for(const o in i.handlers)Object.prototype.hasOwnProperty.call(i.handlers||{},o)&&n(s,o);return}const r=i.handlers[e];if(r){if(!t){n(s,e);return}if(t.guid)for(let o=0;o=e&&(s(...n),t=r)}},uC=function(s,e,t,i=ue){let n;const r=()=>{i.clearTimeout(n),n=null},o=function(){const u=this,c=arguments;let d=function(){n=null,d=null,t||s.apply(u,c)};!n&&t&&s.apply(u,c),i.clearTimeout(n),n=i.setTimeout(d,e)};return o.cancel=r,o};var C3=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:hr,bind_:Zi,throttle:da,debounce:uC});let Bd;class ir{on(e,t){const i=this.addEventListener;this.addEventListener=()=>{},tr(this,e,t),this.addEventListener=i}off(e,t){on(this,e,t)}one(e,t){const i=this.addEventListener;this.addEventListener=()=>{},Jp(this,e,t),this.addEventListener=i}any(e,t){const i=this.addEventListener;this.addEventListener=()=>{},Jx(this,e,t),this.addEventListener=i}trigger(e){const t=e.type||e;typeof e=="string"&&(e={type:t}),e=Zp(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),Lc(this,e)}queueTrigger(e){Bd||(Bd=new Map);const t=e.type||e;let i=Bd.get(this);i||(i=new Map,Bd.set(this,i));const n=i.get(t);i.delete(t),ue.clearTimeout(n);const r=ue.setTimeout(()=>{i.delete(t),i.size===0&&(i=null,Bd.delete(this)),this.trigger(e)},0);i.set(t,r)}}ir.prototype.allowedEvents_={};ir.prototype.addEventListener=ir.prototype.on;ir.prototype.removeEventListener=ir.prototype.off;ir.prototype.dispatchEvent=ir.prototype.trigger;const e0=s=>typeof s.name=="function"?s.name():typeof s.name=="string"?s.name:s.name_?s.name_:s.constructor&&s.constructor.name?s.constructor.name:typeof s,Va=s=>s instanceof ir||!!s.eventBusEl_&&["on","one","off","trigger"].every(e=>typeof s[e]=="function"),k3=(s,e)=>{Va(s)?e():(s.eventedCallbacks||(s.eventedCallbacks=[]),s.eventedCallbacks.push(e))},Yv=s=>typeof s=="string"&&/\S/.test(s)||Array.isArray(s)&&!!s.length,sp=(s,e,t)=>{if(!s||!s.nodeName&&!Va(s))throw new Error(`Invalid target for ${e0(e)}#${t}; must be a DOM node or evented object.`)},cC=(s,e,t)=>{if(!Yv(s))throw new Error(`Invalid event type for ${e0(e)}#${t}; must be a non-empty string or array.`)},dC=(s,e,t)=>{if(typeof s!="function")throw new Error(`Invalid listener for ${e0(e)}#${t}; must be a function.`)},Py=(s,e,t)=>{const i=e.length<3||e[0]===s||e[0]===s.eventBusEl_;let n,r,o;return i?(n=s.eventBusEl_,e.length>=3&&e.shift(),[r,o]=e):(n=e[0],r=e[1],o=e[2]),sp(n,s,t),cC(r,s,t),dC(o,s,t),o=Zi(s,o),{isTargetingSelf:i,target:n,type:r,listener:o}},kl=(s,e,t,i)=>{sp(s,s,e),s.nodeName?A3[e](s,t,i):s[e](t,i)},D3={on(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Py(this,s,"on");if(kl(t,"on",i,n),!e){const r=()=>this.off(t,i,n);r.guid=n.guid;const o=()=>this.off("dispose",r);o.guid=n.guid,kl(this,"on","dispose",r),kl(t,"on","dispose",o)}},one(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Py(this,s,"one");if(e)kl(t,"one",i,n);else{const r=(...o)=>{this.off(t,i,r),n.apply(null,o)};r.guid=n.guid,kl(t,"one",i,r)}},any(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Py(this,s,"any");if(e)kl(t,"any",i,n);else{const r=(...o)=>{this.off(t,i,r),n.apply(null,o)};r.guid=n.guid,kl(t,"any",i,r)}},off(s,e,t){if(!s||Yv(s))on(this.eventBusEl_,s,e);else{const i=s,n=e;sp(i,this,"off"),cC(n,this,"off"),dC(t,this,"off"),t=Zi(this,t),this.off("dispose",t),i.nodeName?(on(i,n,t),on(i,"dispose",t)):Va(i)&&(i.off(n,t),i.off("dispose",t))}},trigger(s,e){sp(this.eventBusEl_,this,"trigger");const t=s&&typeof s!="string"?s.type:s;if(!Yv(t))throw new Error(`Invalid event type for ${e0(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return Lc(this.eventBusEl_,s,e)}};function eb(s,e={}){const{eventBusKey:t}=e;if(t){if(!s[t].nodeName)throw new Error(`The eventBusKey "${t}" does not refer to an element.`);s.eventBusEl_=s[t]}else s.eventBusEl_=$t("span",{className:"vjs-event-bus"});return Object.assign(s,D3),s.eventedCallbacks&&s.eventedCallbacks.forEach(i=>{i()}),s.on("dispose",()=>{s.off(),[s,s.el_,s.eventBusEl_].forEach(function(i){i&&gn.has(i)&&gn.delete(i)}),ue.setTimeout(()=>{s.eventBusEl_=null},0)}),s}const L3={state:{},setState(s){typeof s=="function"&&(s=s());let e;return ec(s,(t,i)=>{this.state[i]!==t&&(e=e||{},e[i]={from:this.state[i],to:t}),this.state[i]=t}),e&&Va(this)&&this.trigger({changes:e,type:"statechanged"}),e}};function hC(s,e){return Object.assign(s,L3),s.state=Object.assign({},s.state,e),typeof s.handleStateChanged=="function"&&Va(s)&&s.on("statechanged",s.handleStateChanged),s}const ih=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toLowerCase())},xs=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toUpperCase())},fC=function(s,e){return xs(s)===xs(e)};var R3=Object.freeze({__proto__:null,toLowerCase:ih,toTitleCase:xs,titleCaseEquals:fC});class Ue{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=ji({},this.options_),t=this.options_=ji(this.options_,t),this.id_=t.id||t.el&&t.el.id,!this.id_){const n=e&&e.id&&e.id()||"no_player";this.id_=`${n}_component_${dr()}`}this.name_=t.name||null,t.el?this.el_=t.el:t.createEl!==!1&&(this.el_=this.createEl()),t.className&&this.el_&&t.className.split(" ").forEach(n=>this.addClass(n)),["on","off","one","any","trigger"].forEach(n=>{this[n]=void 0}),t.evented!==!1&&(eb(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),hC(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Set,this.setIntervalIds_=new Set,this.rafIds_=new Set,this.namedRafs_=new Map,this.clearingTimersOnDispose_=!1,t.initChildren!==!1&&this.initChildren(),this.ready(i),t.reportTouchActivity!==!1&&this.enableTouchActivity()}dispose(e={}){if(!this.isDisposed_){if(this.readyQueue_&&(this.readyQueue_.length=0),this.trigger({type:"dispose",bubbles:!1}),this.isDisposed_=!0,this.children_)for(let t=this.children_.length-1;t>=0;t--)this.children_[t].dispose&&this.children_[t].dispose();this.children_=null,this.childIndex_=null,this.childNameIndex_=null,this.parentComponent_=null,this.el_&&(this.el_.parentNode&&(e.restoreEl?this.el_.parentNode.replaceChild(e.restoreEl,this.el_):this.el_.parentNode.removeChild(this.el_)),this.el_=null),this.player_=null}}isDisposed(){return!!this.isDisposed_}player(){return this.player_}options(e){return e?(this.options_=ji(this.options_,e),this.options_):this.options_}el(){return this.el_}createEl(e,t,i){return $t(e,t,i)}localize(e,t,i=e){const n=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),o=r&&r[n],u=n&&n.split("-")[0],c=r&&r[u];let d=i;return o&&o[e]?d=o[e]:c&&c[e]&&(d=c[e]),t&&(d=d.replace(/\{(\d+)\}/g,function(f,p){const g=t[p-1];let y=g;return typeof g>"u"&&(y=f),y})),d}handleLanguagechange(){}contentEl(){return this.contentEl_||this.el_}id(){return this.id_}name(){return this.name_}children(){return this.children_}getChildById(e){return this.childIndex_[e]}getChild(e){if(e)return this.childNameIndex_[e]}getDescendant(...e){e=e.reduce((i,n)=>i.concat(n),[]);let t=this;for(let i=0;i=0;n--)if(this.children_[n]===e){t=!0,this.children_.splice(n,1);break}if(!t)return;e.parentComponent_=null,this.childIndex_[e.id()]=null,this.childNameIndex_[xs(e.name())]=null,this.childNameIndex_[ih(e.name())]=null;const i=e.el();i&&i.parentNode===this.contentEl()&&this.contentEl().removeChild(e.el())}initChildren(){const e=this.options_.children;if(e){const t=this.options_,i=o=>{const u=o.name;let c=o.opts;if(t[u]!==void 0&&(c=t[u]),c===!1)return;c===!0&&(c={}),c.playerOptions=this.options_.playerOptions;const d=this.addChild(u,c);d&&(this[u]=d)};let n;const r=Ue.getComponent("Tech");Array.isArray(e)?n=e:n=Object.keys(e),n.concat(Object.keys(this.options_).filter(function(o){return!n.some(function(u){return typeof u=="string"?o===u:o===u.name})})).map(o=>{let u,c;return typeof o=="string"?(u=o,c=e[u]||this.options_[u]||{}):(u=o.name,c=o),{name:u,opts:c}}).filter(o=>{const u=Ue.getComponent(o.opts.componentClass||xs(o.name));return u&&!r.isTech(u)}).forEach(i)}}buildCSSClass(){return""}ready(e,t=!1){if(e){if(!this.isReady_){this.readyQueue_=this.readyQueue_||[],this.readyQueue_.push(e);return}t?e.call(this):this.setTimeout(e,1)}}triggerReady(){this.isReady_=!0,this.setTimeout(function(){const e=this.readyQueue_;this.readyQueue_=[],e&&e.length>0&&e.forEach(function(t){t.call(this)},this),this.trigger("ready")},1)}$(e,t){return Wo(e,t||this.contentEl())}$$(e,t){return sC(e,t||this.contentEl())}hasClass(e){return th(this.el_,e)}addClass(...e){jl(this.el_,...e)}removeClass(...e){Yp(this.el_,...e)}toggleClass(e,t){WA(this.el_,e,t)}show(){this.removeClass("vjs-hidden")}hide(){this.addClass("vjs-hidden")}lockShowing(){this.addClass("vjs-lock-showing")}unlockShowing(){this.removeClass("vjs-lock-showing")}getAttribute(e){return QA(this.el_,e)}setAttribute(e,t){bc(this.el_,e,t)}removeAttribute(e){Wp(this.el_,e)}width(e,t){return this.dimension("width",e,t)}height(e,t){return this.dimension("height",e,t)}dimensions(e,t){this.width(e,!0),this.height(t)}dimension(e,t,i){if(t!==void 0){(t===null||t!==t)&&(t=0),(""+t).indexOf("%")!==-1||(""+t).indexOf("px")!==-1?this.el_.style[e]=t:t==="auto"?this.el_.style[e]="":this.el_.style[e]=t+"px",i||this.trigger("componentresize");return}if(!this.el_)return 0;const n=this.el_.style[e],r=n.indexOf("px");return parseInt(r!==-1?n.slice(0,r):this.el_["offset"+xs(e)],10)}currentDimension(e){let t=0;if(e!=="width"&&e!=="height")throw new Error("currentDimension only accepts width or height value");if(t=_c(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){const i=`offset${xs(e)}`;t=this.el_[i]}return t}currentDimensions(){return{width:this.currentDimension("width"),height:this.currentDimension("height")}}currentWidth(){return this.currentDimension("width")}currentHeight(){return this.currentDimension("height")}getPositions(){const e=this.el_.getBoundingClientRect(),t={x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left},i={x:e.left+e.width/2,y:e.top+e.height/2,width:0,height:0,top:e.top+e.height/2,right:e.left+e.width/2,bottom:e.top+e.height/2,left:e.left+e.width/2};return{boundingClientRect:t,center:i}}focus(){this.el_.focus()}blur(){this.el_.blur()}handleKeyDown(e){this.player_&&(e.key!=="Tab"&&!(this.player_.options_.playerOptions.spatialNavigation&&this.player_.options_.playerOptions.spatialNavigation.enabled)&&e.stopPropagation(),this.player_.handleKeyDown(e))}handleKeyPress(e){this.handleKeyDown(e)}emitTapEvents(){let e=0,t=null;const i=10,n=200;let r;this.on("touchstart",function(u){u.touches.length===1&&(t={pageX:u.touches[0].pageX,pageY:u.touches[0].pageY},e=ue.performance.now(),r=!0)}),this.on("touchmove",function(u){if(u.touches.length>1)r=!1;else if(t){const c=u.touches[0].pageX-t.pageX,d=u.touches[0].pageY-t.pageY;Math.sqrt(c*c+d*d)>i&&(r=!1)}});const o=function(){r=!1};this.on("touchleave",o),this.on("touchcancel",o),this.on("touchend",function(u){t=null,r===!0&&ue.performance.now()-e{this.setTimeoutIds_.has(i)&&this.setTimeoutIds_.delete(i),e()},t),this.setTimeoutIds_.add(i),i}clearTimeout(e){return this.setTimeoutIds_.has(e)&&(this.setTimeoutIds_.delete(e),ue.clearTimeout(e)),e}setInterval(e,t){e=Zi(this,e),this.clearTimersOnDispose_();const i=ue.setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),ue.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=Zi(this,e),t=ue.requestAnimationFrame(()=>{this.rafIds_.has(t)&&this.rafIds_.delete(t),e()}),this.rafIds_.add(t),t}requestNamedAnimationFrame(e,t){this.namedRafs_.has(e)&&this.cancelNamedAnimationFrame(e),this.clearTimersOnDispose_(),t=Zi(this,t);const i=this.requestAnimationFrame(()=>{t(),this.namedRafs_.has(e)&&this.namedRafs_.delete(e)});return this.namedRafs_.set(e,i),e}cancelNamedAnimationFrame(e){this.namedRafs_.has(e)&&(this.cancelAnimationFrame(this.namedRafs_.get(e)),this.namedRafs_.delete(e))}cancelAnimationFrame(e){return this.rafIds_.has(e)&&(this.rafIds_.delete(e),ue.cancelAnimationFrame(e)),e}clearTimersOnDispose_(){this.clearingTimersOnDispose_||(this.clearingTimersOnDispose_=!0,this.one("dispose",()=>{[["namedRafs_","cancelNamedAnimationFrame"],["rafIds_","cancelAnimationFrame"],["setTimeoutIds_","clearTimeout"],["setIntervalIds_","clearInterval"]].forEach(([e,t])=>{this[e].forEach((i,n)=>this[t](n))}),this.clearingTimersOnDispose_=!1}))}getIsDisabled(){return!!this.el_.disabled}getIsExpresslyInert(){return this.el_.inert&&!this.el_.ownerDocument.documentElement.inert}getIsFocusable(e){return(e||this.el_).tabIndex>=0&&!(this.getIsDisabled()||this.getIsExpresslyInert())}getIsAvailableToBeFocused(e){function t(r){const o=ue.getComputedStyle(r,null),u=o.getPropertyValue("visibility");return o.getPropertyValue("display")!=="none"&&!["hidden","collapse"].includes(u)}function i(r){return!(!t(r.parentElement)||!t(r)||r.style.opacity==="0"||ue.getComputedStyle(r).height==="0px"||ue.getComputedStyle(r).width==="0px")}function n(r){if(r.offsetWidth+r.offsetHeight+r.getBoundingClientRect().height+r.getBoundingClientRect().width===0)return!1;const o={x:r.getBoundingClientRect().left+r.offsetWidth/2,y:r.getBoundingClientRect().top+r.offsetHeight/2};if(o.x<0||o.x>(st.documentElement.clientWidth||ue.innerWidth)||o.y<0||o.y>(st.documentElement.clientHeight||ue.innerHeight))return!1;let u=st.elementFromPoint(o.x,o.y);for(;u;){if(u===r)return!0;if(u.parentNode)u=u.parentNode;else return!1}}return e||(e=this.el()),!!(n(e)&&i(e)&&(!e.parentElement||e.tabIndex>=0))}static registerComponent(e,t){if(typeof e!="string"||!e)throw new Error(`Illegal component name, "${e}"; must be a non-empty string.`);const i=Ue.getComponent("Tech"),n=i&&i.isTech(t),r=Ue===t||Ue.prototype.isPrototypeOf(t.prototype);if(n||!r){let u;throw n?u="techs must be registered using Tech.registerTech()":u="must be a Component subclass",new Error(`Illegal component, "${e}"; ${u}.`)}e=xs(e),Ue.components_||(Ue.components_={});const o=Ue.getComponent("Player");if(e==="Player"&&o&&o.players){const u=o.players,c=Object.keys(u);if(u&&c.length>0){for(let d=0;dt)throw new Error(`Failed to execute '${s}' on 'TimeRanges': The index provided (${e}) is non-numeric or out of bounds (0-${t}).`)}function gE(s,e,t,i){return I3(s,i,t.length-1),t[i][e]}function By(s){let e;return s===void 0||s.length===0?e={length:0,start(){throw new Error("This TimeRanges object is empty")},end(){throw new Error("This TimeRanges object is empty")}}:e={length:s.length,start:gE.bind(null,"start",0,s),end:gE.bind(null,"end",1,s)},ue.Symbol&&ue.Symbol.iterator&&(e[ue.Symbol.iterator]=()=>(s||[]).values()),e}function kr(s,e){return Array.isArray(s)?By(s):s===void 0||e===void 0?By():By([[s,e]])}const mC=function(s,e){s=s<0?0:s;let t=Math.floor(s%60),i=Math.floor(s/60%60),n=Math.floor(s/3600);const r=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(s)||s===1/0)&&(n=i=t="-"),n=n>0||o>0?n+":":"",i=((n||r>=10)&&i<10?"0"+i:i)+":",t=t<10?"0"+t:t,n+i+t};let tb=mC;function pC(s){tb=s}function gC(){tb=mC}function ql(s,e=s){return tb(s,e)}var N3=Object.freeze({__proto__:null,createTimeRanges:kr,createTimeRange:kr,setFormatTime:pC,resetFormatTime:gC,formatTime:ql});function yC(s,e){let t=0,i,n;if(!e)return 0;(!s||!s.length)&&(s=kr(0,0));for(let r=0;re&&(n=e),t+=n-i;return t/e}function fs(s){if(s instanceof fs)return s;typeof s=="number"?this.code=s:typeof s=="string"?this.message=s:ua(s)&&(typeof s.code=="number"&&(this.code=s.code),Object.assign(this,s)),this.message||(this.message=fs.defaultMessages[this.code]||"")}fs.prototype.code=0;fs.prototype.message="";fs.prototype.status=null;fs.prototype.metadata=null;fs.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"];fs.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail part-way.",3:"The media playback was aborted due to a corruption problem or because the media used features your browser did not support.",4:"The media could not be loaded, either because the server or network failed or because the format is not supported.",5:"The media is encrypted and we do not have the keys to decrypt it."};fs.MEDIA_ERR_CUSTOM=0;fs.prototype.MEDIA_ERR_CUSTOM=0;fs.MEDIA_ERR_ABORTED=1;fs.prototype.MEDIA_ERR_ABORTED=1;fs.MEDIA_ERR_NETWORK=2;fs.prototype.MEDIA_ERR_NETWORK=2;fs.MEDIA_ERR_DECODE=3;fs.prototype.MEDIA_ERR_DECODE=3;fs.MEDIA_ERR_SRC_NOT_SUPPORTED=4;fs.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4;fs.MEDIA_ERR_ENCRYPTED=5;fs.prototype.MEDIA_ERR_ENCRYPTED=5;function sh(s){return s!=null&&typeof s.then=="function"}function ta(s){sh(s)&&s.then(null,e=>{})}const Wv=function(s){return["kind","label","language","id","inBandMetadataTrackDispatchType","mode","src"].reduce((t,i,n)=>(s[i]&&(t[i]=s[i]),t),{cues:s.cues&&Array.prototype.map.call(s.cues,function(t){return{startTime:t.startTime,endTime:t.endTime,text:t.text,id:t.id}})})},O3=function(s){const e=s.$$("track"),t=Array.prototype.map.call(e,n=>n.track);return Array.prototype.map.call(e,function(n){const r=Wv(n.track);return n.src&&(r.src=n.src),r}).concat(Array.prototype.filter.call(s.textTracks(),function(n){return t.indexOf(n)===-1}).map(Wv))},M3=function(s,e){return s.forEach(function(t){const i=e.addRemoteTextTrack(t).track;!t.src&&t.cues&&t.cues.forEach(n=>i.addCue(n))}),e.textTracks()};var Xv={textTracksToJson:O3,jsonToTextTracks:M3,trackToJson:Wv};const Fy="vjs-modal-dialog";class Rc extends Ue{constructor(e,t){super(e,t),this.handleKeyDown_=i=>this.handleKeyDown(i),this.close_=i=>this.close(i),this.opened_=this.hasBeenOpened_=this.hasBeenFilled_=!1,this.closeable(!this.options_.uncloseable),this.content(this.options_.content),this.contentEl_=$t("div",{className:`${Fy}-content`},{role:"document"}),this.descEl_=$t("p",{className:`${Fy}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),Zo(this.descEl_,this.description()),this.el_.appendChild(this.descEl_),this.el_.appendChild(this.contentEl_)}createEl(){return super.createEl("div",{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":`${this.id()}_description`,"aria-hidden":"true","aria-label":this.label(),role:"dialog","aria-live":"polite"})}dispose(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,super.dispose()}buildCSSClass(){return`${Fy} vjs-hidden ${super.buildCSSClass()}`}label(){return this.localize(this.options_.label||"Modal Window")}description(){let e=this.options_.description||this.localize("This is a modal window.");return this.closeable()&&(e+=" "+this.localize("This modal can be closed by pressing the Escape key or activating the close button.")),e}open(){if(this.opened_){this.options_.fillAlways&&this.fill();return}const e=this.player();this.trigger("beforemodalopen"),this.opened_=!0,(this.options_.fillAlways||!this.hasBeenOpened_&&!this.hasBeenFilled_)&&this.fill(),this.wasPlaying_=!e.paused(),this.options_.pauseOnOpen&&this.wasPlaying_&&e.pause(),this.on("keydown",this.handleKeyDown_),this.hadControls_=e.controls(),e.controls(!1),this.show(),this.conditionalFocus_(),this.el().setAttribute("aria-hidden","false"),this.trigger("modalopen"),this.hasBeenOpened_=!0}opened(e){return typeof e=="boolean"&&this[e?"open":"close"](),this.opened_}close(){if(!this.opened_)return;const e=this.player();this.trigger("beforemodalclose"),this.opened_=!1,this.wasPlaying_&&this.options_.pauseOnOpen&&e.play(),this.off("keydown",this.handleKeyDown_),this.hadControls_&&e.controls(!0),this.hide(),this.el().setAttribute("aria-hidden","true"),this.trigger({type:"modalclose",bubbles:!0}),this.conditionalBlur_(),this.options_.temporary&&this.dispose()}closeable(e){if(typeof e=="boolean"){const t=this.closeable_=!!e;let i=this.getChild("closeButton");if(t&&!i){const n=this.contentEl_;this.contentEl_=this.el_,i=this.addChild("closeButton",{controlText:"Close Modal Dialog"}),this.contentEl_=n,this.on(i,"close",this.close_)}!t&&i&&(this.off(i,"close",this.close_),this.removeChild(i),i.dispose())}return this.closeable_}fill(){this.fillWith(this.content())}fillWith(e){const t=this.contentEl(),i=t.parentNode,n=t.nextSibling;this.trigger("beforemodalfill"),this.hasBeenFilled_=!0,i.removeChild(t),this.empty(),iC(t,e),this.trigger("modalfill"),n?i.insertBefore(t,n):i.appendChild(t);const r=this.getChild("closeButton");r&&i.appendChild(r.el_),this.trigger("aftermodalfill")}empty(){this.trigger("beforemodalempty"),Qp(this.contentEl()),this.trigger("modalempty")}content(e){return typeof e<"u"&&(this.content_=e),this.content_}conditionalFocus_(){const e=st.activeElement,t=this.player_.el_;this.previouslyActiveEl_=null,(t.contains(e)||t===e)&&(this.previouslyActiveEl_=e,this.focus())}conditionalBlur_(){this.previouslyActiveEl_&&(this.previouslyActiveEl_.focus(),this.previouslyActiveEl_=null)}handleKeyDown(e){if(this.trigger({type:"modalKeydown",originalEvent:e,target:this,bubbles:!0}),e.stopPropagation(),e.key==="Escape"&&this.closeable()){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;const t=this.focusableEls_(),i=this.el_.querySelector(":focus");let n;for(let r=0;r(t instanceof ue.HTMLAnchorElement||t instanceof ue.HTMLAreaElement)&&t.hasAttribute("href")||(t instanceof ue.HTMLInputElement||t instanceof ue.HTMLSelectElement||t instanceof ue.HTMLTextAreaElement||t instanceof ue.HTMLButtonElement)&&!t.hasAttribute("disabled")||t instanceof ue.HTMLIFrameElement||t instanceof ue.HTMLObjectElement||t instanceof ue.HTMLEmbedElement||t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!==-1||t.hasAttribute("contenteditable"))}}Rc.prototype.options_={pauseOnOpen:!0,temporary:!0};Ue.registerComponent("ModalDialog",Rc);class Kl extends ir{constructor(e=[]){super(),this.tracks_=[],Object.defineProperty(this,"length",{get(){return this.tracks_.length}});for(let t=0;t{this.trigger({track:e,type:"labelchange",target:this})},Va(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,n=this.length;i=0;t--)if(e[t].enabled){Uy(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&Uy(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,Uy(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("enabledchange",e.enabledChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.enabledChange_&&(e.removeEventListener("enabledchange",e.enabledChange_),e.enabledChange_=null)}}const jy=function(s,e){for(let t=0;t=0;t--)if(e[t].selected){jy(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let t=0;t{this.changing_||(this.changing_=!0,jy(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("selectedchange",e.selectedChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.selectedChange_&&(e.removeEventListener("selectedchange",e.selectedChange_),e.selectedChange_=null)}}class ib extends Kl{addTrack(e){super.addTrack(e),this.queueChange_||(this.queueChange_=()=>this.queueTrigger("change")),this.triggerSelectedlanguagechange||(this.triggerSelectedlanguagechange_=()=>this.trigger("selectedlanguagechange")),e.addEventListener("modechange",this.queueChange_),["metadata","chapters"].indexOf(e.kind)===-1&&e.addEventListener("modechange",this.triggerSelectedlanguagechange_)}removeTrack(e){super.removeTrack(e),e.removeEventListener&&(this.queueChange_&&e.removeEventListener("modechange",this.queueChange_),this.selectedlanguagechange_&&e.removeEventListener("modechange",this.triggerSelectedlanguagechange_))}toJSON(){return this.tracks_.map(e=>e.toJSON())}}class P3{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;t0&&(ue.console&&ue.console.groupCollapsed&&ue.console.groupCollapsed(`Text Track parsing errors for ${e.src}`),i.forEach(n=>ui.error(n)),ue.console&&ue.console.groupEnd&&ue.console.groupEnd()),t.flush()},xE=function(s,e){const t={uri:s},i=t0(s);i&&(t.cors=i);const n=e.tech_.crossOrigin()==="use-credentials";n&&(t.withCredentials=n),_A(t,Zi(this,function(r,o,u){if(r)return ui.error(r,o);e.loaded_=!0,typeof ue.WebVTT!="function"?e.tech_&&e.tech_.any(["vttjsloaded","vttjserror"],c=>{if(c.type==="vttjserror"){ui.error(`vttjs failed to load, stopping trying to process ${e.src}`);return}return vE(u,e)}):vE(u,e)}))};class kh extends sb{constructor(e={}){if(!e.tech)throw new Error("A tech was not provided.");const t=ji(e,{kind:U3[e.kind]||"subtitles",language:e.language||e.srclang||""});let i=yE[t.mode]||"disabled";const n=t.default;(t.kind==="metadata"||t.kind==="chapters")&&(i="hidden"),super(t),this.tech_=t.tech,this.cues_=[],this.activeCues_=[],this.preload_=this.tech_.preloadTextTracks!==!1;const r=new np(this.cues_),o=new np(this.activeCues_);let u=!1;this.timeupdateHandler=Zi(this,function(d={}){if(!this.tech_.isDisposed()){if(!this.tech_.isReady_){d.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler));return}this.activeCues=this.activeCues,u&&(this.trigger("cuechange"),u=!1),d.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))}});const c=()=>{this.stopTracking()};this.tech_.one("dispose",c),i!=="disabled"&&this.startTracking(),Object.defineProperties(this,{default:{get(){return n},set(){}},mode:{get(){return i},set(d){yE[d]&&i!==d&&(i=d,!this.preload_&&i!=="disabled"&&this.cues.length===0&&xE(this.src,this),this.stopTracking(),i!=="disabled"&&this.startTracking(),this.trigger("modechange"))}},cues:{get(){return this.loaded_?r:null},set(){}},activeCues:{get(){if(!this.loaded_)return null;if(this.cues.length===0)return o;const d=this.tech_.currentTime(),f=[];for(let p=0,g=this.cues.length;p=d&&f.push(y)}if(u=!1,f.length!==this.activeCues_.length)u=!0;else for(let p=0;p{t=qa.LOADED,this.trigger({type:"load",target:this})})}}qa.prototype.allowedEvents_={load:"load"};qa.NONE=0;qa.LOADING=1;qa.LOADED=2;qa.ERROR=3;const cr={audio:{ListClass:vC,TrackClass:TC,capitalName:"Audio"},video:{ListClass:xC,TrackClass:_C,capitalName:"Video"},text:{ListClass:ib,TrackClass:kh,capitalName:"Text"}};Object.keys(cr).forEach(function(s){cr[s].getterName=`${s}Tracks`,cr[s].privateName=`${s}Tracks_`});const Sc={remoteText:{ListClass:ib,TrackClass:kh,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:P3,TrackClass:qa,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},pn=Object.assign({},cr,Sc);Sc.names=Object.keys(Sc);cr.names=Object.keys(cr);pn.names=[].concat(Sc.names).concat(cr.names);function $3(s,e,t,i,n={}){const r=s.textTracks();n.kind=e,t&&(n.label=t),i&&(n.language=i),n.tech=s;const o=new pn.text.TrackClass(n);return r.addTrack(o),o}class ii extends Ue{constructor(e={},t=function(){}){e.reportTouchActivity=!1,super(null,e,t),this.onDurationChange_=i=>this.onDurationChange(i),this.trackProgress_=i=>this.trackProgress(i),this.trackCurrentTime_=i=>this.trackCurrentTime(i),this.stopTrackingCurrentTime_=i=>this.stopTrackingCurrentTime(i),this.disposeSourceHandler_=i=>this.disposeSourceHandler(i),this.queuedHanders_=new Set,this.hasStarted_=!1,this.on("playing",function(){this.hasStarted_=!0}),this.on("loadstart",function(){this.hasStarted_=!1}),pn.names.forEach(i=>{const n=pn[i];e&&e[n.getterName]&&(this[n.privateName]=e[n.getterName])}),this.featuresProgressEvents||this.manualProgressOn(),this.featuresTimeupdateEvents||this.manualTimeUpdatesOn(),["Text","Audio","Video"].forEach(i=>{e[`native${i}Tracks`]===!1&&(this[`featuresNative${i}Tracks`]=!1)}),e.nativeCaptions===!1||e.nativeTextTracks===!1?this.featuresNativeTextTracks=!1:(e.nativeCaptions===!0||e.nativeTextTracks===!0)&&(this.featuresNativeTextTracks=!0),this.featuresNativeTextTracks||this.emulateTextTracks(),this.preloadTextTracks=e.preloadTextTracks!==!1,this.autoRemoteTextTracks_=new pn.text.ListClass,this.initTrackListeners(),e.nativeControlsForTouch||this.emitTapEvents(),this.constructor&&(this.name_=this.constructor.name||"Unknown Tech")}triggerSourceset(e){this.isReady_||this.one("ready",()=>this.setTimeout(()=>this.triggerSourceset(e),1)),this.trigger({src:e,type:"sourceset"})}manualProgressOn(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)}manualProgressOff(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)}trackProgress(e){this.stopTrackingProgress(),this.progressInterval=this.setInterval(Zi(this,function(){const t=this.bufferedPercent();this.bufferedPercent_!==t&&this.trigger("progress"),this.bufferedPercent_=t,t===1&&this.stopTrackingProgress()}),500)}onDurationChange(e){this.duration_=this.duration()}buffered(){return kr(0,0)}bufferedPercent(){return yC(this.buffered(),this.duration_)}stopTrackingProgress(){this.clearInterval(this.progressInterval)}manualTimeUpdatesOn(){this.manualTimeUpdates=!0,this.on("play",this.trackCurrentTime_),this.on("pause",this.stopTrackingCurrentTime_)}manualTimeUpdatesOff(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off("play",this.trackCurrentTime_),this.off("pause",this.stopTrackingCurrentTime_)}trackCurrentTime(){this.currentTimeInterval&&this.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval(function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},250)}stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval),this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}dispose(){this.clearTracks(cr.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),super.dispose()}clearTracks(e){e=[].concat(e),e.forEach(t=>{const i=this[`${t}Tracks`]()||[];let n=i.length;for(;n--;){const r=i[n];t==="text"&&this.removeRemoteTextTrack(r),i.removeTrack(r)}})}cleanupAutoTextTracks(){const e=this.autoRemoteTextTracks_||[];let t=e.length;for(;t--;){const i=e[t];this.removeRemoteTextTrack(i)}}reset(){}crossOrigin(){}setCrossOrigin(){}error(e){return e!==void 0&&(this.error_=new fs(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?kr(0,0):kr()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){cr.names.forEach(e=>{const t=cr[e],i=()=>{this.trigger(`${e}trackchange`)},n=this[t.getterName]();n.addEventListener("removetrack",i),n.addEventListener("addtrack",i),this.on("dispose",()=>{n.removeEventListener("removetrack",i),n.removeEventListener("addtrack",i)})})}addWebVttScript_(){if(!ue.WebVTT)if(st.body.contains(this.el())){if(!this.options_["vtt.js"]&&xc(VS)&&Object.keys(VS).length>0){this.trigger("vttjsloaded");return}const e=st.createElement("script");e.src=this.options_["vtt.js"]||"https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js",e.onload=()=>{this.trigger("vttjsloaded")},e.onerror=()=>{this.trigger("vttjserror")},this.on("dispose",()=>{e.onload=null,e.onerror=null}),ue.WebVTT=!0,this.el().parentNode.appendChild(e)}else this.ready(this.addWebVttScript_)}emulateTextTracks(){const e=this.textTracks(),t=this.remoteTextTracks(),i=u=>e.addTrack(u.track),n=u=>e.removeTrack(u.track);t.on("addtrack",i),t.on("removetrack",n),this.addWebVttScript_();const r=()=>this.trigger("texttrackchange"),o=()=>{r();for(let u=0;uthis.autoRemoteTextTracks_.addTrack(i.track)),i}removeRemoteTextTrack(e){const t=this.remoteTextTrackEls().getTrackElementByTrack_(e);this.remoteTextTrackEls().removeTrackElement_(t),this.remoteTextTracks().removeTrack(e),this.autoRemoteTextTracks_.removeTrack(e)}getVideoPlaybackQuality(){return{}}requestPictureInPicture(){return Promise.reject()}disablePictureInPicture(){return!0}setDisablePictureInPicture(){}requestVideoFrameCallback(e){const t=dr();return!this.isReady_||this.paused()?(this.queuedHanders_.add(t),this.one("playing",()=>{this.queuedHanders_.has(t)&&(this.queuedHanders_.delete(t),e())})):this.requestNamedAnimationFrame(t,e),t}cancelVideoFrameCallback(e){this.queuedHanders_.has(e)?this.queuedHanders_.delete(e):this.cancelNamedAnimationFrame(e)}setPoster(){}playsinline(){}setPlaysinline(){}overrideNativeAudioTracks(e){}overrideNativeVideoTracks(e){}canPlayType(e){return""}static canPlayType(e){return""}static canPlaySource(e,t){return ii.canPlayType(e.type)}static isTech(e){return e.prototype instanceof ii||e instanceof ii||e===ii}static registerTech(e,t){if(ii.techs_||(ii.techs_={}),!ii.isTech(t))throw new Error(`Tech ${e} must be a Tech`);if(!ii.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!ii.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return e=xs(e),ii.techs_[e]=t,ii.techs_[ih(e)]=t,e!=="Tech"&&ii.defaultTechOrder_.push(e),t}static getTech(e){if(e){if(ii.techs_&&ii.techs_[e])return ii.techs_[e];if(e=xs(e),ue&&ue.videojs&&ue.videojs[e])return ui.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),ue.videojs[e]}}}pn.names.forEach(function(s){const e=pn[s];ii.prototype[e.getterName]=function(){return this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName]}});ii.prototype.featuresVolumeControl=!0;ii.prototype.featuresMuteControl=!0;ii.prototype.featuresFullscreenResize=!1;ii.prototype.featuresPlaybackRate=!1;ii.prototype.featuresProgressEvents=!1;ii.prototype.featuresSourceset=!1;ii.prototype.featuresTimeupdateEvents=!1;ii.prototype.featuresNativeTextTracks=!1;ii.prototype.featuresVideoFrameCallback=!1;ii.withSourceHandlers=function(s){s.registerSourceHandler=function(t,i){let n=s.sourceHandlers;n||(n=s.sourceHandlers=[]),i===void 0&&(i=n.length),n.splice(i,0,t)},s.canPlayType=function(t){const i=s.sourceHandlers||[];let n;for(let r=0;rIl(e,$l[e.type],t,s),1)}function G3(s,e){s.forEach(t=>t.setTech&&t.setTech(e))}function z3(s,e,t){return s.reduceRight(ab(t),e[t]())}function q3(s,e,t,i){return e[t](s.reduce(ab(t),i))}function bE(s,e,t,i=null){const n="call"+xs(t),r=s.reduce(ab(n),i),o=r===ap,u=o?null:e[t](r);return W3(s,t,u,o),u}const K3={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},Y3={setCurrentTime:1,setMuted:1,setVolume:1},TE={play:1,pause:1};function ab(s){return(e,t)=>e===ap?ap:t[s]?t[s](e):e}function W3(s,e,t,i){for(let n=s.length-1;n>=0;n--){const r=s[n];r[e]&&r[e](i,t)}}function X3(s){rp.hasOwnProperty(s.id())&&delete rp[s.id()]}function Q3(s,e){const t=rp[s.id()];let i=null;if(t==null)return i=e(s),rp[s.id()]=[[e,i]],i;for(let n=0;n{if(!e)return"";if(s.cache_.source.src===e&&s.cache_.source.type)return s.cache_.source.type;const t=s.cache_.sources.filter(n=>n.src===e);if(t.length)return t[0].type;const i=s.$$("source");for(let n=0;n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`;const SE=ep?10009:tp?461:8,Bu={codes:{play:415,pause:19,ff:417,rw:412,back:SE},names:{415:"play",19:"pause",417:"ff",412:"rw",[SE]:"back"},isEventKey(s,e){return e=e.toLowerCase(),!!(this.names[s.keyCode]&&this.names[s.keyCode]===e)},getEventName(s){if(this.names[s.keyCode])return this.names[s.keyCode];if(this.codes[s.code]){const e=this.codes[s.code];return this.names[e]}return null}},EE=5;class t4 extends ir{constructor(e){super(),this.player_=e,this.focusableComponents=[],this.isListening_=!1,this.isPaused_=!1,this.onKeyDown_=this.onKeyDown_.bind(this),this.lastFocusedComponent_=null}start(){this.isListening_||(this.player_.on("keydown",this.onKeyDown_),this.player_.on("modalKeydown",this.onKeyDown_),this.player_.on("loadedmetadata",()=>{this.focus(this.updateFocusableComponents()[0])}),this.player_.on("modalclose",()=>{this.refocusComponent()}),this.player_.on("focusin",this.handlePlayerFocus_.bind(this)),this.player_.on("focusout",this.handlePlayerBlur_.bind(this)),this.isListening_=!0,this.player_.errorDisplay&&this.player_.errorDisplay.on("aftermodalfill",()=>{this.updateFocusableComponents(),this.focusableComponents.length&&(this.focusableComponents.length>1?this.focusableComponents[1].focus():this.focusableComponents[0].focus())}))}stop(){this.player_.off("keydown",this.onKeyDown_),this.isListening_=!1}onKeyDown_(e){const t=e.originalEvent?e.originalEvent:e;if(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(t.key)){if(this.isPaused_)return;t.preventDefault();const i=t.key.substring(5).toLowerCase();this.move(i)}else if(Bu.isEventKey(t,"play")||Bu.isEventKey(t,"pause")||Bu.isEventKey(t,"ff")||Bu.isEventKey(t,"rw")){t.preventDefault();const i=Bu.getEventName(t);this.performMediaAction_(i)}else Bu.isEventKey(t,"Back")&&e.target&&typeof e.target.closeable=="function"&&e.target.closeable()&&(t.preventDefault(),e.target.close())}performMediaAction_(e){if(this.player_)switch(e){case"play":this.player_.paused()&&this.player_.play();break;case"pause":this.player_.paused()||this.player_.pause();break;case"ff":this.userSeek_(this.player_.currentTime()+EE);break;case"rw":this.userSeek_(this.player_.currentTime()-EE);break}}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}pause(){this.isPaused_=!0}resume(){this.isPaused_=!1}handlePlayerBlur_(e){const t=e.relatedTarget;let i=null;const n=this.getCurrentComponent(e.target);t&&(i=!!t.closest(".video-js"),t.classList.contains("vjs-text-track-settings")&&!this.isPaused_&&this.searchForTrackSelect_()),(!e.currentTarget.contains(e.relatedTarget)&&!i||!t)&&(n&&n.name()==="CloseButton"?this.refocusComponent():(this.pause(),n&&n.el()&&(this.lastFocusedComponent_=n)))}handlePlayerFocus_(){this.getCurrentComponent()&&this.getCurrentComponent().getIsFocusable()&&this.resume()}updateFocusableComponents(){const e=this.player_,t=[];function i(n){for(const r of n)r.hasOwnProperty("el_")&&r.getIsFocusable()&&r.getIsAvailableToBeFocused(r.el())&&t.push(r),r.hasOwnProperty("children_")&&r.children_.length>0&&i(r.children_)}return e.children_.forEach(n=>{if(n.hasOwnProperty("el_"))if(n.getIsFocusable&&n.getIsAvailableToBeFocused&&n.getIsFocusable()&&n.getIsAvailableToBeFocused(n.el())){t.push(n);return}else n.hasOwnProperty("children_")&&n.children_.length>0?i(n.children_):n.hasOwnProperty("items")&&n.items.length>0?i(n.items):this.findSuitableDOMChild(n)&&t.push(n);if(n.name_==="ErrorDisplay"&&n.opened_){const r=n.el_.querySelector(".vjs-errors-ok-button-container");r&&r.querySelectorAll("button").forEach((u,c)=>{t.push({name:()=>"ModalButton"+(c+1),el:()=>u,getPositions:()=>{const d=u.getBoundingClientRect(),f={x:d.x,y:d.y,width:d.width,height:d.height,top:d.top,right:d.right,bottom:d.bottom,left:d.left},p={x:d.left+d.width/2,y:d.top+d.height/2,width:0,height:0,top:d.top+d.height/2,right:d.left+d.width/2,bottom:d.top+d.height/2,left:d.left+d.width/2};return{boundingClientRect:f,center:p}},getIsAvailableToBeFocused:()=>!0,getIsFocusable:d=>!0,focus:()=>u.focus()})})}}),this.focusableComponents=t,this.focusableComponents}findSuitableDOMChild(e){function t(i){if(e.getIsFocusable(i)&&e.getIsAvailableToBeFocused(i))return i;for(let n=0;n0&&(this.focusableComponents=[],this.trigger({type:"focusableComponentsChanged",focusableComponents:this.focusableComponents}))}move(e){const t=this.getCurrentComponent();if(!t)return;const i=t.getPositions(),n=this.focusableComponents.filter(o=>o!==t&&this.isInDirection_(i.boundingClientRect,o.getPositions().boundingClientRect,e)),r=this.findBestCandidate_(i.center,n,e);r?this.focus(r):this.trigger({type:"endOfFocusableComponents",direction:e,focusedComponent:t})}findBestCandidate_(e,t,i){let n=1/0,r=null;for(const o of t){const u=o.getPositions().center,c=this.calculateDistance_(e,u,i);c=e.right;case"left":return t.right<=e.left;case"down":return t.top>=e.bottom;case"up":return t.bottom<=e.top;default:return!1}}refocusComponent(){if(this.lastFocusedComponent_){this.player_.userActive()||this.player_.userActive(!0),this.updateFocusableComponents();for(let e=0;ethis.handleMouseOver(i),this.handleMouseOut_=i=>this.handleMouseOut(i),this.handleClick_=i=>this.handleClick(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.emitTapEvents(),this.enable()}createEl(e="div",t={},i={}){t=Object.assign({className:this.buildCSSClass(),tabIndex:0},t),e==="button"&&ui.error(`Creating a ClickableComponent with an HTML element of ${e} is not supported; use a Button instead.`),i=Object.assign({role:"button"},i),this.tabIndex_=t.tabIndex;const n=$t(e,t,i);return this.player_.options_.experimentalSvgIcons||n.appendChild($t("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(n),n}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=$t("span",{className:"vjs-control-text"},{"aria-live":"polite"}),e&&e.appendChild(this.controlTextEl_),this.controlText(this.controlText_,e),this.controlTextEl_}controlText(e,t=this.el()){if(e===void 0)return this.controlText_||"Need Text";const i=this.localize(e);this.controlText_=e,Zo(this.controlTextEl_,i),!this.nonIconControl&&!this.player_.options_.noUITitleAttributes&&t.setAttribute("title",i)}buildCSSClass(){return`vjs-control vjs-button ${super.buildCSSClass()}`}enable(){this.enabled_||(this.enabled_=!0,this.removeClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","false"),typeof this.tabIndex_<"u"&&this.el_.setAttribute("tabIndex",this.tabIndex_),this.on(["tap","click"],this.handleClick_),this.on("keydown",this.handleKeyDown_))}disable(){this.enabled_=!1,this.addClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","true"),typeof this.tabIndex_<"u"&&this.el_.removeAttribute("tabIndex"),this.off("mouseover",this.handleMouseOver_),this.off("mouseout",this.handleMouseOut_),this.off(["tap","click"],this.handleClick_),this.off("keydown",this.handleKeyDown_)}handleLanguagechange(){this.controlText(this.controlText_)}handleClick(e){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)}handleKeyDown(e){e.key===" "||e.key==="Enter"?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}Ue.registerComponent("ClickableComponent",i0);class Qv extends i0{constructor(e,t){super(e,t),this.update(),this.update_=i=>this.update(i),e.on("posterchange",this.update_)}dispose(){this.player().off("posterchange",this.update_),super.dispose()}createEl(){return $t("div",{className:"vjs-poster"})}crossOrigin(e){if(typeof e>"u")return this.$("img")?this.$("img").crossOrigin:this.player_.tech_&&this.player_.tech_.isReady_?this.player_.crossOrigin():this.player_.options_.crossOrigin||this.player_.options_.crossorigin||null;if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.$("img")&&(this.$("img").crossOrigin=e)}update(e){const t=this.player().poster();this.setSrc(t),t?this.show():this.hide()}setSrc(e){if(!e){this.el_.textContent="";return}this.$("img")||this.el_.appendChild($t("picture",{className:"vjs-poster",tabIndex:-1},{},$t("img",{loading:"lazy",crossOrigin:this.crossOrigin()},{alt:""}))),this.$("img").src=e}handleClick(e){this.player_.controls()&&(this.player_.tech(!0)&&this.player_.tech(!0).focus(),this.player_.paused()?ta(this.player_.play()):this.player_.pause())}}Qv.prototype.crossorigin=Qv.prototype.crossOrigin;Ue.registerComponent("PosterImage",Qv);const ur="#222",wE="#ccc",s4={monospace:"monospace",sansSerif:"sans-serif",serif:"serif",monospaceSansSerif:'"Andale Mono", "Lucida Console", monospace',monospaceSerif:'"Courier New", monospace',proportionalSansSerif:"sans-serif",proportionalSerif:"serif",casual:'"Comic Sans MS", Impact, fantasy',script:'"Monotype Corsiva", cursive',smallcaps:'"Andale Mono", "Lucida Console", monospace, sans-serif'};function $y(s,e){let t;if(s.length===4)t=s[1]+s[1]+s[2]+s[2]+s[3]+s[3];else if(s.length===7)t=s.slice(1);else throw new Error("Invalid color code provided, "+s+"; must be formatted as e.g. #f0e or #f604e2.");return"rgba("+parseInt(t.slice(0,2),16)+","+parseInt(t.slice(2,4),16)+","+parseInt(t.slice(4,6),16)+","+e+")"}function zr(s,e,t){try{s.style[e]=t}catch{return}}function AE(s){return s?`${s}px`:""}class n4 extends Ue{constructor(e,t,i){super(e,t,i);const n=o=>this.updateDisplay(o),r=o=>{this.updateDisplayOverlay(),this.updateDisplay(o)};e.on("loadstart",o=>this.toggleDisplay(o)),e.on("useractive",n),e.on("userinactive",n),e.on("texttrackchange",n),e.on("loadedmetadata",o=>{this.updateDisplayOverlay(),this.preselectTrack(o)}),e.ready(Zi(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",r),e.on("playerresize",r);const o=ue.screen.orientation||ue,u=ue.screen.orientation?"change":"orientationchange";o.addEventListener(u,r),e.on("dispose",()=>o.removeEventListener(u,r));const c=this.options_.playerOptions.tracks||[];for(let d=0;d0&&u.forEach(f=>{if(f.style.inset){const p=f.style.inset.split(" ");p.length===3&&Object.assign(f.style,{top:p[0],right:p[1],bottom:p[2],left:"unset"})}})}}updateDisplayOverlay(){if(!this.player_.videoHeight()||!ue.CSS.supports("inset-inline: 10px"))return;const e=this.player_.currentWidth(),t=this.player_.currentHeight(),i=e/t,n=this.player_.videoWidth()/this.player_.videoHeight();let r=0,o=0;Math.abs(i-n)>.1&&(i>n?r=Math.round((e-t*n)/2):o=Math.round((t-e/n)/2)),zr(this.el_,"insetInline",AE(r)),zr(this.el_,"insetBlock",AE(o))}updateDisplayState(e){const t=this.player_.textTrackSettings.getValues(),i=e.activeCues;let n=i.length;for(;n--;){const r=i[n];if(!r)continue;const o=r.displayState;if(t.color&&(o.firstChild.style.color=t.color),t.textOpacity&&zr(o.firstChild,"color",$y(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(o.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&zr(o.firstChild,"backgroundColor",$y(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?zr(o,"backgroundColor",$y(t.windowColor,t.windowOpacity)):o.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle==="dropshadow"?o.firstChild.style.textShadow=`2px 2px 3px ${ur}, 2px 2px 4px ${ur}, 2px 2px 5px ${ur}`:t.edgeStyle==="raised"?o.firstChild.style.textShadow=`1px 1px ${ur}, 2px 2px ${ur}, 3px 3px ${ur}`:t.edgeStyle==="depressed"?o.firstChild.style.textShadow=`1px 1px ${wE}, 0 1px ${wE}, -1px -1px ${ur}, 0 -1px ${ur}`:t.edgeStyle==="uniform"&&(o.firstChild.style.textShadow=`0 0 4px ${ur}, 0 0 4px ${ur}, 0 0 4px ${ur}, 0 0 4px ${ur}`)),t.fontPercent&&t.fontPercent!==1){const u=ue.parseFloat(o.style.fontSize);o.style.fontSize=u*t.fontPercent+"px",o.style.height="auto",o.style.top="auto"}t.fontFamily&&t.fontFamily!=="default"&&(t.fontFamily==="small-caps"?o.firstChild.style.fontVariant="small-caps":o.firstChild.style.fontFamily=s4[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof ue.WebVTT!="function"||e.every(i=>!i.activeCues))return;const t=[];for(let i=0;ithis.handleMouseDown(i))}buildCSSClass(){return"vjs-big-play-button"}handleClick(e){const t=this.player_.play();if(e.type==="tap"||this.mouseused_&&"clientX"in e&&"clientY"in e){ta(t),this.player_.tech(!0)&&this.player_.tech(!0).focus();return}const i=this.player_.getChild("controlBar"),n=i&&i.getChild("playToggle");if(!n){this.player_.tech(!0).focus();return}const r=()=>n.focus();sh(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}EC.prototype.controlText_="Play Video";Ue.registerComponent("BigPlayButton",EC);class a4 extends ln{constructor(e,t){super(e,t),this.setIcon("cancel"),this.controlText(t&&t.controlText||this.localize("Close"))}buildCSSClass(){return`vjs-close-button ${super.buildCSSClass()}`}handleClick(e){this.trigger({type:"close",bubbles:!1})}handleKeyDown(e){e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}Ue.registerComponent("CloseButton",a4);class wC extends ln{constructor(e,t={}){super(e,t),t.replay=t.replay===void 0||t.replay,this.setIcon("play"),this.on(e,"play",i=>this.handlePlay(i)),this.on(e,"pause",i=>this.handlePause(i)),t.replay&&this.on(e,"ended",i=>this.handleEnded(i))}buildCSSClass(){return`vjs-play-control ${super.buildCSSClass()}`}handleClick(e){this.player_.paused()?ta(this.player_.play()):this.player_.pause()}handleSeeked(e){this.removeClass("vjs-ended"),this.player_.paused()?this.handlePause(e):this.handlePlay(e)}handlePlay(e){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.setIcon("pause"),this.controlText("Pause")}handlePause(e){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.setIcon("play"),this.controlText("Play")}handleEnded(e){this.removeClass("vjs-playing"),this.addClass("vjs-ended"),this.setIcon("replay"),this.controlText("Replay"),this.one(this.player_,"seeked",t=>this.handleSeeked(t))}}wC.prototype.controlText_="Play";Ue.registerComponent("PlayToggle",wC);class Ic extends Ue{constructor(e,t){super(e,t),this.on(e,["timeupdate","ended","seeking"],i=>this.update(i)),this.updateTextNode_()}createEl(){const e=this.buildCSSClass(),t=super.createEl("div",{className:`${e} vjs-time-control vjs-control`}),i=$t("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)} `},{role:"presentation"});return t.appendChild(i),this.contentEl_=$t("span",{className:`${e}-display`},{role:"presentation"}),t.appendChild(this.contentEl_),t}dispose(){this.contentEl_=null,this.textNode_=null,super.dispose()}update(e){!this.player_.options_.enableSmoothSeeking&&e.type==="seeking"||this.updateContent(e)}updateTextNode_(e=0){e=ql(e),this.formattedTime_!==e&&(this.formattedTime_=e,this.requestNamedAnimationFrame("TimeDisplay#updateTextNode_",()=>{if(!this.contentEl_)return;let t=this.textNode_;t&&this.contentEl_.firstChild!==t&&(t=null,ui.warn("TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.")),this.textNode_=st.createTextNode(this.formattedTime_),this.textNode_&&(t?this.contentEl_.replaceChild(this.textNode_,t):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}}Ic.prototype.labelText_="Time";Ic.prototype.controlText_="Time";Ue.registerComponent("TimeDisplay",Ic);class ob extends Ic{buildCSSClass(){return"vjs-current-time"}updateContent(e){let t;this.player_.ended()?t=this.player_.duration():e&&e.target&&typeof e.target.pendingSeekTime=="function"?t=e.target.pendingSeekTime():t=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime(),this.updateTextNode_(t)}}ob.prototype.labelText_="Current Time";ob.prototype.controlText_="Current Time";Ue.registerComponent("CurrentTimeDisplay",ob);class lb extends Ic{constructor(e,t){super(e,t);const i=n=>this.updateContent(n);this.on(e,"durationchange",i),this.on(e,"loadstart",i),this.on(e,"loadedmetadata",i)}buildCSSClass(){return"vjs-duration"}updateContent(e){const t=this.player_.duration();this.updateTextNode_(t)}}lb.prototype.labelText_="Duration";lb.prototype.controlText_="Duration";Ue.registerComponent("DurationDisplay",lb);class o4 extends Ue{createEl(){const e=super.createEl("div",{className:"vjs-time-control vjs-time-divider"},{"aria-hidden":!0}),t=super.createEl("div"),i=super.createEl("span",{textContent:"/"});return t.appendChild(i),e.appendChild(t),e}}Ue.registerComponent("TimeDivider",o4);class ub extends Ic{constructor(e,t){super(e,t),this.on(e,"durationchange",i=>this.updateContent(i))}buildCSSClass(){return"vjs-remaining-time"}createEl(){const e=super.createEl();return this.options_.displayNegative!==!1&&e.insertBefore($t("span",{},{"aria-hidden":!0},"-"),this.contentEl_),e}updateContent(e){if(typeof this.player_.duration()!="number")return;let t;this.player_.ended()?t=0:this.player_.remainingTimeDisplay?t=this.player_.remainingTimeDisplay():t=this.player_.remainingTime(),this.updateTextNode_(t)}}ub.prototype.labelText_="Remaining Time";ub.prototype.controlText_="Remaining Time";Ue.registerComponent("RemainingTimeDisplay",ub);class l4 extends Ue{constructor(e,t){super(e,t),this.updateShowing(),this.on(this.player(),"durationchange",i=>this.updateShowing(i))}createEl(){const e=super.createEl("div",{className:"vjs-live-control vjs-control"});return this.contentEl_=$t("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild($t("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(st.createTextNode(this.localize("LIVE"))),e.appendChild(this.contentEl_),e}dispose(){this.contentEl_=null,super.dispose()}updateShowing(e){this.player().duration()===1/0?this.show():this.hide()}}Ue.registerComponent("LiveDisplay",l4);class AC extends ln{constructor(e,t){super(e,t),this.updateLiveEdgeStatus(),this.player_.liveTracker&&(this.updateLiveEdgeStatusHandler_=i=>this.updateLiveEdgeStatus(i),this.on(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_))}createEl(){const e=super.createEl("button",{className:"vjs-seek-to-live-control vjs-control"});return this.setIcon("circle",e),this.textEl_=$t("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),e.appendChild(this.textEl_),e}updateLiveEdgeStatus(){!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()?(this.setAttribute("aria-disabled",!0),this.addClass("vjs-at-live-edge"),this.controlText("Seek to live, currently playing live")):(this.setAttribute("aria-disabled",!1),this.removeClass("vjs-at-live-edge"),this.controlText("Seek to live, currently behind live"))}handleClick(){this.player_.liveTracker.seekToLiveEdge()}dispose(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,super.dispose()}}AC.prototype.controlText_="Seek to live, currently playing live";Ue.registerComponent("SeekToLive",AC);function Dh(s,e,t){return s=Number(s),Math.min(t,Math.max(e,isNaN(s)?e:s))}var u4=Object.freeze({__proto__:null,clamp:Dh});class cb extends Ue{constructor(e,t){super(e,t),this.handleMouseDown_=i=>this.handleMouseDown(i),this.handleMouseUp_=i=>this.handleMouseUp(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.handleClick_=i=>this.handleClick(i),this.handleMouseMove_=i=>this.handleMouseMove(i),this.update_=i=>this.update(i),this.bar=this.getChild(this.options_.barName),this.vertical(!!this.options_.vertical),this.enable()}enabled(){return this.enabled_}enable(){this.enabled()||(this.on("mousedown",this.handleMouseDown_),this.on("touchstart",this.handleMouseDown_),this.on("keydown",this.handleKeyDown_),this.on("click",this.handleClick_),this.on(this.player_,"controlsvisible",this.update),this.playerEvent&&this.on(this.player_,this.playerEvent,this.update),this.removeClass("disabled"),this.setAttribute("tabindex",0),this.enabled_=!0)}disable(){if(!this.enabled())return;const e=this.bar.el_.ownerDocument;this.off("mousedown",this.handleMouseDown_),this.off("touchstart",this.handleMouseDown_),this.off("keydown",this.handleKeyDown_),this.off("click",this.handleClick_),this.off(this.player_,"controlsvisible",this.update_),this.off(e,"mousemove",this.handleMouseMove_),this.off(e,"mouseup",this.handleMouseUp_),this.off(e,"touchmove",this.handleMouseMove_),this.off(e,"touchend",this.handleMouseUp_),this.removeAttribute("tabindex"),this.addClass("disabled"),this.playerEvent&&this.off(this.player_,this.playerEvent,this.update),this.enabled_=!1}createEl(e,t={},i={}){return t.className=t.className+" vjs-slider",t=Object.assign({tabIndex:0},t),i=Object.assign({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100},i),super.createEl(e,t,i)}handleMouseDown(e){const t=this.bar.el_.ownerDocument;e.type==="mousedown"&&e.preventDefault(),e.type==="touchstart"&&!ca&&e.preventDefault(),ZA(),this.addClass("vjs-sliding"),this.trigger("slideractive"),this.on(t,"mousemove",this.handleMouseMove_),this.on(t,"mouseup",this.handleMouseUp_),this.on(t,"touchmove",this.handleMouseMove_),this.on(t,"touchend",this.handleMouseUp_),this.handleMouseMove(e,!0)}handleMouseMove(e){}handleMouseUp(e){const t=this.bar.el_.ownerDocument;JA(),this.removeClass("vjs-sliding"),this.trigger("sliderinactive"),this.off(t,"mousemove",this.handleMouseMove_),this.off(t,"mouseup",this.handleMouseUp_),this.off(t,"touchmove",this.handleMouseMove_),this.off(t,"touchend",this.handleMouseUp_),this.update()}update(){if(!this.el_||!this.bar)return;const e=this.getProgress();return e===this.progress_||(this.progress_=e,this.requestNamedAnimationFrame("Slider#update",()=>{const t=this.vertical()?"height":"width";this.bar.el().style[t]=(e*100).toFixed(2)+"%"})),e}getProgress(){return Number(Dh(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){const t=Xp(this.el_,e);return this.vertical()?t.y:t.x}handleKeyDown(e){const t=this.options_.playerOptions.spatialNavigation,i=t&&t.enabled,n=t&&t.horizontalSeek;i?n&&e.key==="ArrowLeft"||!n&&e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepBack()):n&&e.key==="ArrowRight"||!n&&e.key==="ArrowUp"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(this.pendingSeekTime()&&(this.pendingSeekTime(null),this.userSeek_(this.player_.currentTime())),super.handleKeyDown(e)):e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepBack()):e.key==="ArrowUp"||e.key==="ArrowRight"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):super.handleKeyDown(e)}handleClick(e){e.stopPropagation(),e.preventDefault()}vertical(e){if(e===void 0)return this.vertical_||!1;this.vertical_=!!e,this.vertical_?this.addClass("vjs-slider-vertical"):this.addClass("vjs-slider-horizontal")}}Ue.registerComponent("Slider",cb);const Hy=(s,e)=>Dh(s/e*100,0,100).toFixed(2)+"%";class c4 extends Ue{constructor(e,t){super(e,t),this.partEls_=[],this.on(e,"progress",i=>this.update(i))}createEl(){const e=super.createEl("div",{className:"vjs-load-progress"}),t=$t("span",{className:"vjs-control-text"}),i=$t("span",{textContent:this.localize("Loaded")}),n=st.createTextNode(": ");return this.percentageEl_=$t("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),e.appendChild(t),t.appendChild(i),t.appendChild(n),t.appendChild(this.percentageEl_),e}dispose(){this.partEls_=null,this.percentageEl_=null,super.dispose()}update(e){this.requestNamedAnimationFrame("LoadProgressBar#update",()=>{const t=this.player_.liveTracker,i=this.player_.buffered(),n=t&&t.isLive()?t.seekableEnd():this.player_.duration(),r=this.player_.bufferedEnd(),o=this.partEls_,u=Hy(r,n);this.percent_!==u&&(this.el_.style.width=u,Zo(this.percentageEl_,u),this.percent_=u);for(let c=0;ci.length;c--)this.el_.removeChild(o[c-1]);o.length=i.length})}}Ue.registerComponent("LoadProgressBar",c4);class d4 extends Ue{constructor(e,t){super(e,t),this.update=da(Zi(this,this.update),hr)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){const n=fh(this.el_),r=Tc(this.player_.el()),o=e.width*t;if(!r||!n)return;let u=e.left-r.left+o,c=e.width-o+(r.right-e.right);c||(c=e.width-o,u=o);let d=n.width/2;un.width&&(d=n.width),d=Math.round(d),this.el_.style.right=`-${d}px`,this.write(i)}write(e){Zo(this.el_,e)}updateTime(e,t,i,n){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;const o=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const u=this.player_.liveTracker.liveWindow(),c=u-t*u;r=(c<1?"":"-")+ql(c,u)}else r=ql(i,o);this.update(e,t,r),n&&n()})}}Ue.registerComponent("TimeTooltip",d4);class db extends Ue{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=da(Zi(this,this.update),hr)}createEl(){return super.createEl("div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})}update(e,t,i){const n=this.getChild("timeTooltip");if(!n)return;const r=i&&i.target&&typeof i.target.pendingSeekTime=="function"?i.target.pendingSeekTime():this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();n.updateTime(e,t,r)}}db.prototype.options_={children:[]};!an&&!Dr&&db.prototype.options_.children.push("timeTooltip");Ue.registerComponent("PlayProgressBar",db);class CC extends Ue{constructor(e,t){super(e,t),this.update=da(Zi(this,this.update),hr)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t){const i=t*this.player_.duration();this.getChild("timeTooltip").updateTime(e,t,i,()=>{this.el_.style.left=`${e.width*t}px`})}}CC.prototype.options_={children:["timeTooltip"]};Ue.registerComponent("MouseTimeDisplay",CC);class s0 extends cb{constructor(e,t){t=ji(s0.prototype.options_,t),t.children=[...t.children];const i=e.options_.disableSeekWhileScrubbingOnMobile&&(an||Dr)||e.options_.disableSeekWhileScrubbingOnSTV;(!an&&!Dr||i)&&t.children.splice(1,0,"mouseTimeDisplay"),super(e,t),this.shouldDisableSeekWhileScrubbing_=i,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=Zi(this,this.update),this.update=da(this.update_,hr),this.on(this.player_,["durationchange","timeupdate"],this.update),this.on(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in st&&"visibilityState"in st&&this.on(st,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){st.visibilityState==="hidden"?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(e)):(!this.player_.ended()&&!this.player_.paused()&&this.enableInterval_(),this.update())}enableInterval_(){this.updateInterval||(this.updateInterval=this.setInterval(this.update,hr))}disableInterval_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&e&&e.type!=="ended"||this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)}createEl(){return super.createEl("div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})}update(e){if(st.visibilityState==="hidden")return;const t=super.update();return this.requestNamedAnimationFrame("SeekBar#update",()=>{const i=this.player_.ended()?this.player_.duration():this.getCurrentTime_(),n=this.player_.liveTracker;let r=this.player_.duration();n&&n.isLive()&&(r=this.player_.liveTracker.liveCurrentTime()),this.percent_!==t&&(this.el_.setAttribute("aria-valuenow",(t*100).toFixed(2)),this.percent_=t),(this.currentTime_!==i||this.duration_!==r)&&(this.el_.setAttribute("aria-valuetext",this.localize("progress bar timing: currentTime={1} duration={2}",[ql(i,r),ql(r,r)],"{1} of {2}")),this.currentTime_=i,this.duration_=r),this.bar&&this.bar.update(Tc(this.el()),this.getProgress(),e)}),t}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()}pendingSeekTime(e){if(e!==void 0)if(e!==null){const t=this.player_.duration();this.pendingSeekTime_=Math.max(0,Math.min(e,t))}else this.pendingSeekTime_=null;return this.pendingSeekTime_}getPercent(){if(this.pendingSeekTime()!==null)return this.pendingSeekTime()/this.player_.duration();const e=this.getCurrentTime_();let t;const i=this.player_.liveTracker;return i&&i.isLive()?(t=(e-i.seekableStart())/i.liveWindow(),i.atLiveEdge()&&(t=1)):t=e/this.player_.duration(),t}handleMouseDown(e){mh(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!mh(e)||isNaN(this.player_.duration()))return;!t&&!this.player_.scrubbing()&&this.player_.scrubbing(!0);let i;const n=this.calculateDistance(e),r=this.player_.liveTracker;if(!r||!r.isLive())i=n*this.player_.duration(),i===this.player_.duration()&&(i=i-.1);else{if(n>=.99){r.seekToLiveEdge();return}const o=r.seekableStart(),u=r.liveCurrentTime();if(i=o+n*r.liveWindow(),i>=u&&(i=u),i<=o&&(i=o+.1),i===1/0)return}this.shouldDisableSeekWhileScrubbing_?this.pendingSeekTime(i):this.userSeek_(i),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();const e=this.getChild("mouseTimeDisplay");e&&e.show()}disable(){super.disable();const e=this.getChild("mouseTimeDisplay");e&&e.hide()}handleMouseUp(e){super.handleMouseUp(e),e&&e.stopPropagation(),this.player_.scrubbing(!1),this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?ta(this.player_.play()):this.update_()}handlePendingSeek_(e){this.player_.paused()||this.player_.pause();const t=this.pendingSeekTime()!==null?this.pendingSeekTime():this.player_.currentTime();this.pendingSeekTime(t+e),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}stepForward(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(this.options().stepSeconds):this.userSeek_(this.player_.currentTime()+this.options().stepSeconds)}stepBack(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(-this.options().stepSeconds):this.userSeek_(this.player_.currentTime()-this.options().stepSeconds)}handleAction(e){this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(e){const t=this.player_.liveTracker;if(e.key===" "||e.key==="Enter")e.preventDefault(),e.stopPropagation(),this.handleAction(e);else if(e.key==="Home")e.preventDefault(),e.stopPropagation(),this.userSeek_(0);else if(e.key==="End")e.preventDefault(),e.stopPropagation(),t&&t.isLive()?this.userSeek_(t.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(e.key)){e.preventDefault(),e.stopPropagation();const i=parseInt(e.key,10)*.1;t&&t.isLive()?this.userSeek_(t.seekableStart()+t.liveWindow()*i):this.userSeek_(this.player_.duration()*i)}else e.key==="PageDown"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()-this.options().stepSeconds*this.options().pageMultiplier)):e.key==="PageUp"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()+this.options().stepSeconds*this.options().pageMultiplier)):super.handleKeyDown(e)}dispose(){this.disableInterval_(),this.off(this.player_,["durationchange","timeupdate"],this.update),this.off(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.update),this.off(this.player_,["playing"],this.enableIntervalHandler_),this.off(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in st&&"visibilityState"in st&&this.off(st,"visibilitychange",this.toggleVisibility_),super.dispose()}}s0.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar",stepSeconds:5,pageMultiplier:12};Ue.registerComponent("SeekBar",s0);class kC extends Ue{constructor(e,t){super(e,t),this.handleMouseMove=da(Zi(this,this.handleMouseMove),hr),this.throttledHandleMouseSeek=da(Zi(this,this.handleMouseSeek),hr),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.handleMouseDownHandler_=i=>this.handleMouseDown(i),this.enable()}createEl(){return super.createEl("div",{className:"vjs-progress-control vjs-control"})}handleMouseMove(e){const t=this.getChild("seekBar");if(!t)return;const i=t.getChild("playProgressBar"),n=t.getChild("mouseTimeDisplay");if(!i&&!n)return;const r=t.el(),o=fh(r);let u=Xp(r,e).x;u=Dh(u,0,1),n&&n.update(o,u),i&&i.update(o,t.getProgress())}handleMouseSeek(e){const t=this.getChild("seekBar");t&&t.handleMouseMove(e)}enabled(){return this.enabled_}disable(){if(this.children().forEach(e=>e.disable&&e.disable()),!!this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.off(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){const e=this.getChild("seekBar");this.player_.scrubbing(!1),e.videoWasPlaying&&ta(this.player_.play())}}enable(){this.children().forEach(e=>e.enable&&e.enable()),!this.enabled()&&(this.on(["mousedown","touchstart"],this.handleMouseDownHandler_),this.on(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeClass("disabled"),this.enabled_=!0)}removeListenersAddedOnMousedownAndTouchstart(){const e=this.el_.ownerDocument;this.off(e,"mousemove",this.throttledHandleMouseSeek),this.off(e,"touchmove",this.throttledHandleMouseSeek),this.off(e,"mouseup",this.handleMouseUpHandler_),this.off(e,"touchend",this.handleMouseUpHandler_)}handleMouseDown(e){const t=this.el_.ownerDocument,i=this.getChild("seekBar");i&&i.handleMouseDown(e),this.on(t,"mousemove",this.throttledHandleMouseSeek),this.on(t,"touchmove",this.throttledHandleMouseSeek),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.getChild("seekBar");t&&t.handleMouseUp(e),this.removeListenersAddedOnMousedownAndTouchstart()}}kC.prototype.options_={children:["seekBar"]};Ue.registerComponent("ProgressControl",kC);class DC extends ln{constructor(e,t){super(e,t),this.setIcon("picture-in-picture-enter"),this.on(e,["enterpictureinpicture","leavepictureinpicture"],i=>this.handlePictureInPictureChange(i)),this.on(e,["disablepictureinpicturechanged","loadedmetadata"],i=>this.handlePictureInPictureEnabledChange(i)),this.on(e,["loadedmetadata","audioonlymodechange","audiopostermodechange"],()=>this.handlePictureInPictureAudioModeChange()),this.disable()}buildCSSClass(){return`vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`}handlePictureInPictureAudioModeChange(){if(!(this.player_.currentType().substring(0,5)==="audio"||this.player_.audioPosterMode()||this.player_.audioOnlyMode())){this.show();return}this.player_.isInPictureInPicture()&&this.player_.exitPictureInPicture(),this.hide()}handlePictureInPictureEnabledChange(){st.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in ue?this.enable():this.disable()}handlePictureInPictureChange(e){this.player_.isInPictureInPicture()?(this.setIcon("picture-in-picture-exit"),this.controlText("Exit Picture-in-Picture")):(this.setIcon("picture-in-picture-enter"),this.controlText("Picture-in-Picture")),this.handlePictureInPictureEnabledChange()}handleClick(e){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()}show(){typeof st.exitPictureInPicture=="function"&&super.show()}}DC.prototype.controlText_="Picture-in-Picture";Ue.registerComponent("PictureInPictureToggle",DC);class LC extends ln{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),st[e.fsApi_.fullscreenEnabled]===!1&&this.disable()}buildCSSClass(){return`vjs-fullscreen-control ${super.buildCSSClass()}`}handleFullscreenChange(e){this.player_.isFullscreen()?(this.controlText("Exit Fullscreen"),this.setIcon("fullscreen-exit")):(this.controlText("Fullscreen"),this.setIcon("fullscreen-enter"))}handleClick(e){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()}}LC.prototype.controlText_="Fullscreen";Ue.registerComponent("FullscreenToggle",LC);const h4=function(s,e){e.tech_&&!e.tech_.featuresVolumeControl&&s.addClass("vjs-hidden"),s.on(e,"loadstart",function(){e.tech_.featuresVolumeControl?s.removeClass("vjs-hidden"):s.addClass("vjs-hidden")})};class f4 extends Ue{createEl(){const e=super.createEl("div",{className:"vjs-volume-level"});return this.setIcon("circle",e),e.appendChild(super.createEl("span",{className:"vjs-control-text"})),e}}Ue.registerComponent("VolumeLevel",f4);class m4 extends Ue{constructor(e,t){super(e,t),this.update=da(Zi(this,this.update),hr)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,n){if(!i){const r=Tc(this.el_),o=Tc(this.player_.el()),u=e.width*t;if(!o||!r)return;const c=e.left-o.left+u,d=e.width-u+(o.right-e.right);let f=r.width/2;cr.width&&(f=r.width),this.el_.style.right=`-${f}px`}this.write(`${n}%`)}write(e){Zo(this.el_,e)}updateVolume(e,t,i,n,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,n.toFixed(0)),r&&r()})}}Ue.registerComponent("VolumeLevelTooltip",m4);class RC extends Ue{constructor(e,t){super(e,t),this.update=da(Zi(this,this.update),hr)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t,i){const n=100*t;this.getChild("volumeLevelTooltip").updateVolume(e,t,i,n,()=>{i?this.el_.style.bottom=`${e.height*t}px`:this.el_.style.left=`${e.width*t}px`})}}RC.prototype.options_={children:["volumeLevelTooltip"]};Ue.registerComponent("MouseVolumeLevelDisplay",RC);class n0 extends cb{constructor(e,t){super(e,t),this.on("slideractive",i=>this.updateLastVolume_(i)),this.on(e,"volumechange",i=>this.updateARIAAttributes(i)),e.ready(()=>this.updateARIAAttributes())}createEl(){return super.createEl("div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})}handleMouseDown(e){mh(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),n=Tc(i),r=this.vertical();let o=Xp(i,e);o=r?o.y:o.x,o=Dh(o,0,1),t.update(n,o,r)}mh(e)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(e)))}checkMuted(){this.player_.muted()&&this.player_.muted(!1)}getPercent(){return this.player_.muted()?0:this.player_.volume()}stepForward(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)}stepBack(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)}updateARIAAttributes(e){const t=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",t),this.el_.setAttribute("aria-valuetext",t+"%")}volumeAsPercentage_(){return Math.round(this.player_.volume()*100)}updateLastVolume_(){const e=this.player_.volume();this.one("sliderinactive",()=>{this.player_.volume()===0&&this.player_.lastVolume_(e)})}}n0.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!an&&!Dr&&n0.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");n0.prototype.playerEvent="volumechange";Ue.registerComponent("VolumeBar",n0);class IC extends Ue{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||xc(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),h4(this,e),this.throttledHandleMouseMove=da(Zi(this,this.handleMouseMove),hr),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.on("mousedown",i=>this.handleMouseDown(i)),this.on("touchstart",i=>this.handleMouseDown(i)),this.on("mousemove",i=>this.handleMouseMove(i)),this.on(this.volumeBar,["focus","slideractive"],()=>{this.volumeBar.addClass("vjs-slider-active"),this.addClass("vjs-slider-active"),this.trigger("slideractive")}),this.on(this.volumeBar,["blur","sliderinactive"],()=>{this.volumeBar.removeClass("vjs-slider-active"),this.removeClass("vjs-slider-active"),this.trigger("sliderinactive")})}createEl(){let e="vjs-volume-horizontal";return this.options_.vertical&&(e="vjs-volume-vertical"),super.createEl("div",{className:`vjs-volume-control vjs-control ${e}`})}handleMouseDown(e){const t=this.el_.ownerDocument;this.on(t,"mousemove",this.throttledHandleMouseMove),this.on(t,"touchmove",this.throttledHandleMouseMove),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.el_.ownerDocument;this.off(t,"mousemove",this.throttledHandleMouseMove),this.off(t,"touchmove",this.throttledHandleMouseMove),this.off(t,"mouseup",this.handleMouseUpHandler_),this.off(t,"touchend",this.handleMouseUpHandler_)}handleMouseMove(e){this.volumeBar.handleMouseMove(e)}}IC.prototype.options_={children:["volumeBar"]};Ue.registerComponent("VolumeControl",IC);const p4=function(s,e){e.tech_&&!e.tech_.featuresMuteControl&&s.addClass("vjs-hidden"),s.on(e,"loadstart",function(){e.tech_.featuresMuteControl?s.removeClass("vjs-hidden"):s.addClass("vjs-hidden")})};class NC extends ln{constructor(e,t){super(e,t),p4(this,e),this.on(e,["loadstart","volumechange"],i=>this.update(i))}buildCSSClass(){return`vjs-mute-control ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.volume(),i=this.player_.lastVolume_();if(t===0){const n=i<.1?.1:i;this.player_.volume(n),this.player_.muted(!1)}else this.player_.muted(!this.player_.muted())}update(e){this.updateIcon_(),this.updateControlText_()}updateIcon_(){const e=this.player_.volume();let t=3;this.setIcon("volume-high"),an&&this.player_.tech_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),e===0||this.player_.muted()?(this.setIcon("volume-mute"),t=0):e<.33?(this.setIcon("volume-low"),t=1):e<.67&&(this.setIcon("volume-medium"),t=2),Yp(this.el_,[0,1,2,3].reduce((i,n)=>i+`${n?" ":""}vjs-vol-${n}`,"")),jl(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}NC.prototype.controlText_="Mute";Ue.registerComponent("MuteToggle",NC);class OC extends Ue{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||xc(t.volumeControl))&&(t.volumeControl=t.volumeControl||{},t.volumeControl.vertical=!t.inline),super(e,t),this.handleKeyPressHandler_=i=>this.handleKeyPress(i),this.on(e,["loadstart"],i=>this.volumePanelState_(i)),this.on(this.muteToggle,"keyup",i=>this.handleKeyPress(i)),this.on(this.volumeControl,"keyup",i=>this.handleVolumeControlKeyUp(i)),this.on("keydown",i=>this.handleKeyPress(i)),this.on("mouseover",i=>this.handleMouseOver(i)),this.on("mouseout",i=>this.handleMouseOut(i)),this.on(this.volumeControl,["slideractive"],this.sliderActive_),this.on(this.volumeControl,["sliderinactive"],this.sliderInactive_)}sliderActive_(){this.addClass("vjs-slider-active")}sliderInactive_(){this.removeClass("vjs-slider-active")}volumePanelState_(){this.volumeControl.hasClass("vjs-hidden")&&this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-hidden"),this.volumeControl.hasClass("vjs-hidden")&&!this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-mute-toggle-only")}createEl(){let e="vjs-volume-panel-horizontal";return this.options_.inline||(e="vjs-volume-panel-vertical"),super.createEl("div",{className:`vjs-volume-panel vjs-control ${e}`})}dispose(){this.handleMouseOut(),super.dispose()}handleVolumeControlKeyUp(e){e.key==="Escape"&&this.muteToggle.focus()}handleMouseOver(e){this.addClass("vjs-hover"),tr(st,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),on(st,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}OC.prototype.options_={children:["muteToggle","volumeControl"]};Ue.registerComponent("VolumePanel",OC);class MC extends ln{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipForwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`forward-${this.skipTime}`),this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipForwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.forward}buildCSSClass(){return`vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`}handleClick(e){if(isNaN(this.player_.duration()))return;const t=this.player_.currentTime(),i=this.player_.liveTracker,n=i&&i.isLive()?i.seekableEnd():this.player_.duration();let r;t+this.skipTime<=n?r=t+this.skipTime:r=n,this.player_.currentTime(r)}handleLanguagechange(){this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime]))}}MC.prototype.controlText_="Skip Forward";Ue.registerComponent("SkipForward",MC);class PC extends ln{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipBackwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`replay-${this.skipTime}`),this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipBackwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.backward}buildCSSClass(){return`vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.currentTime(),i=this.player_.liveTracker,n=i&&i.isLive()&&i.seekableStart();let r;n&&t-this.skipTime<=n?r=n:t>=this.skipTime?r=t-this.skipTime:r=0,this.player_.currentTime(r)}handleLanguagechange(){this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime]))}}PC.prototype.controlText_="Skip Backward";Ue.registerComponent("SkipBackward",PC);class BC extends Ue{constructor(e,t){super(e,t),t&&(this.menuButton_=t.menuButton),this.focusedChild_=-1,this.on("keydown",i=>this.handleKeyDown(i)),this.boundHandleBlur_=i=>this.handleBlur(i),this.boundHandleTapClick_=i=>this.handleTapClick(i)}addEventListenerForItem(e){e instanceof Ue&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof Ue&&(this.off(e,"blur",this.boundHandleBlur_),this.off(e,["tap","click"],this.boundHandleTapClick_))}removeChild(e){typeof e=="string"&&(e=this.getChild(e)),this.removeEventListenerForItem(e),super.removeChild(e)}addItem(e){const t=this.addChild(e);t&&this.addEventListenerForItem(t)}createEl(){const e=this.options_.contentElType||"ul";this.contentEl_=$t(e,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");const t=super.createEl("div",{append:this.contentEl_,className:"vjs-menu"});return t.appendChild(this.contentEl_),tr(t,"click",function(i){i.preventDefault(),i.stopImmediatePropagation()}),t}dispose(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,super.dispose()}handleBlur(e){const t=e.relatedTarget||st.activeElement;if(!this.children().some(i=>i.el()===t)){const i=this.menuButton_;i&&i.buttonPressed_&&t!==i.el().firstChild&&i.unpressButton()}}handleTapClick(e){if(this.menuButton_){this.menuButton_.unpressButton();const t=this.children();if(!Array.isArray(t))return;const i=t.filter(n=>n.el()===e.target)[0];if(!i)return;i.name()!=="CaptionSettingsMenuItem"&&this.menuButton_.focus()}}handleKeyDown(e){e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(e.key==="ArrowRight"||e.key==="ArrowUp")&&(e.preventDefault(),e.stopPropagation(),this.stepBack())}stepForward(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_+1),this.focus(e)}stepBack(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_-1),this.focus(e)}focus(e=0){const t=this.children().slice();t.length&&t[0].hasClass("vjs-menu-title")&&t.shift(),t.length>0&&(e<0?e=0:e>=t.length&&(e=t.length-1),this.focusedChild_=e,t[e].el_.focus())}}Ue.registerComponent("Menu",BC);class hb extends Ue{constructor(e,t={}){super(e,t),this.menuButton_=new ln(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=ln.prototype.buildCSSClass();this.menuButton_.el_.className=this.buildCSSClass()+" "+i,this.menuButton_.removeClass("vjs-control"),this.addChild(this.menuButton_),this.update(),this.enabled_=!0;const n=r=>this.handleClick(r);this.handleMenuKeyUp_=r=>this.handleMenuKeyUp(r),this.on(this.menuButton_,"tap",n),this.on(this.menuButton_,"click",n),this.on(this.menuButton_,"keydown",r=>this.handleKeyDown(r)),this.on(this.menuButton_,"mouseenter",()=>{this.addClass("vjs-hover"),this.menu.show(),tr(st,"keyup",this.handleMenuKeyUp_)}),this.on("mouseleave",r=>this.handleMouseLeave(r)),this.on("keydown",r=>this.handleSubmenuKeyDown(r))}update(){const e=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=e,this.addChild(e),this.buttonPressed_=!1,this.menuButton_.el_.setAttribute("aria-expanded","false"),this.items&&this.items.length<=this.hideThreshold_?(this.hide(),this.menu.contentEl_.removeAttribute("role")):(this.show(),this.menu.contentEl_.setAttribute("role","menu"))}createMenu(){const e=new BC(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=$t("li",{className:"vjs-menu-title",textContent:xs(this.options_.title),tabIndex:-1}),i=new Ue(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,u)},o=(...u)=>{this.handleSelectedLanguageChange.apply(this,u)};if(e.on(["loadstart","texttrackchange"],r),n.addEventListener("change",r),n.addEventListener("selectedlanguagechange",o),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),n.removeEventListener("change",r),n.removeEventListener("selectedlanguagechange",o)}),n.onchange===void 0){let u;this.on(["tap","click"],function(){if(typeof ue.Event!="object")try{u=new ue.Event("change")}catch{}u||(u=st.createEvent("Event"),u.initEvent("change",!0,!0)),n.dispatchEvent(u)})}this.handleTracksChange()}handleClick(e){const t=this.track,i=this.player_.textTracks();if(super.handleClick(e),!!i)for(let n=0;n-1&&o.mode==="showing"){i=!1;break}}i!==this.isSelected_&&this.selected(i)}handleSelectedLanguageChange(e){const t=this.player().textTracks();let i=!0;for(let n=0,r=t.length;n-1&&o.mode==="showing"){i=!1;break}}i&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}}Ue.registerComponent("OffTextTrackMenuItem",FC);class Nc extends fb{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=Rh){let i;this.label_&&(i=`${this.label_} off`),e.push(new FC(this.player_,{kinds:this.kinds_,kind:this.kind_,label:i})),this.hideThreshold_+=1;const n=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let r=0;r-1){const u=new t(this.player_,{track:o,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});u.addClass(`vjs-${o.kind}-menu-item`),e.push(u)}}return e}}Ue.registerComponent("TextTrackButton",Nc);class UC extends Lh{constructor(e,t){const i=t.track,n=t.cue,r=e.currentTime();t.selectable=!0,t.multiSelectable=!1,t.label=n.text,t.selected=n.startTime<=r&&r{this.items.forEach(n=>{n.selected(this.track_.activeCues[0]===n.cue)})}}buildCSSClass(){return`vjs-chapters-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-chapters-button ${super.buildWrapperCSSClass()}`}update(e){if(e&&e.track&&e.track.kind!=="chapters")return;const t=this.findChaptersTrack();t!==this.track_?(this.setTrack(t),super.update()):(!this.items||t&&t.cues&&t.cues.length!==this.items.length)&&super.update()}setTrack(e){if(this.track_!==e){if(this.updateHandler_||(this.updateHandler_=this.update.bind(this)),this.track_){const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.removeEventListener("load",this.updateHandler_),this.track_.removeEventListener("cuechange",this.selectCurrentItem_),this.track_=null}if(this.track_=e,this.track_){this.track_.mode="hidden";const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.addEventListener("load",this.updateHandler_),this.track_.addEventListener("cuechange",this.selectCurrentItem_)}}}findChaptersTrack(){const e=this.player_.textTracks()||[];for(let t=e.length-1;t>=0;t--){const i=e[t];if(i.kind===this.kind_)return i}}getMenuCaption(){return this.track_&&this.track_.label?this.track_.label:this.localize(xs(this.kind_))}createMenu(){return this.options_.title=this.getMenuCaption(),super.createMenu()}createItems(){const e=[];if(!this.track_)return e;const t=this.track_.cues;if(!t)return e;for(let i=0,n=t.length;i-1&&(this.label_="captions",this.setIcon("captions")),this.menuButton_.controlText(xs(this.label_))}buildCSSClass(){return`vjs-subs-caps-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-subs-caps-button ${super.buildWrapperCSSClass()}`}createItems(){let e=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(e.push(new yb(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,jC),e}}xb.prototype.kinds_=["captions","subtitles"];xb.prototype.controlText_="Subtitles";Ue.registerComponent("SubsCapsButton",xb);class $C extends Lh{constructor(e,t){const i=t.track,n=e.audioTracks();t.label=i.label||i.language||"Unknown",t.selected=i.enabled,super(e,t),this.track=i,this.addClass(`vjs-${i.kind}-menu-item`);const r=(...o)=>{this.handleTracksChange.apply(this,o)};n.addEventListener("change",r),this.on("dispose",()=>{n.removeEventListener("change",r)})}createEl(e,t,i){const n=super.createEl(e,t,i),r=n.querySelector(".vjs-menu-item-text");return["main-desc","descriptions"].indexOf(this.options_.track.kind)>=0&&(r.appendChild($t("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild($t("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),n}handleClick(e){if(super.handleClick(e),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks){const t=this.player_.audioTracks();for(let i=0;ithis.update(r))}handleClick(e){super.handleClick(),this.player().playbackRate(this.rate)}update(e){this.selected(this.player().playbackRate()===this.rate)}}bb.prototype.contentElType="button";Ue.registerComponent("PlaybackRateMenuItem",bb);class VC extends hb{constructor(e,t){super(e,t),this.menuButton_.el_.setAttribute("aria-describedby",this.labelElId_),this.updateVisibility(),this.updateLabel(),this.on(e,"loadstart",i=>this.updateVisibility(i)),this.on(e,"ratechange",i=>this.updateLabel(i)),this.on(e,"playbackrateschange",i=>this.handlePlaybackRateschange(i))}createEl(){const e=super.createEl();return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=$t("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),e.appendChild(this.labelEl_),e}dispose(){this.labelEl_=null,super.dispose()}buildCSSClass(){return`vjs-playback-rate ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-playback-rate ${super.buildWrapperCSSClass()}`}createItems(){const e=this.playbackRates(),t=[];for(let i=e.length-1;i>=0;i--)t.push(new bb(this.player(),{rate:e[i]+"x"}));return t}handlePlaybackRateschange(e){this.update()}playbackRates(){const e=this.player();return e.playbackRates&&e.playbackRates()||[]}playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0}updateVisibility(e){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")}updateLabel(e){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")}}VC.prototype.controlText_="Playback Rate";Ue.registerComponent("PlaybackRateMenuButton",VC);class GC extends Ue{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}Ue.registerComponent("Spacer",GC);class g4 extends GC{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}Ue.registerComponent("CustomControlSpacer",g4);class zC extends Ue{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}zC.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};Ue.registerComponent("ControlBar",zC);class qC extends Rc{constructor(e,t){super(e,t),this.on(e,"error",i=>{this.open(i)})}buildCSSClass(){return`vjs-error-display ${super.buildCSSClass()}`}content(){const e=this.player().error();return e?this.localize(e.message):""}}qC.prototype.options_=Object.assign({},Rc.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});Ue.registerComponent("ErrorDisplay",qC);class KC extends Ue{constructor(e,t={}){super(e,t),this.el_.setAttribute("aria-labelledby",this.selectLabelledbyIds)}createEl(){return this.selectLabelledbyIds=[this.options_.legendId,this.options_.labelId].join(" ").trim(),$t("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${dr()}`)+"-"+t[1].replace(/\W+/g,""),n=$t("option",{id:i,value:this.localize(t[0]),textContent:this.localize(t[1])});return n.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),n}))}}Ue.registerComponent("TextTrackSelect",KC);class Hl extends Ue{constructor(e,t={}){super(e,t);const i=$t("legend",{textContent:this.localize(this.options_.legendText),id:this.options_.legendId});this.el().appendChild(i);const n=this.options_.selects;for(const r of n){const o=this.options_.selectConfigs[r],u=o.className,c=o.id.replace("%s",this.options_.id_);let d=null;const f=`vjs_select_${dr()}`;if(this.options_.type==="colors"){d=$t("span",{className:u});const g=$t("label",{id:c,className:"vjs-label",textContent:this.localize(o.label)});g.setAttribute("for",f),d.appendChild(g)}const p=new KC(e,{SelectOptions:o.options,legendId:this.options_.legendId,id:f,labelId:c});this.addChild(p),this.options_.type==="colors"&&(d.appendChild(p.el()),this.el().appendChild(d))}}createEl(){return $t("fieldset",{className:this.options_.className})}}Ue.registerComponent("TextTrackFieldset",Hl);class YC extends Ue{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new Hl(e,{id_:i,legendId:`captions-text-legend-${i}`,legendText:this.localize("Text"),className:"vjs-fg vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(n);const r=new Hl(e,{id_:i,legendId:`captions-background-${i}`,legendText:this.localize("Text Background"),className:"vjs-bg vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(r);const o=new Hl(e,{id_:i,legendId:`captions-window-${i}`,legendText:this.localize("Caption Area Background"),className:"vjs-window vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(o)}createEl(){return $t("div",{className:"vjs-track-settings-colors"})}}Ue.registerComponent("TextTrackSettingsColors",YC);class WC extends Ue{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new Hl(e,{id_:i,legendId:`captions-font-size-${i}`,legendText:"Font Size",className:"vjs-font-percent vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(n);const r=new Hl(e,{id_:i,legendId:`captions-edge-style-${i}`,legendText:this.localize("Text Edge Style"),className:"vjs-edge-style vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(r);const o=new Hl(e,{id_:i,legendId:`captions-font-family-${i}`,legendText:this.localize("Font Family"),className:"vjs-font-family vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(o)}createEl(){return $t("div",{className:"vjs-track-settings-font"})}}Ue.registerComponent("TextTrackSettingsFont",WC);class XC extends Ue{constructor(e,t={}){super(e,t);const i=new ln(e,{controlText:this.localize("restore all settings to the default values"),className:"vjs-default-button"});i.el().classList.remove("vjs-control","vjs-button"),i.el().textContent=this.localize("Reset"),this.addChild(i);const n=this.localize("Done"),r=new ln(e,{controlText:n,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=n,this.addChild(r)}createEl(){return $t("div",{className:"vjs-track-settings-controls"})}}Ue.registerComponent("TrackSettingsControls",XC);const Vy="vjs-text-track-settings",CE=["#000","Black"],kE=["#00F","Blue"],DE=["#0FF","Cyan"],LE=["#0F0","Green"],RE=["#F0F","Magenta"],IE=["#F00","Red"],NE=["#FFF","White"],OE=["#FF0","Yellow"],Gy=["1","Opaque"],zy=["0.5","Semi-Transparent"],ME=["0","Transparent"],Uo={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[CE,NE,IE,LE,kE,OE,RE,DE],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[Gy,zy,ME],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[NE,CE,IE,LE,kE,OE,RE,DE],className:"vjs-text-color"},edgeStyle:{selector:".vjs-edge-style > select",id:"",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Drop shadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"",label:"Font Family",options:[["proportionalSansSerif","Proportional Sans-Serif"],["monospaceSansSerif","Monospace Sans-Serif"],["proportionalSerif","Proportional Serif"],["monospaceSerif","Monospace Serif"],["casual","Casual"],["script","Script"],["small-caps","Small Caps"]]},fontPercent:{selector:".vjs-font-percent > select",id:"",label:"Font Size",options:[["0.50","50%"],["0.75","75%"],["1.00","100%"],["1.25","125%"],["1.50","150%"],["1.75","175%"],["2.00","200%"],["3.00","300%"],["4.00","400%"]],default:2,parser:s=>s==="1.00"?null:Number(s)},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Opacity",options:[Gy,zy],className:"vjs-text-opacity vjs-opacity"},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color",className:"vjs-window-color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Opacity",options:[ME,zy,Gy],className:"vjs-window-opacity vjs-opacity"}};Uo.windowColor.options=Uo.backgroundColor.options;function QC(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function y4(s,e){const t=s.options[s.options.selectedIndex].value;return QC(t,e)}function v4(s,e,t){if(e){for(let i=0;i{this.saveSettings(),this.close()}),this.on(this.$(".vjs-default-button"),["click","tap"],()=>{this.setDefaults(),this.updateDisplay()}),ec(Uo,e=>{this.on(this.$(e.selector),"change",this.updateDisplay)})}dispose(){this.endDialog=null,super.dispose()}label(){return this.localize("Caption Settings Dialog")}description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")}buildCSSClass(){return super.buildCSSClass()+" vjs-text-track-settings"}getValues(){return jA(Uo,(e,t,i)=>{const n=y4(this.$(t.selector),t.parser);return n!==void 0&&(e[i]=n),e},{})}setValues(e){ec(Uo,(t,i)=>{v4(this.$(t.selector),e[i],t.parser)})}setDefaults(){ec(Uo,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(ue.localStorage.getItem(Vy))}catch(t){ui.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?ue.localStorage.setItem(Vy,JSON.stringify(e)):ue.localStorage.removeItem(Vy)}catch(t){ui.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}Ue.registerComponent("TextTrackSettings",x4);class b4 extends Ue{constructor(e,t){let i=t.ResizeObserver||ue.ResizeObserver;t.ResizeObserver===null&&(i=!1);const n=ji({createEl:!i,reportTouchActivity:!1},t);super(e,n),this.ResizeObserver=t.ResizeObserver||ue.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=uC(()=>{this.resizeHandler()},100,!1,this),i?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(e.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;const r=this.debouncedHandler_;let o=this.unloadListener_=function(){on(this,"resize",r),on(this,"unload",o),o=null};tr(this.el_.contentWindow,"unload",o),tr(this.el_.contentWindow,"resize",r)},this.one("load",this.loadListener_))}createEl(){return super.createEl("iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No content")},{"aria-hidden":"true"})}resizeHandler(){!this.player_||!this.player_.trigger||this.player_.trigger("playerresize")}dispose(){this.debouncedHandler_&&this.debouncedHandler_.cancel(),this.resizeObserver_&&(this.player_.el()&&this.resizeObserver_.unobserve(this.player_.el()),this.resizeObserver_.disconnect()),this.loadListener_&&this.off("load",this.loadListener_),this.el_&&this.el_.contentWindow&&this.unloadListener_&&this.unloadListener_.call(this.el_.contentWindow),this.ResizeObserver=null,this.resizeObserver=null,this.debouncedHandler_=null,this.loadListener_=null,super.dispose()}}Ue.registerComponent("ResizeManager",b4);const T4={trackingThreshold:20,liveTolerance:15};class _4 extends Ue{constructor(e,t){const i=ji(T4,t,{createEl:!1});super(e,i),this.trackLiveHandler_=()=>this.trackLive_(),this.handlePlay_=n=>this.handlePlay(n),this.handleFirstTimeupdate_=n=>this.handleFirstTimeupdate(n),this.handleSeeked_=n=>this.handleSeeked(n),this.seekToLiveEdge_=n=>this.seekToLiveEdge(n),this.reset_(),this.on(this.player_,"durationchange",n=>this.handleDurationchange(n)),this.on(this.player_,"canplay",()=>this.toggleTracking())}trackLive_(){const e=this.player_.seekable();if(!e||!e.length)return;const t=Number(ue.performance.now().toFixed(4)),i=this.lastTime_===-1?0:(t-this.lastTime_)/1e3;this.lastTime_=t,this.pastSeekEnd_=this.pastSeekEnd()+i;const n=this.liveCurrentTime(),r=this.player_.currentTime();let o=this.player_.paused()||this.seekedBehindLive_||Math.abs(n-r)>this.options_.liveTolerance;(!this.timeupdateSeen_||n===1/0)&&(o=!1),o!==this.behindLiveEdge_&&(this.behindLiveEdge_=o,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,hr),this.trackLive_(),this.on(this.player_,["play","pause"],this.trackLiveHandler_),this.timeupdateSeen_?this.on(this.player_,"seeked",this.handleSeeked_):(this.one(this.player_,"play",this.handlePlay_),this.one(this.player_,"timeupdate",this.handleFirstTimeupdate_)))}handleFirstTimeupdate(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)}handleSeeked(){const e=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&e>2,this.nextSeekedFromUser_=!1,this.trackLive_()}handlePlay(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)}reset_(){this.lastTime_=-1,this.pastSeekEnd_=0,this.lastSeekEnd_=-1,this.behindLiveEdge_=!0,this.timeupdateSeen_=!1,this.seekedBehindLive_=!1,this.nextSeekedFromUser_=!1,this.clearInterval(this.trackingInterval_),this.trackingInterval_=null,this.off(this.player_,["play","pause"],this.trackLiveHandler_),this.off(this.player_,"seeked",this.handleSeeked_),this.off(this.player_,"play",this.handlePlay_),this.off(this.player_,"timeupdate",this.handleFirstTimeupdate_),this.off(this.player_,"timeupdate",this.seekToLiveEdge_)}nextSeekedFromUser(){this.nextSeekedFromUser_=!0}stopTracking(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))}seekableEnd(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.end(i));return t.length?t.sort()[t.length-1]:1/0}seekableStart(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.start(i));return t.length?t.sort()[0]:0}liveWindow(){const e=this.liveCurrentTime();return e===1/0?0:e-this.seekableStart()}isLive(){return this.isTracking()}atLiveEdge(){return!this.behindLiveEdge()}liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd()}pastSeekEnd(){const e=this.seekableEnd();return this.lastSeekEnd_!==-1&&e!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=e,this.pastSeekEnd_}behindLiveEdge(){return this.behindLiveEdge_}isTracking(){return typeof this.trackingInterval_=="number"}seekToLiveEdge(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))}dispose(){this.stopTracking(),super.dispose()}}Ue.registerComponent("LiveTracker",_4);class S4 extends Ue{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:$t("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${dr()}`}),description:$t("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${dr()}`})},$t("div",{className:"vjs-title-bar"},{},$A(this.els))}updateDom_(){const e=this.player_.tech_,t=e&&e.el_,i={title:"aria-labelledby",description:"aria-describedby"};["title","description"].forEach(n=>{const r=this.state[n],o=this.els[n],u=i[n];Qp(o),r&&Zo(o,r),t&&(t.removeAttribute(u),r&&t.setAttribute(u,o.id))}),this.state.title||this.state.description?this.show():this.hide()}update(e){this.setState(e)}dispose(){const e=this.player_.tech_,t=e&&e.el_;t&&(t.removeAttribute("aria-labelledby"),t.removeAttribute("aria-describedby")),super.dispose(),this.els=null}}Ue.registerComponent("TitleBar",S4);const E4={initialDisplay:4e3,position:[],takeFocus:!1};class w4 extends ln{constructor(e,t){t=ji(E4,t),super(e,t),this.controlText(t.controlText),this.hide(),this.on(this.player_,["useractive","userinactive"],i=>{this.removeClass("force-display")})}buildCSSClass(){return`vjs-transient-button focus-visible ${this.options_.position.map(e=>`vjs-${e}`).join(" ")}`}createEl(){const e=$t("button",{},{type:"button",class:this.buildCSSClass()},$t("span"));return this.controlTextEl_=e.querySelector("span"),e}show(){super.show(),this.addClass("force-display"),this.options_.takeFocus&&this.el().focus({preventScroll:!0}),this.forceDisplayTimeout=this.player_.setTimeout(()=>{this.removeClass("force-display")},this.options_.initialDisplay)}hide(){this.removeClass("force-display"),super.hide()}dispose(){this.player_.clearTimeout(this.forceDisplayTimeout),super.dispose()}}Ue.registerComponent("TransientButton",w4);const Zv=s=>{const e=s.el();if(e.hasAttribute("src"))return s.triggerSourceset(e.src),!0;const t=s.$$("source"),i=[];let n="";if(!t.length)return!1;for(let r=0;r{let t={};for(let i=0;iZC([s.el(),ue.HTMLMediaElement.prototype,ue.Element.prototype,A4],"innerHTML"),PE=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=C4(s),n=r=>(...o)=>{const u=r.apply(e,o);return Zv(s),u};["append","appendChild","insertAdjacentHTML"].forEach(r=>{e[r]&&(t[r]=e[r],e[r]=n(t[r]))}),Object.defineProperty(e,"innerHTML",ji(i,{set:n(i.set)})),e.resetSourceWatch_=()=>{e.resetSourceWatch_=null,Object.keys(t).forEach(r=>{e[r]=t[r]}),Object.defineProperty(e,"innerHTML",i)},s.one("sourceset",e.resetSourceWatch_)},k4=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?bC(ue.Element.prototype.getAttribute.call(this,"src")):""},set(s){return ue.Element.prototype.setAttribute.call(this,"src",s),s}}),D4=s=>ZC([s.el(),ue.HTMLMediaElement.prototype,k4],"src"),L4=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=D4(s),i=e.setAttribute,n=e.load;Object.defineProperty(e,"src",ji(t,{set:r=>{const o=t.set.call(e,r);return s.triggerSourceset(e.src),o}})),e.setAttribute=(r,o)=>{const u=i.call(e,r,o);return/src/i.test(r)&&s.triggerSourceset(e.src),u},e.load=()=>{const r=n.call(e);return Zv(s)||(s.triggerSourceset(""),PE(s)),r},e.currentSrc?s.triggerSourceset(e.currentSrc):Zv(s)||PE(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=n,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class xt extends ii{constructor(e,t){super(e,t);const i=e.source;let n=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&this.el_.tagName==="VIDEO",i&&(this.el_.currentSrc!==i.src||e.tag&&e.tag.initNetworkState_===3)?this.setSource(i):this.handleLateInit_(this.el_),e.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){const r=this.el_.childNodes;let o=r.length;const u=[];for(;o--;){const c=r[o];c.nodeName.toLowerCase()==="track"&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(c),this.remoteTextTracks().addTrack(c.track),this.textTracks().addTrack(c.track),!n&&!this.el_.hasAttribute("crossorigin")&&t0(c.src)&&(n=!0)):u.push(c))}for(let c=0;c{t=[];for(let r=0;re.removeEventListener("change",i));const n=()=>{for(let r=0;r{e.removeEventListener("change",i),e.removeEventListener("change",n),e.addEventListener("change",n)}),this.on("webkitendfullscreen",()=>{e.removeEventListener("change",i),e.addEventListener("change",i),e.removeEventListener("change",n)})}overrideNative_(e,t){if(t!==this[`featuresNative${e}Tracks`])return;const i=e.toLowerCase();this[`${i}TracksListeners_`]&&Object.keys(this[`${i}TracksListeners_`]).forEach(n=>{this.el()[`${i}Tracks`].removeEventListener(n,this[`${i}TracksListeners_`][n])}),this[`featuresNative${e}Tracks`]=!t,this[`${i}TracksListeners_`]=null,this.proxyNativeTracksForType_(i)}overrideNativeAudioTracks(e){this.overrideNative_("Audio",e)}overrideNativeVideoTracks(e){this.overrideNative_("Video",e)}proxyNativeTracksForType_(e){const t=cr[e],i=this.el()[t.getterName],n=this[t.getterName]();if(!this[`featuresNative${t.capitalName}Tracks`]||!i||!i.addEventListener)return;const r={change:u=>{const c={type:"change",target:n,currentTarget:n,srcElement:n};n.trigger(c),e==="text"&&this[Sc.remoteText.getterName]().trigger(c)},addtrack(u){n.addTrack(u.track)},removetrack(u){n.removeTrack(u.track)}},o=function(){const u=[];for(let c=0;c{const c=r[u];i.addEventListener(u,c),this.on("dispose",d=>i.removeEventListener(u,c))}),this.on("loadstart",o),this.on("dispose",u=>this.off("loadstart",o))}proxyNativeTracks_(){cr.names.forEach(e=>{this.proxyNativeTracksForType_(e)})}createEl(){let e=this.options_.tag;if(!e||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(e){const i=e.cloneNode(!0);e.parentNode&&e.parentNode.insertBefore(i,e),xt.disposeMediaElement(e),e=i}else{e=st.createElement("video");const i=this.options_.tag&&Fo(this.options_.tag),n=ji({},i);(!hh||this.options_.nativeControlsForTouch!==!0)&&delete n.controls,XA(e,Object.assign(n,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&bc(e,"preload",this.options_.preload),this.options_.disablePictureInPicture!==void 0&&(e.disablePictureInPicture=this.options_.disablePictureInPicture);const t=["loop","muted","playsinline","autoplay"];for(let i=0;i=2&&t.push("loadeddata"),e.readyState>=3&&t.push("canplay"),e.readyState>=4&&t.push("canplaythrough"),this.ready(function(){t.forEach(function(i){this.trigger(i)},this)})}setScrubbing(e){this.isScrubbing_=e}scrubbing(){return this.isScrubbing_}setCurrentTime(e){try{this.isScrubbing_&&this.el_.fastSeek&&Kp?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){ui(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&Dr&&ca&&this.el_.currentTime===0){const e=()=>{this.el_.currentTime>0&&(this.el_.duration===1/0&&this.trigger("durationchange"),this.off("timeupdate",e))};return this.on("timeupdate",e),NaN}return this.el_.duration||NaN}width(){return this.el_.offsetWidth}height(){return this.el_.offsetHeight}proxyWebkitFullscreen_(){if(!("webkitDisplayingFullscreen"in this.el_))return;const e=function(){this.trigger("fullscreenchange",{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},t=function(){"webkitPresentationMode"in this.el_&&this.el_.webkitPresentationMode!=="picture-in-picture"&&(this.one("webkitendfullscreen",e),this.trigger("fullscreenchange",{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on("webkitbeginfullscreen",t),this.on("dispose",()=>{this.off("webkitbeginfullscreen",t),this.off("webkitendfullscreen",e)})}supportsFullScreen(){return typeof this.el_.webkitEnterFullScreen=="function"}enterFullScreen(){const e=this.el_;if(e.paused&&e.networkState<=e.HAVE_METADATA)ta(this.el_.play()),this.setTimeout(function(){e.pause();try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}},0);else try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}}exitFullScreen(){if(!this.el_.webkitDisplayingFullscreen){this.trigger("fullscreenerror",new Error("The video is not fullscreen"));return}this.el_.webkitExitFullScreen()}requestPictureInPicture(){return this.el_.requestPictureInPicture()}requestVideoFrameCallback(e){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(e):super.requestVideoFrameCallback(e)}cancelVideoFrameCallback(e){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(e):super.cancelVideoFrameCallback(e)}src(e){if(e===void 0)return this.el_.src;this.setSrc(e)}addSourceElement(e,t){if(!e)return ui.error("Invalid source URL."),!1;const i={src:e};t&&(i.type=t);const n=$t("source",{},i);return this.el_.appendChild(n),!0}removeSourceElement(e){if(!e)return ui.error("Source URL is required to remove the source element."),!1;const t=this.el_.querySelectorAll("source");for(const i of t)if(i.src===e)return this.el_.removeChild(i),!0;return ui.warn(`No matching source element found with src: ${e}`),!1}reset(){xt.resetMediaElement(this.el_)}currentSrc(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc}setControls(e){this.el_.controls=!!e}addTextTrack(e,t,i){return this.featuresNativeTextTracks?this.el_.addTextTrack(e,t,i):super.addTextTrack(e,t,i)}createRemoteTextTrack(e){if(!this.featuresNativeTextTracks)return super.createRemoteTextTrack(e);const t=st.createElement("track");return e.kind&&(t.kind=e.kind),e.label&&(t.label=e.label),(e.language||e.srclang)&&(t.srclang=e.language||e.srclang),e.default&&(t.default=e.default),e.id&&(t.id=e.id),e.src&&(t.src=e.src),t}addRemoteTextTrack(e,t){const i=super.addRemoteTextTrack(e,t);return this.featuresNativeTextTracks&&this.el().appendChild(i),i}removeRemoteTextTrack(e){if(super.removeRemoteTextTrack(e),this.featuresNativeTextTracks){const t=this.$$("track");let i=t.length;for(;i--;)(e===t[i]||e===t[i].track)&&this.el().removeChild(t[i])}}getVideoPlaybackQuality(){if(typeof this.el().getVideoPlaybackQuality=="function")return this.el().getVideoPlaybackQuality();const e={};return typeof this.el().webkitDroppedFrameCount<"u"&&typeof this.el().webkitDecodedFrameCount<"u"&&(e.droppedVideoFrames=this.el().webkitDroppedFrameCount,e.totalVideoFrames=this.el().webkitDecodedFrameCount),ue.performance&&(e.creationTime=ue.performance.now()),e}}Vp(xt,"TEST_VID",function(){if(!kc())return;const s=st.createElement("video"),e=st.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});xt.isSupported=function(){try{xt.TEST_VID.volume=.5}catch{return!1}return!!(xt.TEST_VID&&xt.TEST_VID.canPlayType)};xt.canPlayType=function(s){return xt.TEST_VID.canPlayType(s)};xt.canPlaySource=function(s,e){return xt.canPlayType(s.type)};xt.canControlVolume=function(){try{const s=xt.TEST_VID.volume;xt.TEST_VID.volume=s/2+.1;const e=s!==xt.TEST_VID.volume;return e&&an?(ue.setTimeout(()=>{xt&&xt.prototype&&(xt.prototype.featuresVolumeControl=s!==xt.TEST_VID.volume)}),!1):e}catch{return!1}};xt.canMuteVolume=function(){try{const s=xt.TEST_VID.muted;return xt.TEST_VID.muted=!s,xt.TEST_VID.muted?bc(xt.TEST_VID,"muted","muted"):Wp(xt.TEST_VID,"muted","muted"),s!==xt.TEST_VID.muted}catch{return!1}};xt.canControlPlaybackRate=function(){if(Dr&&ca&&Gp<58)return!1;try{const s=xt.TEST_VID.playbackRate;return xt.TEST_VID.playbackRate=s/2+.1,s!==xt.TEST_VID.playbackRate}catch{return!1}};xt.canOverrideAttributes=function(){try{const s=()=>{};Object.defineProperty(st.createElement("video"),"src",{get:s,set:s}),Object.defineProperty(st.createElement("audio"),"src",{get:s,set:s}),Object.defineProperty(st.createElement("video"),"innerHTML",{get:s,set:s}),Object.defineProperty(st.createElement("audio"),"innerHTML",{get:s,set:s})}catch{return!1}return!0};xt.supportsNativeTextTracks=function(){return Kp||an&&ca};xt.supportsNativeVideoTracks=function(){return!!(xt.TEST_VID&&xt.TEST_VID.videoTracks)};xt.supportsNativeAudioTracks=function(){return!!(xt.TEST_VID&&xt.TEST_VID.audioTracks)};xt.Events=["loadstart","suspend","abort","error","emptied","stalled","loadedmetadata","loadeddata","canplay","canplaythrough","playing","waiting","seeking","seeked","ended","durationchange","timeupdate","progress","play","pause","ratechange","resize","volumechange"];[["featuresMuteControl","canMuteVolume"],["featuresPlaybackRate","canControlPlaybackRate"],["featuresSourceset","canOverrideAttributes"],["featuresNativeTextTracks","supportsNativeTextTracks"],["featuresNativeVideoTracks","supportsNativeVideoTracks"],["featuresNativeAudioTracks","supportsNativeAudioTracks"]].forEach(function([s,e]){Vp(xt.prototype,s,()=>xt[e](),!0)});xt.prototype.featuresVolumeControl=xt.canControlVolume();xt.prototype.movingMediaElementInDOM=!an;xt.prototype.featuresFullscreenResize=!0;xt.prototype.featuresProgressEvents=!0;xt.prototype.featuresTimeupdateEvents=!0;xt.prototype.featuresVideoFrameCallback=!!(xt.TEST_VID&&xt.TEST_VID.requestVideoFrameCallback);xt.disposeMediaElement=function(s){if(s){for(s.parentNode&&s.parentNode.removeChild(s);s.hasChildNodes();)s.removeChild(s.firstChild);s.removeAttribute("src"),typeof s.load=="function"&&(function(){try{s.load()}catch{}})()}};xt.resetMediaElement=function(s){if(!s)return;const e=s.querySelectorAll("source");let t=e.length;for(;t--;)s.removeChild(e[t]);s.removeAttribute("src"),typeof s.load=="function"&&(function(){try{s.load()}catch{}})()};["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach(function(s){xt.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){xt.prototype["set"+xs(s)]=function(e){this.el_[s]=e,e?this.el_.setAttribute(s,s):this.el_.removeAttribute(s)}});["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach(function(s){xt.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){xt.prototype["set"+xs(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){xt.prototype[s]=function(){return this.el_[s]()}});ii.withSourceHandlers(xt);xt.nativeSourceHandler={};xt.nativeSourceHandler.canPlayType=function(s){try{return xt.TEST_VID.canPlayType(s)}catch{return""}};xt.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return xt.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=rb(s.src);return xt.nativeSourceHandler.canPlayType(`video/${t}`)}return""};xt.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};xt.nativeSourceHandler.dispose=function(){};xt.registerSourceHandler(xt.nativeSourceHandler);ii.registerTech("Html5",xt);const JC=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],qy={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},Jv=["tiny","xsmall","small","medium","large","xlarge","huge"],Nm={};Jv.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;Nm[s]=`vjs-layout-${e}`});const R4={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let us=class qu extends Ue{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${dr()}`,t=Object.assign(qu.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const o=e.closest("[lang]");o&&(t.language=o.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=o=>this.documentFullscreenChange_(o),this.boundFullWindowOnEscKey_=o=>this.fullWindowOnEscKey(o),this.boundUpdateStyleEl_=o=>this.updateStyleEl_(o),this.boundApplyInitTime_=o=>this.applyInitTime_(o),this.boundUpdateCurrentBreakpoint_=o=>this.updateCurrentBreakpoint_(o),this.boundHandleTechClick_=o=>this.handleTechClick_(o),this.boundHandleTechDoubleClick_=o=>this.handleTechDoubleClick_(o),this.boundHandleTechTouchStart_=o=>this.handleTechTouchStart_(o),this.boundHandleTechTouchMove_=o=>this.handleTechTouchMove_(o),this.boundHandleTechTouchEnd_=o=>this.handleTechTouchEnd_(o),this.boundHandleTechTap_=o=>this.handleTechTap_(o),this.boundUpdatePlayerHeightOnAudioOnlyMode_=o=>this.updatePlayerHeightOnAudioOnlyMode_(o),this.isFullscreen_=!1,this.log=FA(this.id_),this.fsApi_=Qm,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={controlBarHeight:null,playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(this.tag=e,this.tagAttributes=e&&Fo(e),this.language(this.options_.language),t.languages){const o={};Object.getOwnPropertyNames(t.languages).forEach(function(u){o[u.toLowerCase()]=t.languages[u]}),this.languages_=o}else this.languages_=qu.prototype.options_.languages;this.resetCache_(),this.poster_=t.poster||"",this.controls_=!!t.controls,e.controls=!1,e.removeAttribute("controls"),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],e.hasAttribute("autoplay")?this.autoplay(!0):this.autoplay(this.options_.autoplay),t.plugins&&Object.keys(t.plugins).forEach(o=>{if(typeof this[o]!="function")throw new Error(`plugin "${o}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),eb(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(tr(st,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const n=ji(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(o=>{this[o](t.plugins[o])}),t.debug&&this.debug(!0),this.options_.playerOptions=n,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const u=new ue.DOMParser().parseFromString(e4,"image/svg+xml");if(u.querySelector("parsererror"))ui.warn("Failed to load SVG Icons. Falling back to Font Icons."),this.options_.experimentalSvgIcons=null;else{const d=u.documentElement;d.style.display="none",this.el_.appendChild(d),this.addClass("vjs-svg-icons-enabled")}}this.initChildren(),this.isAudio(e.nodeName.toLowerCase()==="audio"),this.controls()?this.addClass("vjs-controls-enabled"):this.addClass("vjs-controls-disabled"),this.el_.setAttribute("role","region"),this.isAudio()?this.el_.setAttribute("aria-label",this.localize("Audio Player")):this.el_.setAttribute("aria-label",this.localize("Video Player")),this.isAudio()&&this.addClass("vjs-audio"),t.spatialNavigation&&t.spatialNavigation.enabled&&(this.spatialNavigation=new t4(this),this.addClass("vjs-spatial-navigation-enabled")),hh&&this.addClass("vjs-touch-enabled"),an||this.addClass("vjs-workinghover"),qu.players[this.id_]=this;const r=Hv.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",o=>this.listenForUserActivity_(o)),this.on("keydown",o=>this.handleKeyDown(o)),this.on("languagechange",o=>this.handleLanguagechange(o)),this.breakpoints(this.options_.breakpoints),this.responsive(this.options_.responsive),this.on("ready",()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)})}dispose(){this.trigger("dispose"),this.off("dispose"),on(st,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),on(st,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),qu.players[this.id_]=null,this.tag&&this.tag.player&&(this.tag.player=null),this.el_&&this.el_.player&&(this.el_.player=null),this.tech_&&(this.tech_.dispose(),this.isPosterFromTech_=!1,this.poster_=""),this.playerElIngest_&&(this.playerElIngest_=null),this.tag&&(this.tag=null),X3(this),pn.names.forEach(e=>{const t=pn[e],i=this[t.getterName]();i&&i.off&&i.off()}),super.dispose({restoreEl:this.options_.restoreEl})}createEl(){let e=this.tag,t,i=this.playerElIngest_=e.parentNode&&e.parentNode.hasAttribute&&e.parentNode.hasAttribute("data-vjs-player");const n=this.tag.tagName.toLowerCase()==="video-js";i?t=this.el_=e.parentNode:n||(t=this.el_=super.createEl("div"));const r=Fo(e);if(n){for(t=this.el_=e,e=this.tag=st.createElement("video");t.children.length;)e.appendChild(t.firstChild);th(t,"video-js")||jl(t,"video-js"),t.appendChild(e),i=this.playerElIngest_=t,Object.keys(t).forEach(c=>{try{e[c]=t[c]}catch{}})}e.setAttribute("tabindex","-1"),r.tabindex="-1",ca&&zp&&(e.setAttribute("role","application"),r.role="application"),e.removeAttribute("width"),e.removeAttribute("height"),"width"in r&&delete r.width,"height"in r&&delete r.height,Object.getOwnPropertyNames(r).forEach(function(c){n&&c==="class"||t.setAttribute(c,r[c]),n&&e.setAttribute(c,r[c])}),e.playerId=e.id,e.id+="_html5_api",e.className="vjs-tech",e.player=t.player=this,this.addClass("vjs-paused");const o=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(c=>qA[c]).map(c=>"vjs-device-"+c.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...o),ue.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=oC("vjs-styles-dimensions");const c=Wo(".vjs-styles-defaults"),d=Wo("head");d.insertBefore(this.styleEl_,c?c.nextSibling:d.firstChild)}this.fill_=!1,this.fluid_=!1,this.width(this.options_.width),this.height(this.options_.height),this.fill(this.options_.fill),this.fluid(this.options_.fluid),this.aspectRatio(this.options_.aspectRatio),this.crossOrigin(this.options_.crossOrigin||this.options_.crossorigin);const u=e.getElementsByTagName("a");for(let c=0;c"u")return this.techGet_("crossOrigin");if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){ui.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.techCall_("setCrossOrigin",e),this.posterImage&&this.posterImage.crossOrigin(e)}width(e){return this.dimension("width",e)}height(e){return this.dimension("height",e)}dimension(e,t){const i=e+"_";if(t===void 0)return this[i]||0;if(t===""||t==="auto"){this[i]=void 0,this.updateStyleEl_();return}const n=parseFloat(t);if(isNaN(n)){ui.error(`Improper value "${t}" supplied for for ${e}`);return}this[i]=n,this.updateStyleEl_()}fluid(e){if(e===void 0)return!!this.fluid_;this.fluid_=!!e,Va(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),k3(this,()=>{this.on(["playerreset","resize"],this.boundUpdateStyleEl_)})):this.removeClass("vjs-fluid"),this.updateStyleEl_()}fill(e){if(e===void 0)return!!this.fill_;this.fill_=!!e,e?(this.addClass("vjs-fill"),this.fluid(!1)):this.removeClass("vjs-fill")}aspectRatio(e){if(e===void 0)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(e))throw new Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");this.aspectRatio_=e,this.fluid(!0),this.updateStyleEl_()}updateStyleEl_(){if(ue.VIDEOJS_NO_DYNAMIC_STYLE===!0){const u=typeof this.width_=="number"?this.width_:this.options_.width,c=typeof this.height_=="number"?this.height_:this.options_.height,d=this.tech_&&this.tech_.el();d&&(u>=0&&(d.width=u),c>=0&&(d.height=c));return}let e,t,i,n;this.aspectRatio_!==void 0&&this.aspectRatio_!=="auto"?i=this.aspectRatio_:this.videoWidth()>0?i=this.videoWidth()+":"+this.videoHeight():i="16:9";const r=i.split(":"),o=r[1]/r[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/o:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*o,/^[^a-zA-Z]/.test(this.id())?n="dimensions-"+this.id():n=this.id()+"-dimensions",this.addClass(n),lC(this.styleEl_,` + .${n} { + width: ${e}px; + height: ${t}px; + } + + .${n}.vjs-fluid:not(.vjs-audio-only-mode) { + padding-top: ${o*100}%; + } + `)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=xs(e),n=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(ii.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=i,this.isReady_=!1;let r=this.autoplay();(typeof this.autoplay()=="string"||this.autoplay()===!0&&this.options_.normalizeAutoplay)&&(r=!1);const o={source:t,autoplay:r,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:`${this.id()}_${n}_api`,playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,disablePictureInPicture:this.options_.disablePictureInPicture,muted:this.options_.muted,poster:this.poster(),language:this.language(),playerElIngest:this.playerElIngest_||!1,"vtt.js":this.options_["vtt.js"],canOverridePoster:!!this.options_.techCanOverridePoster,enableSourceset:this.options_.enableSourceset};pn.names.forEach(c=>{const d=pn[c];o[d.getterName]=this[d.privateName]}),Object.assign(o,this.options_[i]),Object.assign(o,this.options_[n]),Object.assign(o,this.options_[e.toLowerCase()]),this.tag&&(o.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(o.startTime=this.cache_.currentTime);const u=ii.getTech(e);if(!u)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new u(o),this.tech_.ready(Zi(this,this.handleTechReady_),!0),Xv.jsonToTextTracks(this.textTracksJson_||[],this.tech_),JC.forEach(c=>{this.on(this.tech_,c,d=>this[`handleTech${xs(c)}_`](d))}),Object.keys(qy).forEach(c=>{this.on(this.tech_,c,d=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${qy[c]}_`].bind(this),event:d});return}this[`handleTech${qy[c]}_`](d)})}),this.on(this.tech_,"loadstart",c=>this.handleTechLoadStart_(c)),this.on(this.tech_,"sourceset",c=>this.handleTechSourceset_(c)),this.on(this.tech_,"waiting",c=>this.handleTechWaiting_(c)),this.on(this.tech_,"ended",c=>this.handleTechEnded_(c)),this.on(this.tech_,"seeking",c=>this.handleTechSeeking_(c)),this.on(this.tech_,"play",c=>this.handleTechPlay_(c)),this.on(this.tech_,"pause",c=>this.handleTechPause_(c)),this.on(this.tech_,"durationchange",c=>this.handleTechDurationChange_(c)),this.on(this.tech_,"fullscreenchange",(c,d)=>this.handleTechFullscreenChange_(c,d)),this.on(this.tech_,"fullscreenerror",(c,d)=>this.handleTechFullscreenError_(c,d)),this.on(this.tech_,"enterpictureinpicture",c=>this.handleTechEnterPictureInPicture_(c)),this.on(this.tech_,"leavepictureinpicture",c=>this.handleTechLeavePictureInPicture_(c)),this.on(this.tech_,"error",c=>this.handleTechError_(c)),this.on(this.tech_,"posterchange",c=>this.handleTechPosterChange_(c)),this.on(this.tech_,"textdata",c=>this.handleTechTextData_(c)),this.on(this.tech_,"ratechange",c=>this.handleTechRateChange_(c)),this.on(this.tech_,"loadedmetadata",this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_("controls")),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode!==this.el()&&(i!=="Html5"||!this.tag)&&Gv(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){pn.names.forEach(e=>{const t=pn[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=Xv.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1}tech(e){return e===void 0&&ui.warn(`Using the tech directly can be dangerous. I hope you know what you're doing. +See https://github.com/videojs/video.js/issues/2617 for more info. +`),this.tech_}version(){return{"video.js":Hv}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,"click",this.boundHandleTechClick_),this.on(this.tech_,"dblclick",this.boundHandleTechDoubleClick_),this.on(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.on(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.on(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.on(this.tech_,"tap",this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,"tap",this.boundHandleTechTap_),this.off(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.off(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.off(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.off(this.tech_,"click",this.boundHandleTechClick_),this.off(this.tech_,"dblclick",this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass("vjs-ended","vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()?(this.hasStarted(!1),this.trigger("loadstart")):this.trigger("loadstart"),this.manualAutoplay_(this.autoplay()===!0&&this.options_.normalizeAutoplay?"play":this.autoplay())}manualAutoplay_(e){if(!this.tech_||typeof e!="string")return;const t=()=>{const n=this.muted();this.muted(!0);const r=()=>{this.muted(n)};this.playTerminatedQueue_.push(r);const o=this.play();if(sh(o))return o.catch(u=>{throw r(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${u||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),sh(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!sh(i))return i.then(()=>{this.trigger({type:"autoplay-success",autoplay:e})}).catch(()=>{this.trigger({type:"autoplay-failure",autoplay:e})})}updateSourceCaches_(e=""){let t=e,i="";typeof t!="string"&&(t=e.src,i=e.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],t&&!i&&(i=J3(this,t)),this.cache_.source=ji({},e,{src:t,type:i});const n=this.cache_.sources.filter(c=>c.src&&c.src===t),r=[],o=this.$$("source"),u=[];for(let c=0;cthis.updateSourceCaches_(r);const i=this.currentSource().src,n=e.src;i&&!/^blob:/.test(i)&&/^blob:/.test(n)&&(!this.lastSource_||this.lastSource_.tech!==n&&this.lastSource_.player!==i)&&(t=()=>{}),t(n),e.src||this.tech_.any(["sourceset","loadstart"],r=>{if(r.type==="sourceset")return;const o=this.techGet_("currentSrc");this.lastSource_.tech=o,this.updateSourceCaches_(o)})}this.lastSource_={player:this.currentSource().src,tech:e.src},this.trigger({src:e.src,type:"sourceset"})}hasStarted(e){if(e===void 0)return this.hasStarted_;e!==this.hasStarted_&&(this.hasStarted_=e,this.hasStarted_?this.addClass("vjs-has-started"):this.removeClass("vjs-has-started"))}handleTechPlay_(){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")}handleTechRateChange_(){this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0&&(this.queuedCallbacks_.forEach(e=>e.callback(e.event)),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")}handleTechWaiting_(){this.addClass("vjs-waiting"),this.trigger("waiting");const e=this.currentTime(),t=()=>{e!==this.currentTime()&&(this.removeClass("vjs-waiting"),this.off("timeupdate",t))};this.on("timeupdate",t)}handleTechCanPlay_(){this.removeClass("vjs-waiting"),this.trigger("canplay")}handleTechCanPlayThrough_(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")}handleTechPlaying_(){this.removeClass("vjs-waiting"),this.trigger("playing")}handleTechSeeking_(){this.addClass("vjs-seeking"),this.trigger("seeking")}handleTechSeeked_(){this.removeClass("vjs-seeking","vjs-ended"),this.trigger("seeked")}handleTechPause_(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")}handleTechEnded_(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")}handleTechDurationChange_(){this.duration(this.techGet_("duration"))}handleTechClick_(e){this.controls_&&(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.click===void 0||this.options_.userActions.click!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.click=="function"?this.options_.userActions.click.call(this,e):this.paused()?ta(this.play()):this.pause())}handleTechDoubleClick_(e){if(!this.controls_)return;Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"),i=>i.contains(e.target))||(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.doubleClick===void 0||this.options_.userActions.doubleClick!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.doubleClick=="function"?this.options_.userActions.doubleClick.call(this,e):this.isInPictureInPicture()&&!st.pictureInPictureElement?this.exitPictureInPicture():this.isFullscreen()?this.exitFullscreen():this.requestFullscreen())}handleTechTap_(){this.userActive(!this.userActive())}handleTechTouchStart_(){this.userWasActive=this.userActive()}handleTechTouchMove_(){this.userWasActive&&this.reportUserActivity()}handleTechTouchEnd_(e){e.cancelable&&e.preventDefault()}toggleFullscreenClass_(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")}documentFullscreenChange_(e){const t=e.target.player;if(t&&t!==this)return;const i=this.el();let n=st[this.fsApi_.fullscreenElement]===i;!n&&i.matches&&(n=i.matches(":"+this.fsApi_.fullscreen)),this.isFullscreen(n)}handleTechFullscreenChange_(e,t){t&&(t.nativeIOSFullscreen&&(this.addClass("vjs-ios-native-fs"),this.tech_.one("webkitendfullscreen",()=>{this.removeClass("vjs-ios-native-fs")})),this.isFullscreen(t.isFullscreen))}handleTechFullscreenError_(e,t){this.trigger("fullscreenerror",t)}togglePictureInPictureClass_(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")}handleTechEnterPictureInPicture_(e){this.isInPictureInPicture(!0)}handleTechLeavePictureInPicture_(e){this.isInPictureInPicture(!1)}handleTechError_(){const e=this.tech_.error();e&&this.error(e)}handleTechTextData_(){let e=null;arguments.length>1&&(e=arguments[1]),this.trigger("textdata",e)}getCache(){return this.cache_}resetCache_(){this.cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:"",source:{},sources:[],playbackRates:[],volume:1}}techCall_(e,t){this.ready(function(){if(e in Y3)return q3(this.middleware_,this.tech_,e,t);if(e in TE)return bE(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw ui(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in K3)return z3(this.middleware_,this.tech_,e);if(e in TE)return bE(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(ui(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(ui(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(ui(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=ta){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(Kp||an);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=o=>{this.play_()},this.one(["ready","loadstart"],this.waitToPlay_),!t&&i&&this.load();return}const n=this.techGet_("play");i&&this.hasClass("vjs-ended")&&this.resetProgressBar_(),n===null?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(n)}runPlayTerminatedQueue_(){const e=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],e.forEach(function(t){t()})}runPlayCallbacks_(e){const t=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],t.forEach(function(i){i(e)})}pause(){this.techCall_("pause")}paused(){return this.techGet_("paused")!==!1}played(){return this.techGet_("played")||kr(0,0)}scrubbing(e){if(typeof e>"u")return this.scrubbing_;this.scrubbing_=!!e,this.techCall_("setScrubbing",this.scrubbing_),e?this.addClass("vjs-scrubbing"):this.removeClass("vjs-scrubbing")}currentTime(e){if(e===void 0)return this.cache_.currentTime=this.techGet_("currentTime")||0,this.cache_.currentTime;if(e<0&&(e=0),!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=e,this.off("canplay",this.boundApplyInitTime_),this.one("canplay",this.boundApplyInitTime_);return}this.techCall_("setCurrentTime",e),this.cache_.initTime=0,isFinite(e)&&(this.cache_.currentTime=Number(e))}applyInitTime_(){this.currentTime(this.cache_.initTime)}duration(e){if(e===void 0)return this.cache_.duration!==void 0?this.cache_.duration:NaN;e=parseFloat(e),e<0&&(e=1/0),e!==this.cache_.duration&&(this.cache_.duration=e,e===1/0?this.addClass("vjs-live"):this.removeClass("vjs-live"),isNaN(e)||this.trigger("durationchange"))}remainingTime(){return this.duration()-this.currentTime()}remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())}buffered(){let e=this.techGet_("buffered");return(!e||!e.length)&&(e=kr(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=kr(0,0)),e}seeking(){return this.techGet_("seeking")}ended(){return this.techGet_("ended")}networkState(){return this.techGet_("networkState")}readyState(){return this.techGet_("readyState")}bufferedPercent(){return yC(this.buffered(),this.duration())}bufferedEnd(){const e=this.buffered(),t=this.duration();let i=e.end(e.length-1);return i>t&&(i=t),i}volume(e){let t;if(e!==void 0){t=Math.max(0,Math.min(1,e)),this.cache_.volume=t,this.techCall_("setVolume",t),t>0&&this.lastVolume_(t);return}return t=parseFloat(this.techGet_("volume")),isNaN(t)?1:t}muted(e){if(e!==void 0){this.techCall_("setMuted",e);return}return this.techGet_("muted")||!1}defaultMuted(e){return e!==void 0&&this.techCall_("setDefaultMuted",e),this.techGet_("defaultMuted")||!1}lastVolume_(e){if(e!==void 0&&e!==0){this.cache_.lastVolume=e;return}return this.cache_.lastVolume}supportsFullScreen(){return this.techGet_("supportsFullScreen")||!1}isFullscreen(e){if(e!==void 0){const t=this.isFullscreen_;this.isFullscreen_=!!e,this.isFullscreen_!==t&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),this.toggleFullscreenClass_();return}return this.isFullscreen_}requestFullscreen(e){this.isInPictureInPicture()&&this.exitPictureInPicture();const t=this;return new Promise((i,n)=>{function r(){t.off("fullscreenerror",u),t.off("fullscreenchange",o)}function o(){r(),i()}function u(d,f){r(),n(f)}t.one("fullscreenchange",o),t.one("fullscreenerror",u);const c=t.requestFullscreenHelper_(e);c&&(c.then(r,r),c.then(i,n))})}requestFullscreenHelper_(e){let t;if(this.fsApi_.prefixed||(t=this.options_.fullscreen&&this.options_.fullscreen.options||{},e!==void 0&&(t=e)),this.fsApi_.requestFullscreen){const i=this.el_[this.fsApi_.requestFullscreen](t);return i&&i.then(()=>this.isFullscreen(!0),()=>this.isFullscreen(!1)),i}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()}exitFullscreen(){const e=this;return new Promise((t,i)=>{function n(){e.off("fullscreenerror",o),e.off("fullscreenchange",r)}function r(){n(),t()}function o(c,d){n(),i(d)}e.one("fullscreenchange",r),e.one("fullscreenerror",o);const u=e.exitFullscreenHelper_();u&&(u.then(n,n),u.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=st[this.fsApi_.exitFullscreen]();return e&&ta(e.then(()=>this.isFullscreen(!1))),e}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()}enterFullWindow(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=st.documentElement.style.overflow,tr(st,"keydown",this.boundFullWindowOnEscKey_),st.documentElement.style.overflow="hidden",jl(st.body,"vjs-full-window"),this.trigger("enterFullWindow")}fullWindowOnEscKey(e){e.key==="Escape"&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,on(st,"keydown",this.boundFullWindowOnEscKey_),st.documentElement.style.overflow=this.docOrigOverflow,Yp(st.body,"vjs-full-window"),this.trigger("exitFullWindow")}disablePictureInPicture(e){if(e===void 0)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",e),this.options_.disablePictureInPicture=e,this.trigger("disablepictureinpicturechanged")}isInPictureInPicture(e){if(e!==void 0){this.isInPictureInPicture_=!!e,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_}requestPictureInPicture(){if(this.options_.enableDocumentPictureInPicture&&ue.documentPictureInPicture){const e=st.createElement(this.el().tagName);return e.classList=this.el().classList,e.classList.add("vjs-pip-container"),this.posterImage&&e.appendChild(this.posterImage.el().cloneNode(!0)),this.titleBar&&e.appendChild(this.titleBar.el().cloneNode(!0)),e.appendChild($t("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),ue.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(nC(t),this.el_.parentNode.insertBefore(e,this.el_),t.document.body.appendChild(this.el_),t.document.body.classList.add("vjs-pip-window"),this.player_.isInPictureInPicture(!0),this.player_.trigger({type:"enterpictureinpicture",pipWindow:t}),t.addEventListener("pagehide",i=>{const n=i.target.querySelector(".video-js");e.parentNode.replaceChild(n,e),this.player_.isInPictureInPicture(!1),this.player_.trigger("leavepictureinpicture")}),t))}return"pictureInPictureEnabled"in st&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(ue.documentPictureInPicture&&ue.documentPictureInPicture.window)return ue.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in st)return st.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(n=>{const r=n.tagName.toLowerCase();if(n.isContentEditable)return!0;const o=["button","checkbox","hidden","radio","reset","submit"];return r==="input"?o.indexOf(n.type)===-1:["textarea"].indexOf(r)!==-1})(this.el_.ownerDocument.activeElement)||(typeof t.hotkeys=="function"?t.hotkeys.call(this,e):this.handleHotkeys(e))}handleHotkeys(e){const t=this.options_.userActions?this.options_.userActions.hotkeys:{},{fullscreenKey:i=o=>e.key.toLowerCase()==="f",muteKey:n=o=>e.key.toLowerCase()==="m",playPauseKey:r=o=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const o=Ue.getComponent("FullscreenToggle");st[this.fsApi_.fullscreenEnabled]!==!1&&o.prototype.handleClick.call(this,e)}else n.call(this,e)?(e.preventDefault(),e.stopPropagation(),Ue.getComponent("MuteToggle").prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),Ue.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,n=this.options_.techOrder;i[u,ii.getTech(u)]).filter(([u,c])=>c?c.isSupported():(ui.error(`The "${u}" tech is undefined. Skipped browser support check for that tech.`),!1)),i=function(u,c,d){let f;return u.some(p=>c.some(g=>{if(f=d(p,g),f)return!0})),f};let n;const r=u=>(c,d)=>u(d,c),o=([u,c],d)=>{if(c.canPlaySource(d,this.options_[u.toLowerCase()]))return{source:d,tech:u}};return this.options_.sourceOrder?n=i(e,t,r(o)):n=i(t,e,o),n||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=SC(e);if(!i.length){this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0);return}if(this.changingSrc_=!0,t||(this.cache_.sources=i),this.updateSourceCaches_(i[0]),V3(this,i[0],(n,r)=>{if(this.middleware_=r,t||(this.cache_.sources=i),this.updateSourceCaches_(n),this.src_(n)){if(i.length>1)return this.handleSrc_(i.slice(1));this.changingSrc_=!1,this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0),this.triggerReady();return}G3(r,this.tech_)}),i.length>1){const n=()=>{this.error(null),this.handleSrc_(i.slice(1),!0)},r=()=>{this.off("error",n)};this.one("error",n),this.one("playing",r),this.resetRetryOnError_=()=>{this.off("error",n),this.off("playing",r)}}}src(e){return this.handleSrc_(e,!1)}src_(e){const t=this.selectSource([e]);return t?fC(t.tech,this.techName_)?(this.ready(function(){this.tech_.constructor.prototype.hasOwnProperty("setSource")?this.techCall_("setSource",e):this.techCall_("src",e.src),this.changingSrc_=!1},!0),!1):(this.changingSrc_=!0,this.loadTech_(t.tech,t.source),this.tech_.ready(()=>{this.changingSrc_=!1}),!1):!0}addSourceElement(e,t){return this.tech_?this.tech_.addSourceElement(e,t):!1}removeSourceElement(e){return this.tech_?this.tech_.removeSourceElement(e):!1}load(){if(this.tech_&&this.tech_.vhs){this.src(this.currentSource());return}this.techCall_("load")}reset(){if(this.paused())this.doReset_();else{const e=this.play();ta(e.then(()=>this.doReset_()))}}doReset_(){this.tech_&&this.tech_.clearTracks("text"),this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),this.error(null),this.titleBar&&this.titleBar.update({title:void 0,description:void 0}),Va(this)&&this.trigger("playerreset")}resetControlBarUI_(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()}resetProgressBar_(){this.currentTime(0);const{currentTimeDisplay:e,durationDisplay:t,progressControl:i,remainingTimeDisplay:n}=this.controlBar||{},{seekBar:r}=i||{};e&&e.updateContent(),t&&t.updateContent(),n&&n.updateContent(),r&&(r.update(),r.loadProgressBar&&r.loadProgressBar.update())}resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()}resetVolumeBar_(){this.volume(1),this.trigger("volumechange")}currentSources(){const e=this.currentSource(),t=[];return Object.keys(e).length!==0&&t.push(e),this.cache_.sources||t}currentSource(){return this.cache_.source||{}}currentSrc(){return this.currentSource()&&this.currentSource().src||""}currentType(){return this.currentSource()&&this.currentSource().type||""}preload(e){if(e!==void 0){this.techCall_("setPreload",e),this.options_.preload=e;return}return this.techGet_("preload")}autoplay(e){if(e===void 0)return this.options_.autoplay||!1;let t;typeof e=="string"&&/(any|play|muted)/.test(e)||e===!0&&this.options_.normalizeAutoplay?(this.options_.autoplay=e,this.manualAutoplay_(typeof e=="string"?e:"play"),t=!1):e?this.options_.autoplay=!0:this.options_.autoplay=!1,t=typeof t>"u"?this.options_.autoplay:t,this.tech_&&this.techCall_("setAutoplay",t)}playsinline(e){return e!==void 0&&(this.techCall_("setPlaysinline",e),this.options_.playsinline=e),this.techGet_("playsinline")}loop(e){if(e!==void 0){this.techCall_("setLoop",e),this.options_.loop=e;return}return this.techGet_("loop")}poster(e){if(e===void 0)return this.poster_;e||(e=""),e!==this.poster_&&(this.poster_=e,this.techCall_("setPoster",e),this.isPosterFromTech_=!1,this.trigger("posterchange"))}handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){const e=this.tech_.poster()||"";e!==this.poster_&&(this.poster_=e,this.isPosterFromTech_=!0,this.trigger("posterchange"))}}controls(e){if(e===void 0)return!!this.controls_;e=!!e,this.controls_!==e&&(this.controls_=e,this.usingNativeControls()&&this.techCall_("setControls",e),this.controls_?(this.removeClass("vjs-controls-disabled"),this.addClass("vjs-controls-enabled"),this.trigger("controlsenabled"),this.usingNativeControls()||this.addTechControlsListeners_()):(this.removeClass("vjs-controls-enabled"),this.addClass("vjs-controls-disabled"),this.trigger("controlsdisabled"),this.usingNativeControls()||this.removeTechControlsListeners_()))}usingNativeControls(e){if(e===void 0)return!!this.usingNativeControls_;e=!!e,this.usingNativeControls_!==e&&(this.usingNativeControls_=e,this.usingNativeControls_?(this.addClass("vjs-using-native-controls"),this.trigger("usingnativecontrols")):(this.removeClass("vjs-using-native-controls"),this.trigger("usingcustomcontrols")))}error(e){if(e===void 0)return this.error_||null;if(Yo("beforeerror").forEach(t=>{const i=t(this,e);if(!(ua(i)&&!Array.isArray(i)||typeof i=="string"||typeof i=="number"||i===null)){this.log.error("please return a value that MediaError expects in beforeerror hooks");return}e=i}),this.options_.suppressNotSupportedError&&e&&e.code===4){const t=function(){this.error(e)};this.options_.suppressNotSupportedError=!1,this.any(["click","touchstart"],t),this.one("loadstart",function(){this.off(["click","touchstart"],t)});return}if(e===null){this.error_=null,this.removeClass("vjs-error"),this.errorDisplay&&this.errorDisplay.close();return}this.error_=new fs(e),this.addClass("vjs-error"),ui.error(`(CODE:${this.error_.code} ${fs.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),Yo("error").forEach(t=>t(this,this.error_))}reportUserActivity(e){this.userActivity_=!0}userActive(e){if(e===void 0)return this.userActive_;if(e=!!e,e!==this.userActive_){if(this.userActive_=e,this.userActive_){this.userActivity_=!0,this.removeClass("vjs-user-inactive"),this.addClass("vjs-user-active"),this.trigger("useractive");return}this.tech_&&this.tech_.one("mousemove",function(t){t.stopPropagation(),t.preventDefault()}),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}}listenForUserActivity_(){let e,t,i;const n=Zi(this,this.reportUserActivity),r=function(p){(p.screenX!==t||p.screenY!==i)&&(t=p.screenX,i=p.screenY,n())},o=function(){n(),this.clearInterval(e),e=this.setInterval(n,250)},u=function(p){n(),this.clearInterval(e)};this.on("mousedown",o),this.on("mousemove",r),this.on("mouseup",u),this.on("mouseleave",u);const c=this.getChild("controlBar");c&&!an&&!Dr&&(c.on("mouseenter",function(p){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),c.on("mouseleave",function(p){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on("keydown",n),this.on("keyup",n);let d;const f=function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(d);const p=this.options_.inactivityTimeout;p<=0||(d=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},p))};this.setInterval(f,250)}playbackRate(e){if(e!==void 0){this.techCall_("setPlaybackRate",e);return}return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_("playbackRate"):1}defaultPlaybackRate(e){return e!==void 0?this.techCall_("setDefaultPlaybackRate",e):this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_("defaultPlaybackRate"):1}isAudio(e){if(e!==void 0){this.isAudio_=!!e;return}return!!this.isAudio_}updatePlayerHeightOnAudioOnlyMode_(){const e=this.getChild("ControlBar");!e||this.audioOnlyCache_.controlBarHeight===e.currentHeight()||(this.audioOnlyCache_.controlBarHeight=e.currentHeight(),this.height(this.audioOnlyCache_.controlBarHeight))}enableAudioOnlyUI_(){this.addClass("vjs-audio-only-mode");const e=this.children(),t=this.getChild("ControlBar"),i=t&&t.currentHeight();e.forEach(n=>{n!==t&&n.el_&&!n.hasClass("vjs-hidden")&&(n.hide(),this.audioOnlyCache_.hiddenChildren.push(n))}),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.audioOnlyCache_.controlBarHeight=i,this.on("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.height(i),this.trigger("audioonlymodechange")}disableAudioOnlyUI_(){this.removeClass("vjs-audio-only-mode"),this.off("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.audioOnlyCache_.hiddenChildren.forEach(e=>e.show()),this.height(this.audioOnlyCache_.playerHeight),this.trigger("audioonlymodechange")}audioOnlyMode(e){if(typeof e!="boolean"||e===this.audioOnlyMode_)return this.audioOnlyMode_;if(this.audioOnlyMode_=e,e){const t=[];return this.isInPictureInPicture()&&t.push(this.exitPictureInPicture()),this.isFullscreen()&&t.push(this.exitFullscreen()),this.audioPosterMode()&&t.push(this.audioPosterMode(!1)),Promise.all(t).then(()=>this.enableAudioOnlyUI_())}return Promise.resolve().then(()=>this.disableAudioOnlyUI_())}enablePosterModeUI_(){(this.tech_&&this.tech_).hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}disablePosterModeUI_(){(this.tech_&&this.tech_).show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}audioPosterMode(e){return typeof e!="boolean"||e===this.audioPosterMode_?this.audioPosterMode_:(this.audioPosterMode_=e,e?this.audioOnlyMode()?this.audioOnlyMode(!1).then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.disablePosterModeUI_()}))}addTextTrack(e,t,i){if(this.tech_)return this.tech_.addTextTrack(e,t,i)}addRemoteTextTrack(e,t){if(this.tech_)return this.tech_.addRemoteTextTrack(e,t)}removeRemoteTextTrack(e={}){let{track:t}=e;if(t||(t=e),this.tech_)return this.tech_.removeRemoteTextTrack(t)}getVideoPlaybackQuality(){return this.techGet_("getVideoPlaybackQuality")}videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0}videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0}language(e){if(e===void 0)return this.language_;this.language_!==String(e).toLowerCase()&&(this.language_=String(e).toLowerCase(),Va(this)&&this.trigger("languagechange"))}languages(){return ji(qu.prototype.options_.languages,this.languages_)}toJSON(){const e=ji(this.options_),t=e.tracks;e.tracks=[];for(let i=0;i{this.removeChild(i)}),i.open(),i}updateCurrentBreakpoint_(){if(!this.responsive())return;const e=this.currentBreakpoint(),t=this.currentWidth();for(let i=0;ithis.addRemoteTextTrack(p,!1)),this.titleBar&&this.titleBar.update({title:f,description:o||n||""}),this.ready(t)}getMedia(){if(!this.cache_.media){const e=this.poster(),t=this.currentSources(),i=Array.prototype.map.call(this.remoteTextTracks(),r=>({kind:r.kind,label:r.label,language:r.language,src:r.src})),n={src:t,textTracks:i};return e&&(n.poster=e,n.artwork=[{src:n.poster,type:op(n.poster)}]),n}return ji(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=Fo(e),n=i["data-setup"];if(th(e,"vjs-fill")&&(i.fill=!0),th(e,"vjs-fluid")&&(i.fluid=!0),n!==null)try{Object.assign(i,JSON.parse(n||"{}"))}catch(r){ui.error("data-setup",r)}if(Object.assign(t,i),e.hasChildNodes()){const r=e.childNodes;for(let o=0,u=r.length;otypeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}};us.prototype.videoTracks=()=>{};us.prototype.audioTracks=()=>{};us.prototype.textTracks=()=>{};us.prototype.remoteTextTracks=()=>{};us.prototype.remoteTextTrackEls=()=>{};pn.names.forEach(function(s){const e=pn[s];us.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});us.prototype.crossorigin=us.prototype.crossOrigin;us.players={};const Fd=ue.navigator;us.prototype.options_={techOrder:ii.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:Fd&&(Fd.languages&&Fd.languages[0]||Fd.userLanguage||Fd.language)||"en",languages:{},notSupportedMessage:"No compatible source was found for this media.",normalizeAutoplay:!1,fullscreen:{options:{navigationUI:"hide"}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,spatialNavigation:{enabled:!1,horizontalSeek:!1},enableSmoothSeeking:!1,disableSeekWhileScrubbingOnMobile:!1,disableSeekWhileScrubbingOnSTV:!1};JC.forEach(function(s){us.prototype[`handleTech${xs(s)}_`]=function(){return this.trigger(s)}});Ue.registerComponent("Player",us);const lp="plugin",sc="activePlugins_",Wu={},up=s=>Wu.hasOwnProperty(s),Om=s=>up(s)?Wu[s]:void 0,ek=(s,e)=>{s[sc]=s[sc]||{},s[sc][e]=!0},cp=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},I4=function(s,e){const t=function(){cp(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return ek(this,s),cp(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},BE=(s,e)=>(e.prototype.name=s,function(...t){cp(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,cp(this,i.getEventHash()),i});class Bn{constructor(e){if(this.constructor===Bn)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),eb(this),delete this.trigger,hC(this,this.constructor.defaultState),ek(e,this.name),this.dispose=this.dispose.bind(this),e.on("dispose",this.dispose)}version(){return this.constructor.VERSION}getEventHash(e={}){return e.name=this.name,e.plugin=this.constructor,e.instance=this,e}trigger(e,t={}){return Lc(this.eventBusEl_,e,this.getEventHash(t))}handleStateChanged(e){}dispose(){const{name:e,player:t}=this;this.trigger("dispose"),this.off(),t.off("dispose",this.dispose),t[sc][e]=!1,this.player=this.state=null,t[e]=BE(e,Wu[e])}static isBasic(e){const t=typeof e=="string"?Om(e):e;return typeof t=="function"&&!Bn.prototype.isPrototypeOf(t.prototype)}static registerPlugin(e,t){if(typeof e!="string")throw new Error(`Illegal plugin name, "${e}", must be a string, was ${typeof e}.`);if(up(e))ui.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(us.prototype.hasOwnProperty(e))throw new Error(`Illegal plugin name, "${e}", cannot share a name with an existing player method!`);if(typeof t!="function")throw new Error(`Illegal plugin for "${e}", must be a function, was ${typeof t}.`);return Wu[e]=t,e!==lp&&(Bn.isBasic(t)?us.prototype[e]=I4(e,t):us.prototype[e]=BE(e,t)),t}static deregisterPlugin(e){if(e===lp)throw new Error("Cannot de-register base plugin.");up(e)&&(delete Wu[e],delete us.prototype[e])}static getPlugins(e=Object.keys(Wu)){let t;return e.forEach(i=>{const n=Om(i);n&&(t=t||{},t[i]=n)}),t}static getPluginVersion(e){const t=Om(e);return t&&t.VERSION||""}}Bn.getPlugin=Om;Bn.BASE_PLUGIN_NAME=lp;Bn.registerPlugin(lp,Bn);us.prototype.usingPlugin=function(s){return!!this[sc]&&this[sc][s]===!0};us.prototype.hasPlugin=function(s){return!!up(s)};function N4(s,e){let t=!1;return function(...i){return t||ui.warn(s),t=!0,e.apply(this,i)}}function Lr(s,e,t,i){return N4(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var O4={NetworkBadStatus:"networkbadstatus",NetworkRequestFailed:"networkrequestfailed",NetworkRequestAborted:"networkrequestaborted",NetworkRequestTimeout:"networkrequesttimeout",NetworkBodyParserFailed:"networkbodyparserfailed",StreamingHlsPlaylistParserError:"streaminghlsplaylistparsererror",StreamingDashManifestParserError:"streamingdashmanifestparsererror",StreamingContentSteeringParserError:"streamingcontentsteeringparsererror",StreamingVttParserError:"streamingvttparsererror",StreamingFailedToSelectNextSegment:"streamingfailedtoselectnextsegment",StreamingFailedToDecryptSegment:"streamingfailedtodecryptsegment",StreamingFailedToTransmuxSegment:"streamingfailedtotransmuxsegment",StreamingFailedToAppendSegment:"streamingfailedtoappendsegment",StreamingCodecsChangeError:"streamingcodecschangeerror"};const tk=s=>s.indexOf("#")===0?s.slice(1):s;function Ae(s,e,t){let i=Ae.getPlayer(s);if(i)return e&&ui.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const n=typeof s=="string"?Wo("#"+tk(s)):s;if(!Dc(n))throw new TypeError("The element or ID supplied is not valid. (videojs)");const o=("getRootNode"in n?n.getRootNode()instanceof ue.ShadowRoot:!1)?n.getRootNode():n.ownerDocument.body;(!n.ownerDocument.defaultView||!o.contains(n))&&ui.warn("The element supplied is not included in the DOM"),e=e||{},e.restoreEl===!0&&(e.restoreEl=(n.parentNode&&n.parentNode.hasAttribute&&n.parentNode.hasAttribute("data-vjs-player")?n.parentNode:n).cloneNode(!0)),Yo("beforesetup").forEach(c=>{const d=c(n,ji(e));if(!ua(d)||Array.isArray(d)){ui.error("please return an object in beforesetup hooks");return}e=ji(e,d)});const u=Ue.getComponent("Player");return i=new u(n,e,t),Yo("setup").forEach(c=>c(i)),i}Ae.hooks_=ja;Ae.hooks=Yo;Ae.hook=m3;Ae.hookOnce=p3;Ae.removeHook=BA;if(ue.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&kc()){let s=Wo(".vjs-styles-defaults");if(!s){s=oC("vjs-styles-defaults");const e=Wo("head");e&&e.insertBefore(s,e.firstChild),lC(s,` + .video-js { + width: 300px; + height: 150px; + } + + .vjs-fluid:not(.vjs-audio-only-mode) { + padding-top: 56.25% + } + `)}}qv(1,Ae);Ae.VERSION=Hv;Ae.options=us.prototype.options_;Ae.getPlayers=()=>us.players;Ae.getPlayer=s=>{const e=us.players;let t;if(typeof s=="string"){const i=tk(s),n=e[i];if(n)return n;t=Wo("#"+i)}else t=s;if(Dc(t)){const{player:i,playerId:n}=t;if(i||e[n])return i||e[n]}};Ae.getAllPlayers=()=>Object.keys(us.players).map(s=>us.players[s]).filter(Boolean);Ae.players=us.players;Ae.getComponent=Ue.getComponent;Ae.registerComponent=(s,e)=>(ii.isTech(e)&&ui.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),Ue.registerComponent.call(Ue,s,e));Ae.getTech=ii.getTech;Ae.registerTech=ii.registerTech;Ae.use=H3;Object.defineProperty(Ae,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(Ae.middleware,"TERMINATOR",{value:ap,writeable:!1,enumerable:!0});Ae.browser=qA;Ae.obj=v3;Ae.mergeOptions=Lr(9,"videojs.mergeOptions","videojs.obj.merge",ji);Ae.defineLazyProperty=Lr(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",Vp);Ae.bind=Lr(9,"videojs.bind","native Function.prototype.bind",Zi);Ae.registerPlugin=Bn.registerPlugin;Ae.deregisterPlugin=Bn.deregisterPlugin;Ae.plugin=(s,e)=>(ui.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),Bn.registerPlugin(s,e));Ae.getPlugins=Bn.getPlugins;Ae.getPlugin=Bn.getPlugin;Ae.getPluginVersion=Bn.getPluginVersion;Ae.addLanguage=function(s,e){return s=(""+s).toLowerCase(),Ae.options.languages=ji(Ae.options.languages,{[s]:e}),Ae.options.languages[s]};Ae.log=ui;Ae.createLogger=FA;Ae.time=N3;Ae.createTimeRange=Lr(9,"videojs.createTimeRange","videojs.time.createTimeRanges",kr);Ae.createTimeRanges=Lr(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",kr);Ae.formatTime=Lr(9,"videojs.formatTime","videojs.time.formatTime",ql);Ae.setFormatTime=Lr(9,"videojs.setFormatTime","videojs.time.setFormatTime",pC);Ae.resetFormatTime=Lr(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",gC);Ae.parseUrl=Lr(9,"videojs.parseUrl","videojs.url.parseUrl",nb);Ae.isCrossOrigin=Lr(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",t0);Ae.EventTarget=ir;Ae.any=Jx;Ae.on=tr;Ae.one=Jp;Ae.off=on;Ae.trigger=Lc;Ae.xhr=_A;Ae.TrackList=Kl;Ae.TextTrack=kh;Ae.TextTrackList=ib;Ae.AudioTrack=TC;Ae.AudioTrackList=vC;Ae.VideoTrack=_C;Ae.VideoTrackList=xC;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{Ae[s]=function(){return ui.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),rC[s].apply(null,arguments)}});Ae.computedStyle=Lr(9,"videojs.computedStyle","videojs.dom.computedStyle",_c);Ae.dom=rC;Ae.fn=C3;Ae.num=u4;Ae.str=R3;Ae.url=j3;Ae.Error=O4;class M4{constructor(e){let t=this;return t.id=e.id,t.label=t.id,t.width=e.width,t.height=e.height,t.bitrate=e.bandwidth,t.frameRate=e.frameRate,t.enabled_=e.enabled,Object.defineProperty(t,"enabled",{get(){return t.enabled_()},set(i){t.enabled_(i)}}),t}}class dp extends Ae.EventTarget{constructor(){super();let e=this;return e.levels_=[],e.selectedIndex_=-1,Object.defineProperty(e,"selectedIndex",{get(){return e.selectedIndex_}}),Object.defineProperty(e,"length",{get(){return e.levels_.length}}),e[Symbol.iterator]=()=>e.levels_.values(),e}addQualityLevel(e){let t=this.getQualityLevelById(e.id);if(t)return t;const i=this.levels_.length;return t=new M4(e),""+i in this||Object.defineProperty(this,i,{get(){return this.levels_[i]}}),this.levels_.push(t),this.trigger({qualityLevel:t,type:"addqualitylevel"}),t}removeQualityLevel(e){let t=null;for(let i=0,n=this.length;ii&&this.selectedIndex_--;break}return t&&this.trigger({qualityLevel:e,type:"removequalitylevel"}),t}getQualityLevelById(e){for(let t=0,i=this.length;ti,s.qualityLevels.VERSION=ik,i},sk=function(s){return P4(this,Ae.obj.merge({},s))};Ae.registerPlugin("qualityLevels",sk);sk.VERSION=ik;const Nn=Up,hp=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,pr=s=>Ae.log.debug?Ae.log.debug.bind(Ae,"VHS:",`${s} >`):function(){};function Di(...s){const e=Ae.obj||Ae;return(e.merge||e.mergeOptions).apply(e,s)}function Vs(...s){const e=Ae.time||Ae;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function B4(s){if(s.length===0)return"Buffered Ranges are empty";let e=`Buffered Ranges: +`;for(let t=0;t ${n}. Duration (${n-i}) +`}return e}const ia=1/30,sa=ia*3,nk=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},cm=function(s,e){return nk(s,function(t){return t-ia>=e})},F4=function(s){if(s.length<2)return Vs();const e=[];for(let t=1;t{const e=[];if(!s||!s.length)return"";for(let t=0;t "+s.end(t));return e.join(", ")},j4=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},Fl=s=>{const e=[];for(let t=0;tr)){if(e>n&&e<=r){t+=r-e;continue}t+=r-n}}return t},_b=(s,e)=>{if(!e.preload)return e.duration;let t=0;return(e.parts||[]).forEach(function(i){t+=i.duration}),(e.preloadHints||[]).forEach(function(i){i.type==="PART"&&(t+=s.partTargetDuration)}),t},ex=s=>(s.segments||[]).reduce((e,t,i)=>(t.parts?t.parts.forEach(function(n,r){e.push({duration:n.duration,segmentIndex:i,partIndex:r,part:n,segment:t})}):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e),[]),ak=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},ok=({preloadSegment:s})=>{if(!s)return;const{parts:e,preloadHints:t}=s;let i=(t||[]).reduce((n,r)=>n+(r.type==="PART"?1:0),0);return i+=e&&e.length?e.length:0,i},lk=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=ak(e).length>0;return t&&e.serverControl&&e.serverControl.partHoldBack?e.serverControl.partHoldBack:t&&e.partTargetDuration?e.partTargetDuration*3:e.serverControl&&e.serverControl.holdBack?e.serverControl.holdBack:e.targetDuration?e.targetDuration*3:0},H4=function(s,e){let t=0,i=e-s.mediaSequence,n=s.segments[i];if(n){if(typeof n.start<"u")return{result:n.start,precise:!0};if(typeof n.end<"u")return{result:n.end-n.duration,precise:!0}}for(;i--;){if(n=s.segments[i],typeof n.end<"u")return{result:t+n.end,precise:!0};if(t+=_b(s,n),typeof n.start<"u")return{result:t+n.start,precise:!0}}return{result:t,precise:!1}},V4=function(s,e){let t=0,i,n=e-s.mediaSequence;for(;n"u"&&(e=s.mediaSequence+s.segments.length),e"u"){if(s.totalDuration)return s.totalDuration;if(!s.endList)return ue.Infinity}return uk(s,e,t)},nh=function({defaultDuration:s,durationList:e,startIndex:t,endIndex:i}){let n=0;if(t>i&&([t,i]=[i,t]),t<0){for(let r=t;r0)for(let d=c-1;d>=0;d--){const f=u[d];if(o+=f.duration,r){if(o<0)continue}else if(o+ia<=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n-nh({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e}}if(c<0){for(let d=c;d<0;d++)if(o-=s.targetDuration,o<0)return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e};c=0}for(let d=c;dia,g=o===0,y=p&&o+ia>=0;if(!((g||y)&&d!==u.length-1)){if(r){if(o>0)continue}else if(o-ia>=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n+nh({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}}return{segmentIndex:u[u.length-1].segmentIndex,partIndex:u[u.length-1].partIndex,startTime:e}},hk=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},Sb=function(s){return s.excludeUntil&&s.excludeUntil===1/0},r0=function(s){const e=hk(s);return!s.disabled&&!e},q4=function(s){return s.disabled},K4=function(s){for(let e=0;e{if(s.playlists.length===1)return!0;const t=e.attributes.BANDWIDTH||Number.MAX_VALUE;return s.playlists.filter(i=>r0(i)?(i.attributes.BANDWIDTH||0)!s&&!e||!s&&e||s&&!e?!1:!!(s===e||s.id&&e.id&&s.id===e.id||s.resolvedUri&&e.resolvedUri&&s.resolvedUri===e.resolvedUri||s.uri&&e.uri&&s.uri===e.uri),FE=function(s,e){const t=s&&s.mediaGroups&&s.mediaGroups.AUDIO||{};let i=!1;for(const n in t){for(const r in t[n])if(i=e(t[n][r]),i)break;if(i)break}return!!i},Ih=s=>{if(!s||!s.playlists||!s.playlists.length)return FE(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;ewA(r))||FE(s,r=>Eb(t,r))))return!1}return!0};var On={liveEdgeDelay:lk,duration:ck,seekable:G4,getMediaInfoForTime:z4,isEnabled:r0,isDisabled:q4,isExcluded:hk,isIncompatible:Sb,playlistEnd:dk,isAes:K4,hasAttribute:fk,estimateSegmentRequestTime:Y4,isLowestEnabledRendition:tx,isAudioOnly:Ih,playlistMatch:Eb,segmentDurationWithParts:_b};const{log:mk}=Ae,nc=(s,e)=>`${s}-${e}`,pk=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,W4=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:n=[],llhls:r})=>{const o=new PM;s&&o.on("warn",s),e&&o.on("info",e),i.forEach(d=>o.addParser(d)),n.forEach(d=>o.addTagMapper(d)),o.push(t),o.end();const u=o.manifest;if(r||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(d){u.hasOwnProperty(d)&&delete u[d]}),u.segments&&u.segments.forEach(function(d){["parts","preloadHints"].forEach(function(f){d.hasOwnProperty(f)&&delete d[f]})})),!u.targetDuration){let d=10;u.segments&&u.segments.length&&(d=u.segments.reduce((f,p)=>Math.max(f,p.duration),0)),s&&s({message:`manifest has no targetDuration defaulting to ${d}`}),u.targetDuration=d}const c=ak(u);if(c.length&&!u.partTargetDuration){const d=c.reduce((f,p)=>Math.max(f,p.duration),0);s&&(s({message:`manifest has no partTargetDuration defaulting to ${d}`}),mk.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),u.partTargetDuration=d}return u},Oc=(s,e)=>{s.mediaGroups&&["AUDIO","SUBTITLES"].forEach(t=>{if(s.mediaGroups[t])for(const i in s.mediaGroups[t])for(const n in s.mediaGroups[t][i]){const r=s.mediaGroups[t][i][n];e(r,t,i,n)}})},gk=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},X4=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];gk({playlist:t,id:nc(e,t.uri)}),t.resolvedUri=Nn(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||mk.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},Q4=s=>{Oc(s,e=>{e.uri&&(e.resolvedUri=Nn(s.uri,e.uri))})},Z4=(s,e)=>{const t=nc(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:ue.location.href,resolvedUri:ue.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},yk=(s,e,t=pk)=>{s.uri=e;for(let n=0;n{if(!n.playlists||!n.playlists.length){if(i&&r==="AUDIO"&&!n.uri)for(let c=0;c(n.set(r.id,r),n),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(this.offset_===null)return[];const e={},t=[];this.pendingDateRanges_.forEach((i,n)=>{if(!this.processedDateRanges_.has(n)&&(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),!!i.class))if(e[i.class]){const r=e[i.class].push(i);i.classListIndex=r-1}else e[i.class]=[i],i.classListIndex=0});for(const i of t){const n=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&n[i.classListIndex+1]?i.endTime=n[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((i,n)=>{i.startDate.getTime(){const n=e.status<200||e.status>299,r=e.status>=400&&e.status<=499,o={uri:e.uri,requestType:s},u=n&&!r||i;if(t&&r)o.error=Es({},t),o.errorType=Ae.Error.NetworkRequestFailed;else if(e.aborted)o.errorType=Ae.Error.NetworkRequestAborted;else if(e.timedout)o.errorType=Ae.Error.NetworkRequestTimeout;else if(u){const c=i?Ae.Error.NetworkBodyParserFailed:Ae.Error.NetworkBadStatus;o.errorType=c,o.status=e.status,o.headers=e.headers}return o},J4=pr("CodecUtils"),xk=function(s){const e=s.attributes||{};if(e.CODECS)return Zr(e.CODECS)},bk=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},eB=(s,e)=>{if(!bk(s,e))return!0;const t=e.attributes||{},i=s.mediaGroups.AUDIO[t.AUDIO];for(const n in i)if(!i[n].uri&&!i[n].playlists)return!0;return!1},ph=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:n})=>{e[t]=e[t]||[],e[t].push(EA(`${i}${n}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){J4(`multiple ${t} codecs found as attributes: ${e[t].join(", ")}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),e[t]=null;return}e[t]=e[t][0]}),e},jE=function(s){let e=0;return s.audio&&e++,s.video&&e++,e},rh=function(s,e){const t=e.attributes||{},i=ph(xk(e)||[]);if(bk(s,e)&&!i.audio&&!eB(s,e)){const n=ph(FM(s,t.AUDIO)||[]);n.audio&&(i.audio=n.audio)}return i},{EventTarget:tB}=Ae,iB=(s,e)=>{if(e.endList||!e.serverControl)return s;const t={};if(e.serverControl.canBlockReload){const{preloadSegment:i}=e;let n=e.mediaSequence+e.segments.length;if(i){const r=i.parts||[],o=ok(e)-1;o>-1&&o!==r.length-1&&(t._HLS_part=o),(o>-1||r.length)&&n--}t._HLS_msn=n}if(e.serverControl&&e.serverControl.canSkipUntil&&(t._HLS_skip=e.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(t).length){const i=new ue.URL(s);["_HLS_skip","_HLS_msn","_HLS_part"].forEach(function(n){t.hasOwnProperty(n)&&i.searchParams.set(n,t[n])}),s=i.toString()}return s},sB=(s,e)=>{if(!s)return e;const t=Di(s,e);if(s.preloadHints&&!e.preloadHints&&delete t.preloadHints,s.parts&&!e.parts)delete t.parts;else if(s.parts&&e.parts)for(let i=0;i{const i=s.slice(),n=e.slice();t=t||0;const r=[];let o;for(let u=0;u{!s.resolvedUri&&s.uri&&(s.resolvedUri=Nn(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=Nn(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=Nn(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=Nn(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=Nn(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=Nn(e,t.uri))})},_k=function(s){const e=s.segments||[],t=s.preloadSegment;if(t&&t.parts&&t.parts.length){if(t.preloadHints){for(let i=0;is===e||s.segments&&e.segments&&s.segments.length===e.segments.length&&s.endList===e.endList&&s.mediaSequence===e.mediaSequence&&s.preloadSegment===e.preloadSegment,ix=(s,e,t=Sk)=>{const i=Di(s,{}),n=i.playlists[e.id];if(!n||t(n,e))return null;e.segments=_k(e);const r=Di(n,e);if(r.preloadSegment&&!e.preloadSegment&&delete r.preloadSegment,n.segments){if(e.skip){e.segments=e.segments||[];for(let o=0;o{Tk(o,r.resolvedUri)});for(let o=0;o{if(o.playlists)for(let f=0;f{const t=s.segments||[],i=t[t.length-1],n=i&&i.parts&&i.parts[i.parts.length-1],r=n&&n.duration||i&&i.duration;return e&&r?r*1e3:(s.partTargetDuration||s.targetDuration||10)*500},$E=(s,e,t)=>{if(!s)return;const i=[];return s.forEach(n=>{if(!n.attributes)return;const{BANDWIDTH:r,RESOLUTION:o,CODECS:u}=n.attributes;i.push({id:n.id,bandwidth:r,resolution:o,codecs:u})}),{type:e,isLive:t,renditions:i}};let Qu=class extends tB{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=pr("PlaylistLoader");const{withCredentials:n=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=n,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;const r=t.options_;this.customTagParsers=r&&r.customTagParsers||[],this.customTagMappers=r&&r.customTagMappers||[],this.llhls=r&&r.llhls,this.dateRangesStorage_=new UE,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){const e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);const t=this.dateRangesStorage_.getDateRangesToProcess();!t.length||!this.addDateRangesToTextTrack_||this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if(this.state!=="HAVE_METADATA")return;const e=this.media();let t=Nn(this.main.uri,e.uri);this.llhls&&(t=iB(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials,requestType:"hls-playlist"},(i,n)=>{if(this.request){if(i)return this.playlistRequestError(this.request,this.media(),"HAVE_METADATA");this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}})}playlistRequestError(e,t,i){const{uri:n,id:r}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[r],status:e.status,message:`HLS playlist request error at URL: ${n}.`,responseText:e.responseText,code:e.status>=500?4:2,metadata:Vl({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=W4({onwarn:({message:n})=>this.logger_(`m3u8-parser warn for ${e}: ${n}`),oninfo:({message:n})=>this.logger_(`m3u8-parser info for ${e}: ${n}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls});return!i.playlists||!i.playlists.length||this.excludeAudioOnlyVariants(i.playlists),i}catch(i){this.error=i,this.error.metadata={errorType:Ae.Error.StreamingHlsPlaylistParserError,error:i}}}excludeAudioOnlyVariants(e){const t=i=>{const n=i.attributes||{},{width:r,height:o}=n.RESOLUTION||{};if(r&&o)return!0;const u=xk(i)||[];return!!ph(u).video};e.some(t)&&e.forEach(i=>{t(i)||(i.excludeUntil=1/0)})}haveMetadata({playlistString:e,playlistObject:t,url:i,id:n}){this.request=null,this.state="HAVE_METADATA";const r={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:r});const o=t||this.parseManifest_({url:i,manifestString:e});o.lastRequest=Date.now(),gk({playlist:o,uri:i,id:n});const u=ix(this.main,o);this.targetDuration=o.partTargetDuration||o.targetDuration,this.pendingMedia_=null,u?(this.main=u,this.media_=this.main.playlists[n]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(sx(this.media(),!!u)),r.parsedPlaylist=$E(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),ue.clearTimeout(this.mediaUpdateTimeout),ue.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new UE,this.off()}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);if(typeof e=="string"){if(!this.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.main.playlists[e]}if(ue.clearTimeout(this.finalRenditionTimeout),t){const u=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=ue.setTimeout(this.media.bind(this,e,!1),u);return}const i=this.state,n=!this.media_||e.id!==this.media_.id,r=this.main.playlists[e.id];if(r&&r.endList||e.endList&&e.segments.length){this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,n&&(this.trigger("mediachanging"),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange"));return}if(this.updateMediaUpdateTimeout_(sx(e,!0)),!n)return;if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e;const o={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:o}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(u,c)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=hp(e.resolvedUri,c),u)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:o}),this.haveMetadata({playlistString:c.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(ue.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),this.state==="HAVE_NOTHING"&&(this.started=!1),this.state==="SWITCHING_MEDIA"?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":this.state==="HAVE_CURRENT_METADATA"&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(ue.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=ue.setTimeout(()=>{this.mediaUpdateTimeout=null,this.load()},i);return}if(!this.started){this.start();return}t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist")}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(ue.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=ue.setTimeout(()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)},e))}start(){if(this.started=!0,typeof this.src=="object"){this.src.uri||(this.src.uri=ue.location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);return}const e={playlistInfo:{type:"multivariant",uri:this.src}};this.trigger({type:"playlistrequeststart",metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,i)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:i.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:i.responseText,code:2,metadata:Vl({requestType:i.requestType,request:i,error:t})},this.state==="HAVE_NOTHING"&&(this.started=!1),this.trigger("error");this.trigger({type:"playlistrequestcomplete",metadata:e}),this.src=hp(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const n=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=$E(n.playlists,e.playlistInfo.type,!1),this.trigger({type:"playlistparsecomplete",metadata:e}),this.setupInitialPlaylist(n)})}srcUri(){return typeof this.src=="string"?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists){this.main=e,yk(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=_k(i),i.segments.forEach(n=>{Tk(n,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||ue.location.href;this.main=Z4(e,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){const i=this.main,n=e.ID;let r=i.playlists.length;for(;r--;){const o=i.playlists[r];if(o.attributes["PATHWAY-ID"]===n){const u=o.resolvedUri,c=o.id;if(t){const d=this.createCloneURI_(o.resolvedUri,e),f=nc(n,d),p=this.createCloneAttributes_(n,o.attributes),g=this.createClonePlaylist_(o,f,e,p);i.playlists[r]=g,i.playlists[f]=g,i.playlists[d]=g}else i.playlists.splice(r,1);delete i.playlists[c],delete i.playlists[u]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,n=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!i.mediaGroups[r]||!i.mediaGroups[r][n])){for(const o in i.mediaGroups[r])if(o===n){for(const u in i.mediaGroups[r][o])i.mediaGroups[r][o][u].playlists.forEach((d,f)=>{const p=i.playlists[d.id],g=p.id,y=p.resolvedUri;delete i.playlists[g],delete i.playlists[y]});delete i.mediaGroups[r][o]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,n=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),o=nc(e.ID,r),u=this.createCloneAttributes_(e.ID,t.attributes),c=this.createClonePlaylist_(t,o,e,u);i.playlists[n]=c,i.playlists[o]=c,i.playlists[r]=c,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],n=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!n.mediaGroups[r]||n.mediaGroups[r][t]))for(const o in n.mediaGroups[r]){if(o===i)n.mediaGroups[r][t]={};else continue;for(const u in n.mediaGroups[r][o]){const c=n.mediaGroups[r][o][u];n.mediaGroups[r][t][u]=Es({},c);const d=n.mediaGroups[r][t][u],f=this.createCloneURI_(c.resolvedUri,e);d.resolvedUri=f,d.uri=f,d.playlists=[],c.playlists.forEach((p,g)=>{const y=n.playlists[p.id],x=pk(r,t,u),_=nc(t,x);if(y&&!n.playlists[_]){const w=this.createClonePlaylist_(y,_,e),D=w.resolvedUri;n.playlists[_]=w,n.playlists[D]=w}d.playlists[g]=this.createClonePlaylist_(p,_,e)})}}})}createClonePlaylist_(e,t,i,n){const r=this.createCloneURI_(e.resolvedUri,i),o={resolvedUri:r,uri:r,id:t};return e.segments&&(o.segments=[]),n&&(o.attributes=n),Di(e,o)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const n=t["URI-REPLACEMENT"].PARAMS;for(const r of Object.keys(n))i.searchParams.set(r,n[r]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(n=>{t[n]&&(i[n]=e)}),i}getKeyIdSet(e){const t=new Set;if(!e||!e.contentProtection)return t;for(const i in e.contentProtection)if(e.contentProtection[i]&&e.contentProtection[i].attributes&&e.contentProtection[i].attributes.keyId){const n=e.contentProtection[i].attributes.keyId;t.add(n.toLowerCase())}return t}};const nx=function(s,e,t,i){const n=s.responseType==="arraybuffer"?s.response:s.responseText;!e&&n&&(s.responseTime=Date.now(),s.roundTripTime=s.responseTime-s.requestTime,s.bytesReceived=n.byteLength||n.length,s.bandwidth||(s.bandwidth=Math.floor(s.bytesReceived/s.roundTripTime*8*1e3))),t.headers&&(s.responseHeaders=t.headers),e&&e.code==="ETIMEDOUT"&&(s.timedout=!0),!e&&!s.aborted&&t.statusCode!==200&&t.statusCode!==206&&t.statusCode!==0&&(e=new Error("XHR Failed with a response of: "+(s&&(n||s.responseText)))),i(e,s)},rB=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},aB=(s,e,t,i)=>{!s||!s.size||s.forEach(n=>{n(e,t,i)})},Ek=function(){const s=function e(t,i){t=Di({timeout:45e3},t);const n=e.beforeRequest||Ae.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||Ae.Vhs.xhr._requestCallbackSet||new Set,o=e._responseCallbackSet||Ae.Vhs.xhr._responseCallbackSet;n&&typeof n=="function"&&(Ae.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(n));const u=Ae.Vhs.xhr.original===!0?Ae.xhr:Ae.Vhs.xhr,c=rB(r,t);r.delete(n);const d=u(c||t,function(p,g){return aB(o,d,p,g),nx(d,p,g,i)}),f=d.abort;return d.abort=function(){return d.aborted=!0,f.apply(d,arguments)},d.uri=t.uri,d.requestType=t.requestType,d.requestTime=Date.now(),d};return s.original=!0,s},oB=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=ue.BigInt(s.offset)+ue.BigInt(s.length)-ue.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},rx=function(s){const e={};return s.byterange&&(e.Range=oB(s.byterange)),e},lB=function(s,e){return s.start(e)+"-"+s.end(e)},uB=function(s,e){const t=s.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},cB=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},wk=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];CA(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},fp=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},Ak=function(s){return s.resolvedUri},Ck=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",n,r;for(let o=0;oCk(s),hB=s=>{let e="",t;for(t=0;t{if(!e.dateTimeObject)return null;const t=e.videoTimingInfo.transmuxerPrependedSeconds,n=e.videoTimingInfo.transmuxedPresentationStart+t,r=s-n;return new Date(e.dateTimeObject.getTime()+r*1e3)},pB=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,gB=(s,e)=>{let t;try{t=new Date(s)}catch{return null}if(!e||!e.segments||e.segments.length===0)return null;let i=e.segments[0];if(tu?null:(t>new Date(r)&&(i=n),{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:On.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},yB=(s,e)=>{if(!e||!e.segments||e.segments.length===0)return null;let t=0,i;for(let r=0;rt){if(s>t+n.duration*kk)return null;i=n}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:t-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},vB=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const n=t.getTime();return(i.getTime()-n)/1e3},xB=s=>{if(!s.segments||s.segments.length===0)return!1;for(let e=0;e{if(!t)throw new Error("getProgramTime: callback must be provided");if(!s||e===void 0)return t({message:"getProgramTime: playlist and time must be provided"});const i=yB(e,s);if(!i)return t({message:"valid programTime was not found"});if(i.type==="estimate")return t({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:i.estimatedStart});const n={mediaSeconds:e},r=mB(e,i.segment);return r&&(n.programDateTime=r.toISOString()),t(null,n)},Dk=({programTime:s,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:n=!0,tech:r,callback:o})=>{if(!o)throw new Error("seekToProgramTime: callback must be provided");if(typeof s>"u"||!e||!i)return o({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!r.hasStarted_)return o({message:"player must be playing a live stream to start buffering"});if(!xB(e))return o({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const u=gB(s,e);if(!u)return o({message:`${s} was not found in the stream`});const c=u.segment,d=vB(c.dateTimeObject,s);if(u.type==="estimate"){if(t===0)return o({message:`${s} is not buffered yet. Try again`});i(u.estimatedStart+d),r.one("seeked",()=>{Dk({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:n,tech:r,callback:o})});return}const f=c.start+d,p=()=>o(null,r.currentTime());r.one("seeked",p),n&&r.pause(),i(f)},Yy=(s,e)=>{if(s.readyState===4)return e()},TB=(s,e,t,i)=>{let n=[],r,o=!1;const u=function(p,g,y,x){return g.abort(),o=!0,t(p,g,y,x)},c=function(p,g){if(o)return;if(p)return p.metadata=Vl({requestType:i,request:g,error:p}),u(p,g,"",n);const y=g.responseText.substring(n&&n.byteLength||0,g.responseText.length);if(n=YM(n,kA(y,!0)),r=r||qd(n),n.length<10||r&&n.lengthu(p,g,"",n));const x=Yx(n);return x==="ts"&&n.length<188?Yy(g,()=>u(p,g,"",n)):!x&&n.length<376?Yy(g,()=>u(p,g,"",n)):u(null,g,x,n)},f=e({uri:s,beforeSend(p){p.overrideMimeType("text/plain; charset=x-user-defined"),p.addEventListener("progress",function({total:g,loaded:y}){return nx(p,null,{statusCode:p.status},c)})}},function(p,g){return nx(f,p,g,c)});return f},{EventTarget:_B}=Ae,HE=function(s,e){if(!Sk(s,e)||s.sidx&&e.sidx&&(s.sidx.offset!==e.sidx.offset||s.sidx.length!==e.sidx.length))return!1;if(!s.sidx&&e.sidx||s.sidx&&!e.sidx||s.segments&&!e.segments||!s.segments&&e.segments)return!1;if(!s.segments&&!e.segments)return!0;for(let t=0;t{const n=i.attributes.NAME||t;return`placeholder-uri-${s}-${e}-${n}`},EB=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:n})=>{const r=qP(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:n});return yk(r,e,SB),r},wB=(s,e)=>{Oc(s,(t,i,n,r)=>{(!e.mediaGroups[i][n]||!(r in e.mediaGroups[i][n]))&&delete s.mediaGroups[i][n][r]})},AB=(s,e,t)=>{let i=!0,n=Di(s,{duration:e.duration,minimumUpdatePeriod:e.minimumUpdatePeriod,timelineStarts:e.timelineStarts});for(let r=0;r{if(r.playlists&&r.playlists.length){const d=r.playlists[0].id,f=ix(n,r.playlists[0],HE);f&&(n=f,c in n.mediaGroups[o][u]||(n.mediaGroups[o][u][c]=r),n.mediaGroups[o][u][c].playlists[0]=n.playlists[d],i=!1)}}),wB(n,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:n},CB=(s,e)=>(!s.map&&!e.map||!!(s.map&&e.map&&s.map.byterange.offset===e.map.byterange.offset&&s.map.byterange.length===e.map.byterange.length))&&s.uri===e.uri&&s.byterange.offset===e.byterange.offset&&s.byterange.length===e.byterange.length,VE=(s,e)=>{const t={};for(const i in s){const r=s[i].sidx;if(r){const o=$p(r);if(!e[o])break;const u=e[o].sidxInfo;CB(u,r)&&(t[o]=e[o])}}return t},kB=(s,e)=>{let i=VE(s.playlists,e);return Oc(s,(n,r,o,u)=>{if(n.playlists&&n.playlists.length){const c=n.playlists;i=Di(i,VE(c,e))}}),i};class ax extends _B{constructor(e,t,i={},n){super(),this.isPaused_=!0,this.mainPlaylistLoader_=n||this,n||(this.isMain_=!0);const{withCredentials:r=!1}=i;if(this.vhs_=t,this.withCredentials=r,this.addMetadataToTextTrack=i.addMetadataToTextTrack,!e)throw new Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",()=>{this.refreshXml_()}),this.on("mediaupdatetimeout",()=>{this.refreshMedia_(this.media().id)}),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=pr("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}get isPaused(){return this.isPaused_}requestErrored_(e,t,i){if(!this.request)return!0;if(this.request=null,e)return this.error=typeof e=="object"&&!(e instanceof Error)?e:{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2,metadata:e.metadata},i&&(this.state=i),this.trigger("error"),!0}addSidxSegments_(e,t,i){const n=e.sidx&&$p(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n]){ue.clearTimeout(this.mediaRequest_),this.mediaRequest_=ue.setTimeout(()=>i(!1),0);return}const r=hp(e.sidx.resolvedUri),o=(c,d)=>{if(this.requestErrored_(c,d,t))return;const f=this.mainPlaylistLoader_.sidxMapping_,{requestType:p}=d;let g;try{g=QP(Ft(d.response).subarray(8))}catch(y){y.metadata=Vl({requestType:p,request:d,parseFailure:!0}),this.requestErrored_(y,d,t);return}return f[n]={sidxInfo:e.sidx,sidx:g},zx(e,g,e.sidx.resolvedUri),i(!0)},u="dash-sidx";this.request=TB(r,this.vhs_.xhr,(c,d,f,p)=>{if(c)return o(c,d);if(!f||f!=="mp4"){const x=f||"unknown";return o({status:d.status,message:`Unsupported ${x} container type for sidx segment at URL: ${r}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},d)}const{offset:g,length:y}=e.sidx.byterange;if(p.length>=y+g)return o(c,{response:p.subarray(g,g+y),status:d.status,uri:d.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:rx({byterange:e.sidx.byterange})},o)},u)}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},ue.clearTimeout(this.minimumUpdatePeriodTimeout_),ue.clearTimeout(this.mediaRequest_),ue.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);const t=this.state;if(typeof e=="string"){if(!this.mainPlaylistLoader_.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}const i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList){this.state="HAVE_METADATA",this.media_=e,i&&(this.trigger("mediachanging"),this.trigger("mediachange"));return}i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,n=>{this.haveMetadata({startingState:t,playlist:e})}))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,ue.clearTimeout(this.mediaRequest_),this.mediaRequest_=null,this.refreshMedia_(t.id),e==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.isPaused_=!0,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),ue.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(ue.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){this.isPaused_=!1,ue.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=ue.setTimeout(()=>this.load(),i);return}if(!this.started){this.start();return}t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist")}start(){if(this.started=!0,!this.isMain_){ue.clearTimeout(this.mediaRequest_),this.mediaRequest_=ue.setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),!this.hasPendingRequest()&&!this.media_&&this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){const t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(i,n)=>{if(i){const{requestType:o}=n;i.metadata=Vl({requestType:o,request:n,error:i})}if(this.requestErrored_(i,n)){this.state==="HAVE_NOTHING"&&(this.started=!1);return}this.trigger({type:"manifestrequestcomplete",metadata:t});const r=n.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=n.responseText,n.responseHeaders&&n.responseHeaders.date?this.mainLoaded_=Date.parse(n.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=hp(this.mainPlaylistLoader_.srcUrl,n),r){this.handleMain_(),this.syncClientServerClock_(()=>e(n,r));return}return e(n,r)})}syncClientServerClock_(e){const t=KP(this.mainPlaylistLoader_.mainXml_);if(t===null)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e();if(t.method==="DIRECT")return this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e();this.request=this.vhs_.xhr({uri:Nn(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,n)=>{if(!this.request)return;if(i){const{requestType:o}=n;return this.error.metadata=Vl({requestType:o,request:n,error:i}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}let r;t.method==="HEAD"?!n.responseHeaders||!n.responseHeaders.date?r=this.mainLoaded_:r=Date.parse(n.responseHeaders.date):r=Date.parse(n.responseText),this.mainPlaylistLoader_.clientOffset_=r-Date.now(),e()})}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){ue.clearTimeout(this.mediaRequest_),this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main,t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestparsestart",metadata:t});let i;try{i=EB({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e})}catch(r){this.error=r,this.error.metadata={errorType:Ae.Error.StreamingDashManifestParserError,error:r},this.trigger("error")}e&&(i=AB(e,i,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=i||e;const n=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(n&&n!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=n),(!e||i&&i.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(i),i){const{duration:r,endList:o}=i,u=[];i.playlists.forEach(d=>{u.push({id:d.id,bandwidth:d.attributes.BANDWIDTH,resolution:d.attributes.RESOLUTION,codecs:d.attributes.CODECS})});const c={duration:r,isLive:!o,renditions:u};t.parsedManifest=c,this.trigger({type:"manifestparsecomplete",metadata:t})}return!!i}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(ue.clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;if(t===0&&(e.media()?t=e.media().targetDuration*1e3:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),typeof t!="number"||t<=0){t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`);return}this.createMUPTimeout_(t)}createMUPTimeout_(e){const t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=ue.setTimeout(()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)},e)}refreshXml_(){this.requestMain_((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=kB(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,i=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(e){if(!e)throw new Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const t=this.mainPlaylistLoader_.main.playlists,i=!this.media_||this.media_!==t[e];if(i?this.media_=t[e]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){const n=()=>{this.media().endList||(this.mediaUpdateTimeout=ue.setTimeout(()=>{this.trigger("mediaupdatetimeout"),n()},sx(this.media(),!!i)))};n()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){const t=this.mainPlaylistLoader_.main.eventStream.map(i=>({cueTime:i.start,frames:[{data:i.messageData}]}));this.addMetadataToTextTrack("EventStream",t,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const n=e.contentProtection[i].attributes["cenc:default_KID"];n&&t.add(n.replace(/-/g,"").toLowerCase())}return t}}}var $s={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};const DB=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(E){var C,A,R,P;if(C=b[E],!!C)if(arguments.length===2)for(R=C.length,A=0;A"u")){for(b in Y)Y.hasOwnProperty(b)&&(Y[b]=[b.charCodeAt(0),b.charCodeAt(1),b.charCodeAt(2),b.charCodeAt(3)]);re=new Uint8Array([105,115,111,109]),H=new Uint8Array([97,118,99,49]),Z=new Uint8Array([0,0,0,1]),K=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),ie=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),te={video:K,audio:ie},ee=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),$=new Uint8Array([0,0,0,0,0,0,0,0]),le=new Uint8Array([0,0,0,0,0,0,0,0]),be=le,fe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),_e=le,ne=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),u=function(b){var E=[],C=0,A,R,P;for(A=1;A>>1,b.samplingfrequencyindex<<7|b.channelcount<<3,6,1,2]))},f=function(){return u(Y.ftyp,re,Z,re,H)},V=function(b){return u(Y.hdlr,te[b])},p=function(b){return u(Y.mdat,b)},j=function(b){var E=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,b.duration>>>24&255,b.duration>>>16&255,b.duration>>>8&255,b.duration&255,85,196,0,0]);return b.samplerate&&(E[12]=b.samplerate>>>24&255,E[13]=b.samplerate>>>16&255,E[14]=b.samplerate>>>8&255,E[15]=b.samplerate&255),u(Y.mdhd,E)},B=function(b){return u(Y.mdia,j(b),V(b.type),y(b))},g=function(b){return u(Y.mfhd,new Uint8Array([0,0,0,0,(b&4278190080)>>24,(b&16711680)>>16,(b&65280)>>8,b&255]))},y=function(b){return u(Y.minf,b.type==="video"?u(Y.vmhd,ne):u(Y.smhd,$),c(),z(b))},x=function(b,E){for(var C=[],A=E.length;A--;)C[A]=N(E[A]);return u.apply(null,[Y.moof,g(b)].concat(C))},_=function(b){for(var E=b.length,C=[];E--;)C[E]=I(b[E]);return u.apply(null,[Y.moov,D(4294967295)].concat(C).concat(w(b)))},w=function(b){for(var E=b.length,C=[];E--;)C[E]=q(b[E]);return u.apply(null,[Y.mvex].concat(C))},D=function(b){var E=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(b&4278190080)>>24,(b&16711680)>>16,(b&65280)>>8,b&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return u(Y.mvhd,E)},M=function(b){var E=b.samples||[],C=new Uint8Array(4+E.length),A,R;for(R=0;R>>8),P.push(A[se].byteLength&255),P=P.concat(Array.prototype.slice.call(A[se]));for(se=0;se>>8),J.push(R[se].byteLength&255),J=J.concat(Array.prototype.slice.call(R[se]));if(ae=[Y.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(C.width&65280)>>8,C.width&255,(C.height&65280)>>8,C.height&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u(Y.avcC,new Uint8Array([1,C.profileIdc,C.profileCompatibility,C.levelIdc,255].concat([A.length],P,[R.length],J))),u(Y.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],C.sarRatio){var ce=C.sarRatio[0],ge=C.sarRatio[1];ae.push(u(Y.pasp,new Uint8Array([(ce&4278190080)>>24,(ce&16711680)>>16,(ce&65280)>>8,ce&255,(ge&4278190080)>>24,(ge&16711680)>>16,(ge&65280)>>8,ge&255])))}return u.apply(null,ae)},E=function(C){return u(Y.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(C.channelcount&65280)>>8,C.channelcount&255,(C.samplesize&65280)>>8,C.samplesize&255,0,0,0,0,(C.samplerate&65280)>>8,C.samplerate&255,0,0]),d(C))}})(),L=function(b){var E=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(b.id&4278190080)>>24,(b.id&16711680)>>16,(b.id&65280)>>8,b.id&255,0,0,0,0,(b.duration&4278190080)>>24,(b.duration&16711680)>>16,(b.duration&65280)>>8,b.duration&255,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(b.width&65280)>>8,b.width&255,0,0,(b.height&65280)>>8,b.height&255,0,0]);return u(Y.tkhd,E)},N=function(b){var E,C,A,R,P,J,se;return E=u(Y.tfhd,new Uint8Array([0,0,0,58,(b.id&4278190080)>>24,(b.id&16711680)>>16,(b.id&65280)>>8,b.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),J=Math.floor(b.baseMediaDecodeTime/o),se=Math.floor(b.baseMediaDecodeTime%o),C=u(Y.tfdt,new Uint8Array([1,0,0,0,J>>>24&255,J>>>16&255,J>>>8&255,J&255,se>>>24&255,se>>>16&255,se>>>8&255,se&255])),P=92,b.type==="audio"?(A=Q(b,P),u(Y.traf,E,C,A)):(R=M(b),A=Q(b,R.length+P),u(Y.traf,E,C,A,R))},I=function(b){return b.duration=b.duration||4294967295,u(Y.trak,L(b),B(b))},q=function(b){var E=new Uint8Array([0,0,0,0,(b.id&4278190080)>>24,(b.id&16711680)>>16,(b.id&65280)>>8,b.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return b.type!=="video"&&(E[E.length-1]=0),u(Y.trex,E)},(function(){var b,E,C;C=function(A,R){var P=0,J=0,se=0,ae=0;return A.length&&(A[0].duration!==void 0&&(P=1),A[0].size!==void 0&&(J=2),A[0].flags!==void 0&&(se=4),A[0].compositionTimeOffset!==void 0&&(ae=8)),[0,0,P|J|se|ae,1,(A.length&4278190080)>>>24,(A.length&16711680)>>>16,(A.length&65280)>>>8,A.length&255,(R&4278190080)>>>24,(R&16711680)>>>16,(R&65280)>>>8,R&255]},E=function(A,R){var P,J,se,ae,ce,ge;for(ae=A.samples||[],R+=20+16*ae.length,se=C(ae,R),J=new Uint8Array(se.length+ae.length*16),J.set(se),P=se.length,ge=0;ge>>24,J[P++]=(ce.duration&16711680)>>>16,J[P++]=(ce.duration&65280)>>>8,J[P++]=ce.duration&255,J[P++]=(ce.size&4278190080)>>>24,J[P++]=(ce.size&16711680)>>>16,J[P++]=(ce.size&65280)>>>8,J[P++]=ce.size&255,J[P++]=ce.flags.isLeading<<2|ce.flags.dependsOn,J[P++]=ce.flags.isDependedOn<<6|ce.flags.hasRedundancy<<4|ce.flags.paddingValue<<1|ce.flags.isNonSyncSample,J[P++]=ce.flags.degradationPriority&61440,J[P++]=ce.flags.degradationPriority&15,J[P++]=(ce.compositionTimeOffset&4278190080)>>>24,J[P++]=(ce.compositionTimeOffset&16711680)>>>16,J[P++]=(ce.compositionTimeOffset&65280)>>>8,J[P++]=ce.compositionTimeOffset&255;return u(Y.trun,J)},b=function(A,R){var P,J,se,ae,ce,ge;for(ae=A.samples||[],R+=20+8*ae.length,se=C(ae,R),P=new Uint8Array(se.length+ae.length*8),P.set(se),J=se.length,ge=0;ge>>24,P[J++]=(ce.duration&16711680)>>>16,P[J++]=(ce.duration&65280)>>>8,P[J++]=ce.duration&255,P[J++]=(ce.size&4278190080)>>>24,P[J++]=(ce.size&16711680)>>>16,P[J++]=(ce.size&65280)>>>8,P[J++]=ce.size&255;return u(Y.trun,P)},Q=function(A,R){return A.type==="audio"?b(A,R):E(A,R)}})();var Me={ftyp:f,mdat:p,moof:x,moov:_,initSegment:function(b){var E=f(),C=_(b),A;return A=new Uint8Array(E.byteLength+C.byteLength),A.set(E),A.set(C,E.byteLength),A}},et=function(b){var E,C,A=[],R=[];for(R.byteLength=0,R.nalCount=0,R.duration=0,A.byteLength=0,E=0;E1&&(E=b.shift(),b.byteLength-=E.byteLength,b.nalCount-=E.nalCount,b[0][0].dts=E.dts,b[0][0].pts=E.pts,b[0][0].duration+=E.duration),b},At=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},mt=function(b,E){var C=At();return C.dataOffset=E,C.compositionTimeOffset=b.pts-b.dts,C.duration=b.duration,C.size=4*b.length,C.size+=b.byteLength,b.keyFrame&&(C.flags.dependsOn=2,C.flags.isNonSyncSample=0),C},Vt=function(b,E){var C,A,R,P,J,se=E||0,ae=[];for(C=0;Ckt.ONE_SECOND_IN_TS/2))){for(ce=Ot()[b.samplerate],ce||(ce=E[0].data),ge=0;ge=C?b:(E.minSegmentDts=1/0,b.filter(function(A){return A.dts>=C?(E.minSegmentDts=Math.min(E.minSegmentDts,A.dts),E.minSegmentPts=E.minSegmentDts,!0):!1}))},Ai=function(b){var E,C,A=[];for(E=0;E=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(b),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},oi.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},oi.prototype.addText=function(b){this.rows[this.rowIdx]+=b},oi.prototype.backspace=function(){if(!this.isEmpty()){var b=this.rows[this.rowIdx];this.rows[this.rowIdx]=b.substr(0,b.length-1)}};var ei=function(b,E,C){this.serviceNum=b,this.text="",this.currentWindow=new oi(-1),this.windows=[],this.stream=C,typeof E=="string"&&this.createTextDecoder(E)};ei.prototype.init=function(b,E){this.startPts=b;for(var C=0;C<8;C++)this.windows[C]=new oi(C),typeof E=="function"&&(this.windows[C].beforeRowOverflow=E)},ei.prototype.setCurrentWindow=function(b){this.currentWindow=this.windows[b]},ei.prototype.createTextDecoder=function(b){if(typeof TextDecoder>"u")this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(b)}catch(E){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+b+" encoding. "+E})}};var Ht=function(b){b=b||{},Ht.prototype.init.call(this);var E=this,C=b.captionServices||{},A={},R;Object.keys(C).forEach(P=>{R=C[P],/^SERVICE/.test(P)&&(A[P]=R.encoding)}),this.serviceEncodings=A,this.current708Packet=null,this.services={},this.push=function(P){P.type===3?(E.new708Packet(),E.add708Bytes(P)):(E.current708Packet===null&&E.new708Packet(),E.add708Bytes(P))}};Ht.prototype=new ss,Ht.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Ht.prototype.add708Bytes=function(b){var E=b.ccData,C=E>>>8,A=E&255;this.current708Packet.ptsVals.push(b.pts),this.current708Packet.data.push(C),this.current708Packet.data.push(A)},Ht.prototype.push708Packet=function(){var b=this.current708Packet,E=b.data,C=null,A=null,R=0,P=E[R++];for(b.seq=P>>6,b.sizeCode=P&63;R>5,A=P&31,C===7&&A>0&&(P=E[R++],C=P),this.pushServiceBlock(C,R,A),A>0&&(R+=A-1)},Ht.prototype.pushServiceBlock=function(b,E,C){var A,R=E,P=this.current708Packet.data,J=this.services[b];for(J||(J=this.initService(b,R));R("0"+(vt&255).toString(16)).slice(-2)).join("")}if(R?(Pe=[se,ae],b++):Pe=[se],E.textDecoder_&&!A)ge=E.textDecoder_.decode(new Uint8Array(Pe));else if(R){const je=ut(Pe);ge=String.fromCharCode(parseInt(je,16))}else ge=es(J|se);return ce.pendingNewLine&&!ce.isEmpty()&&ce.newLine(this.getPts(b)),ce.pendingNewLine=!1,ce.addText(ge),b},Ht.prototype.multiByteCharacter=function(b,E){var C=this.current708Packet.data,A=C[b+1],R=C[b+2];return Pi(A)&&Pi(R)&&(b=this.handleText(++b,E,{isMultiByte:!0})),b},Ht.prototype.setCurrentWindow=function(b,E){var C=this.current708Packet.data,A=C[b],R=A&7;return E.setCurrentWindow(R),b},Ht.prototype.defineWindow=function(b,E){var C=this.current708Packet.data,A=C[b],R=A&7;E.setCurrentWindow(R);var P=E.currentWindow;return A=C[++b],P.visible=(A&32)>>5,P.rowLock=(A&16)>>4,P.columnLock=(A&8)>>3,P.priority=A&7,A=C[++b],P.relativePositioning=(A&128)>>7,P.anchorVertical=A&127,A=C[++b],P.anchorHorizontal=A,A=C[++b],P.anchorPoint=(A&240)>>4,P.rowCount=A&15,A=C[++b],P.columnCount=A&63,A=C[++b],P.windowStyle=(A&56)>>3,P.penStyle=A&7,P.virtualRowCount=P.rowCount+1,b},Ht.prototype.setWindowAttributes=function(b,E){var C=this.current708Packet.data,A=C[b],R=E.currentWindow.winAttr;return A=C[++b],R.fillOpacity=(A&192)>>6,R.fillRed=(A&48)>>4,R.fillGreen=(A&12)>>2,R.fillBlue=A&3,A=C[++b],R.borderType=(A&192)>>6,R.borderRed=(A&48)>>4,R.borderGreen=(A&12)>>2,R.borderBlue=A&3,A=C[++b],R.borderType+=(A&128)>>5,R.wordWrap=(A&64)>>6,R.printDirection=(A&48)>>4,R.scrollDirection=(A&12)>>2,R.justify=A&3,A=C[++b],R.effectSpeed=(A&240)>>4,R.effectDirection=(A&12)>>2,R.displayEffect=A&3,b},Ht.prototype.flushDisplayed=function(b,E){for(var C=[],A=0;A<8;A++)E.windows[A].visible&&!E.windows[A].isEmpty()&&C.push(E.windows[A].getText());E.endPts=b,E.text=C.join(` + +`),this.pushCaption(E),E.startPts=b},Ht.prototype.pushCaption=function(b){b.text!==""&&(this.trigger("data",{startPts:b.startPts,endPts:b.endPts,text:b.text,stream:"cc708_"+b.serviceNum}),b.text="",b.startPts=b.endPts)},Ht.prototype.displayWindows=function(b,E){var C=this.current708Packet.data,A=C[++b],R=this.getPts(b);this.flushDisplayed(R,E);for(var P=0;P<8;P++)A&1<>4,R.offset=(A&12)>>2,R.penSize=A&3,A=C[++b],R.italics=(A&128)>>7,R.underline=(A&64)>>6,R.edgeType=(A&56)>>3,R.fontStyle=A&7,b},Ht.prototype.setPenColor=function(b,E){var C=this.current708Packet.data,A=C[b],R=E.currentWindow.penColor;return A=C[++b],R.fgOpacity=(A&192)>>6,R.fgRed=(A&48)>>4,R.fgGreen=(A&12)>>2,R.fgBlue=A&3,A=C[++b],R.bgOpacity=(A&192)>>6,R.bgRed=(A&48)>>4,R.bgGreen=(A&12)>>2,R.bgBlue=A&3,A=C[++b],R.edgeRed=(A&48)>>4,R.edgeGreen=(A&12)>>2,R.edgeBlue=A&3,b},Ht.prototype.setPenLocation=function(b,E){var C=this.current708Packet.data,A=C[b],R=E.currentWindow.penLoc;return E.currentWindow.pendingNewLine=!0,A=C[++b],R.row=A&15,A=C[++b],R.column=A&63,b},Ht.prototype.reset=function(b,E){var C=this.getPts(b);return this.flushDisplayed(C,E),this.initService(E.serviceNum,b)};var Rs={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},Zs=function(b){return b===null?"":(b=Rs[b]||b,String.fromCharCode(b))},xe=14,Ne=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],Oe=function(){for(var b=[],E=xe+1;E--;)b.push({text:"",indent:0,offset:0});return b},Fe=function(b,E){Fe.prototype.init.call(this),this.field_=b||0,this.dataChannel_=E||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(C){var A,R,P,J,se;if(A=C.ccData&32639,A===this.lastControlCode_){this.lastControlCode_=null;return}if((A&61440)===4096?this.lastControlCode_=A:A!==this.PADDING_&&(this.lastControlCode_=null),P=A>>>8,J=A&255,A!==this.PADDING_)if(A===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(A===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(C.pts),this.flushDisplayed(C.pts),R=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=R,this.startPts_=C.pts;else if(A===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(C.pts);else if(A===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(C.pts);else if(A===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(C.pts);else if(A===this.CARRIAGE_RETURN_)this.clearFormatting(C.pts),this.flushDisplayed(C.pts),this.shiftRowsUp_(),this.startPts_=C.pts;else if(A===this.BACKSPACE_)this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(A===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(C.pts),this.displayed_=Oe();else if(A===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=Oe();else if(A===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(C.pts),this.displayed_=Oe()),this.mode_="paintOn",this.startPts_=C.pts;else if(this.isSpecialCharacter(P,J))P=(P&3)<<8,se=Zs(P|J),this[this.mode_](C.pts,se),this.column_++;else if(this.isExtCharacter(P,J))this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),P=(P&3)<<8,se=Zs(P|J),this[this.mode_](C.pts,se),this.column_++;else if(this.isMidRowCode(P,J))this.clearFormatting(C.pts),this[this.mode_](C.pts," "),this.column_++,(J&14)===14&&this.addFormatting(C.pts,["i"]),(J&1)===1&&this.addFormatting(C.pts,["u"]);else if(this.isOffsetControlCode(P,J)){const ce=J&3;this.nonDisplayed_[this.row_].offset=ce,this.column_+=ce}else if(this.isPAC(P,J)){var ae=Ne.indexOf(A&7968);if(this.mode_==="rollUp"&&(ae-this.rollUpRows_+1<0&&(ae=this.rollUpRows_-1),this.setRollUp(C.pts,ae)),ae!==this.row_&&ae>=0&&ae<=14&&(this.clearFormatting(C.pts),this.row_=ae),J&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(C.pts,["u"]),(A&16)===16){const ce=(A&14)>>1;this.column_=ce*4,this.nonDisplayed_[this.row_].indent+=ce}this.isColorPAC(J)&&(J&14)===14&&this.addFormatting(C.pts,["i"])}else this.isNormalChar(P)&&(J===0&&(J=null),se=Zs(P),se+=Zs(J),this[this.mode_](C.pts,se),this.column_+=se.length)}};Fe.prototype=new ss,Fe.prototype.flushDisplayed=function(b){const E=A=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+A+"."})},C=[];this.displayed_.forEach((A,R)=>{if(A&&A.text&&A.text.length){try{A.text=A.text.trim()}catch{E(R)}A.text.length&&C.push({text:A.text,line:R+1,position:10+Math.min(70,A.indent*10)+A.offset*2.5})}else A==null&&E(R)}),C.length&&this.trigger("data",{startPts:this.startPts_,endPts:b,content:C,stream:this.name_})},Fe.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=Oe(),this.nonDisplayed_=Oe(),this.lastControlCode_=null,this.column_=0,this.row_=xe,this.rollUpRows_=2,this.formatting_=[]},Fe.prototype.setConstants=function(){this.dataChannel_===0?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):this.dataChannel_===1&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=this.CONTROL_|32,this.END_OF_CAPTION_=this.CONTROL_|47,this.ROLL_UP_2_ROWS_=this.CONTROL_|37,this.ROLL_UP_3_ROWS_=this.CONTROL_|38,this.ROLL_UP_4_ROWS_=this.CONTROL_|39,this.CARRIAGE_RETURN_=this.CONTROL_|45,this.RESUME_DIRECT_CAPTIONING_=this.CONTROL_|41,this.BACKSPACE_=this.CONTROL_|33,this.ERASE_DISPLAYED_MEMORY_=this.CONTROL_|44,this.ERASE_NON_DISPLAYED_MEMORY_=this.CONTROL_|46},Fe.prototype.isSpecialCharacter=function(b,E){return b===this.EXT_&&E>=48&&E<=63},Fe.prototype.isExtCharacter=function(b,E){return(b===this.EXT_+1||b===this.EXT_+2)&&E>=32&&E<=63},Fe.prototype.isMidRowCode=function(b,E){return b===this.EXT_&&E>=32&&E<=47},Fe.prototype.isOffsetControlCode=function(b,E){return b===this.OFFSET_&&E>=33&&E<=35},Fe.prototype.isPAC=function(b,E){return b>=this.BASE_&&b=64&&E<=127},Fe.prototype.isColorPAC=function(b){return b>=64&&b<=79||b>=96&&b<=127},Fe.prototype.isNormalChar=function(b){return b>=32&&b<=127},Fe.prototype.setRollUp=function(b,E){if(this.mode_!=="rollUp"&&(this.row_=xe,this.mode_="rollUp",this.flushDisplayed(b),this.nonDisplayed_=Oe(),this.displayed_=Oe()),E!==void 0&&E!==this.row_)for(var C=0;C"},"");this[this.mode_](b,C)},Fe.prototype.clearFormatting=function(b){if(this.formatting_.length){var E=this.formatting_.reverse().reduce(function(C,A){return C+""},"");this.formatting_=[],this[this.mode_](b,E)}},Fe.prototype.popOn=function(b,E){var C=this.nonDisplayed_[this.row_].text;C+=E,this.nonDisplayed_[this.row_].text=C},Fe.prototype.rollUp=function(b,E){var C=this.displayed_[this.row_].text;C+=E,this.displayed_[this.row_].text=C},Fe.prototype.shiftRowsUp_=function(){var b;for(b=0;bE&&(C=-1);Math.abs(E-b)>ye;)b+=C*he;return b},Ie=function(b){var E,C;Ie.prototype.init.call(this),this.type_=b||me,this.push=function(A){if(A.type==="metadata"){this.trigger("data",A);return}this.type_!==me&&A.type!==this.type_||(C===void 0&&(C=A.dts),A.dts=Qe(A.dts,C),A.pts=Qe(A.pts,C),E=A.dts,this.trigger("data",A))},this.flush=function(){C=E,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){C=void 0,E=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};Ie.prototype=new Ce;var Ye={TimestampRolloverStream:Ie,handleRollover:Qe},Ct=(b,E,C)=>{if(!b)return-1;for(var A=C;A";b.data[0]===Mt.Utf8&&(C=Rt(b.data,0,E),!(C<0)&&(b.mimeType=at(b.data,E,C),E=C+1,b.pictureType=b.data[E],E++,A=Rt(b.data,0,E),!(A<0)&&(b.description=rt(b.data,E,A),E=A+1,b.mimeType===R?b.url=at(b.data,E,b.data.length):b.pictureData=b.data.subarray(E,b.data.length))))},"T*":function(b){b.data[0]===Mt.Utf8&&(b.value=rt(b.data,1,b.data.length).replace(/\0*$/,""),b.values=b.value.split("\0"))},TXXX:function(b){var E;b.data[0]===Mt.Utf8&&(E=Rt(b.data,0,1),E!==-1&&(b.description=rt(b.data,1,E),b.value=rt(b.data,E+1,b.data.length).replace(/\0*$/,""),b.data=b.value))},"W*":function(b){b.url=at(b.data,0,b.data.length).replace(/\0.*$/,"")},WXXX:function(b){var E;b.data[0]===Mt.Utf8&&(E=Rt(b.data,0,1),E!==-1&&(b.description=rt(b.data,1,E),b.url=at(b.data,E+1,b.data.length).replace(/\0.*$/,"")))},PRIV:function(b){var E;for(E=0;E>>2;vt*=4,vt+=je[7]&3,ge.timeStamp=vt,se.pts===void 0&&se.dts===void 0&&(se.pts=ge.timeStamp,se.dts=ge.timeStamp),this.trigger("timestamp",ge)}se.frames.push(ge),ae+=10,ae+=ce}while(ae>>4>1&&(J+=R[J]+1),P.pid===0)P.type="pat",b(R.subarray(J),P),this.trigger("data",P);else if(P.pid===this.pmtPid)for(P.type="pmt",b(R.subarray(J),P),this.trigger("data",P);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([R,J,P]):this.processPes_(R,J,P)},this.processPes_=function(R,P,J){J.pid===this.programMapTable.video?J.streamType=Xi.H264_STREAM_TYPE:J.pid===this.programMapTable.audio?J.streamType=Xi.ADTS_STREAM_TYPE:J.streamType=this.programMapTable["timed-metadata"][J.pid],J.type="pes",J.data=R.subarray(P),this.trigger("data",J)}},sr.prototype=new Wi,sr.STREAM_TYPES={h264:27,adts:15},Xl=function(){var b=this,E=!1,C={data:[],size:0},A={data:[],size:0},R={data:[],size:0},P,J=function(ae,ce){var ge;const Pe=ae[0]<<16|ae[1]<<8|ae[2];ce.data=new Uint8Array,Pe===1&&(ce.packetLength=6+(ae[4]<<8|ae[5]),ce.dataAlignmentIndicator=(ae[6]&4)!==0,ge=ae[7],ge&192&&(ce.pts=(ae[9]&14)<<27|(ae[10]&255)<<20|(ae[11]&254)<<12|(ae[12]&255)<<5|(ae[13]&254)>>>3,ce.pts*=4,ce.pts+=(ae[13]&6)>>>1,ce.dts=ce.pts,ge&64&&(ce.dts=(ae[14]&14)<<27|(ae[15]&255)<<20|(ae[16]&254)<<12|(ae[17]&255)<<5|(ae[18]&254)>>>3,ce.dts*=4,ce.dts+=(ae[18]&6)>>>1)),ce.data=ae.subarray(9+ae[8]))},se=function(ae,ce,ge){var Pe=new Uint8Array(ae.size),ut={type:ce},je=0,vt=0,qt=!1,bs;if(!(!ae.data.length||ae.size<9)){for(ut.trackId=ae.data[0].pid,je=0;je>5,ae=((E[R+6]&3)+1)*1024,ce=ae*yr/eu[(E[R+2]&60)>>>2],E.byteLength-R>>6&3)+1,channelcount:(E[R+2]&1)<<2|(E[R+3]&192)>>>6,samplerate:eu[(E[R+2]&60)>>>2],samplingfrequencyindex:(E[R+2]&60)>>>2,samplesize:16,data:E.subarray(R+7+J,R+P)}),C++,R+=P}typeof ge=="number"&&(this.skipWarn_(ge,R),ge=null),E=E.subarray(R)}},this.flush=function(){C=0,this.trigger("done")},this.reset=function(){E=void 0,this.trigger("reset")},this.endTimeline=function(){E=void 0,this.trigger("endedtimeline")}},Wa.prototype=new Jl;var Xa=Wa,ga;ga=function(b){var E=b.byteLength,C=0,A=0;this.length=function(){return 8*E},this.bitsAvailable=function(){return 8*E+A},this.loadWord=function(){var R=b.byteLength-E,P=new Uint8Array(4),J=Math.min(4,E);if(J===0)throw new Error("no bytes available");P.set(b.subarray(R,R+J)),C=new DataView(P.buffer).getUint32(0),A=J*8,E-=J},this.skipBits=function(R){var P;A>R?(C<<=R,A-=R):(R-=A,P=Math.floor(R/8),R-=P*8,E-=P,this.loadWord(),C<<=R,A-=R)},this.readBits=function(R){var P=Math.min(A,R),J=C>>>32-P;return A-=P,A>0?C<<=P:E>0&&this.loadWord(),P=R-P,P>0?J<>>R)!==0)return C<<=R,A-=R,R;return this.loadWord(),R+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var R=this.skipLeadingZeros();return this.readBits(R+1)-1},this.readExpGolomb=function(){var R=this.readUnsignedExpGolomb();return 1&R?1+R>>>1:-1*(R>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var Nh=ga,tu=t,Oh=Nh,Rr,vn,iu;vn=function(){var b=0,E,C;vn.prototype.init.call(this),this.push=function(A){var R;C?(R=new Uint8Array(C.byteLength+A.data.byteLength),R.set(C),R.set(A.data,C.byteLength),C=R):C=A.data;for(var P=C.byteLength;b3&&this.trigger("data",C.subarray(b+3)),C=null,b=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},vn.prototype=new tu,iu={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},Rr=function(){var b=new vn,E,C,A,R,P,J,se;Rr.prototype.init.call(this),E=this,this.push=function(ae){ae.type==="video"&&(C=ae.trackId,A=ae.pts,R=ae.dts,b.push(ae))},b.on("data",function(ae){var ce={trackId:C,pts:A,dts:R,data:ae,nalUnitTypeCode:ae[0]&31};switch(ce.nalUnitTypeCode){case 5:ce.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:ce.nalUnitType="sei_rbsp",ce.escapedRBSP=P(ae.subarray(1));break;case 7:ce.nalUnitType="seq_parameter_set_rbsp",ce.escapedRBSP=P(ae.subarray(1)),ce.config=J(ce.escapedRBSP);break;case 8:ce.nalUnitType="pic_parameter_set_rbsp";break;case 9:ce.nalUnitType="access_unit_delimiter_rbsp";break}E.trigger("data",ce)}),b.on("done",function(){E.trigger("done")}),b.on("partialdone",function(){E.trigger("partialdone")}),b.on("reset",function(){E.trigger("reset")}),b.on("endedtimeline",function(){E.trigger("endedtimeline")}),this.flush=function(){b.flush()},this.partialFlush=function(){b.partialFlush()},this.reset=function(){b.reset()},this.endTimeline=function(){b.endTimeline()},se=function(ae,ce){var ge=8,Pe=8,ut,je;for(ut=0;ut>4;return C=C>=0?C:0,R?C+20:C+10},il=function(b,E){return b.length-E<10||b[E]!==73||b[E+1]!==68||b[E+2]!==51?E:(E+=su(b,E),il(b,E))},Mh=function(b){var E=il(b,0);return b.length>=E+2&&(b[E]&255)===255&&(b[E+1]&240)===240&&(b[E+1]&22)===16},sl=function(b){return b[0]<<21|b[1]<<14|b[2]<<7|b[3]},nu=function(b,E,C){var A,R="";for(A=E;A>5,A=b[E+4]<<3,R=b[E+3]&6144;return R|A|C},ya=function(b,E){return b[E]===73&&b[E+1]===68&&b[E+2]===51?"timed-metadata":b[E]&!0&&(b[E+1]&240)===240?"audio":null},ru=function(b){for(var E=0;E+5>>2]}return null},nl=function(b){var E,C,A,R;E=10,b[5]&64&&(E+=4,E+=sl(b.subarray(10,14)));do{if(C=sl(b.subarray(E+4,E+8)),C<1)return null;if(R=String.fromCharCode(b[E],b[E+1],b[E+2],b[E+3]),R==="PRIV"){A=b.subarray(E+10,E+C+10);for(var P=0;P>>2;return ae*=4,ae+=se[7]&3,ae}break}}E+=10,E+=C}while(E=3;){if(b[R]===73&&b[R+1]===68&&b[R+2]===51){if(b.length-R<10||(A=au.parseId3TagSize(b,R),R+A>b.length))break;J={type:"timed-metadata",data:b.subarray(R,R+A)},this.trigger("data",J),R+=A;continue}else if((b[R]&255)===255&&(b[R+1]&240)===240){if(b.length-R<7||(A=au.parseAdtsSize(b,R),R+A>b.length))break;se={type:"audio",data:b.subarray(R,R+A),pts:E,dts:E},this.trigger("data",se),R+=A;continue}R++}P=b.length-R,P>0?b=b.subarray(R):b=new Uint8Array},this.reset=function(){b=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){b=new Uint8Array,this.trigger("endedtimeline")}},Nr.prototype=new Bc;var ou=Nr,Bh=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],c0=Bh,d0=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],h0=d0,Qa=t,rl=Me,al=tt,lu=bt,Un=oe,vr=u0,ol=Xe,Fh=Xa,f0=tl.H264Stream,m0=ou,p0=Pc.isLikelyAacData,Fc=Xe.ONE_SECOND_IN_TS,Uh=c0,jh=h0,uu,Za,cu,va,g0=function(b,E){E.stream=b,this.trigger("log",E)},$h=function(b,E){for(var C=Object.keys(E),A=0;A=-1e4&&ge<=ae&&(!Pe||ce>ge)&&(Pe=je,ce=ge)));return Pe?Pe.gop:null},this.alignGopsAtStart_=function(se){var ae,ce,ge,Pe,ut,je,vt,qt;for(ut=se.byteLength,je=se.nalCount,vt=se.duration,ae=ce=0;aege.pts){ae++;continue}ce++,ut-=Pe.byteLength,je-=Pe.nalCount,vt-=Pe.duration}return ce===0?se:ce===se.length?null:(qt=se.slice(ce),qt.byteLength=ut,qt.duration=vt,qt.nalCount=je,qt.pts=qt[0].pts,qt.dts=qt[0].dts,qt)},this.alignGopsAtEnd_=function(se){var ae,ce,ge,Pe,ut,je;for(ae=R.length-1,ce=se.length-1,ut=null,je=!1;ae>=0&&ce>=0;){if(ge=R[ae],Pe=se[ce],ge.pts===Pe.pts){je=!0;break}if(ge.pts>Pe.pts){ae--;continue}ae===R.length-1&&(ut=ce),ce--}if(!je&&ut===null)return null;var vt;if(je?vt=ce:vt=ut,vt===0)return se;var qt=se.slice(vt),bs=qt.reduce(function(un,$r){return un.byteLength+=$r.byteLength,un.duration+=$r.duration,un.nalCount+=$r.nalCount,un},{byteLength:0,duration:0,nalCount:0});return qt.byteLength=bs.byteLength,qt.duration=bs.duration,qt.nalCount=bs.nalCount,qt.pts=qt[0].pts,qt.dts=qt[0].dts,qt},this.alignGopsWith=function(se){R=se}},uu.prototype=new Qa,va=function(b,E){this.numberOfTracks=0,this.metadataStream=E,b=b||{},typeof b.remux<"u"?this.remuxTracks=!!b.remux:this.remuxTracks=!0,typeof b.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=b.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,va.prototype.init.call(this),this.push=function(C){if(C.content||C.text)return this.pendingCaptions.push(C);if(C.frames)return this.pendingMetadata.push(C);this.pendingTracks.push(C.track),this.pendingBytes+=C.boxes.byteLength,C.track.type==="video"&&(this.videoTrack=C.track,this.pendingBoxes.push(C.boxes)),C.track.type==="audio"&&(this.audioTrack=C.track,this.pendingBoxes.unshift(C.boxes))}},va.prototype=new Qa,va.prototype.flush=function(b){var E=0,C={captions:[],captionStreams:{},metadata:[],info:{}},A,R,P,J=0,se;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(J=this.videoTrack.timelineStartInfo.pts,jh.forEach(function(ae){C.info[ae]=this.videoTrack[ae]},this)):this.audioTrack&&(J=this.audioTrack.timelineStartInfo.pts,Uh.forEach(function(ae){C.info[ae]=this.audioTrack[ae]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?C.type=this.pendingTracks[0].type:C.type="combined",this.emittedTracks+=this.pendingTracks.length,P=rl.initSegment(this.pendingTracks),C.initSegment=new Uint8Array(P.byteLength),C.initSegment.set(P),C.data=new Uint8Array(this.pendingBytes),se=0;se=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},va.prototype.setRemux=function(b){this.remuxTracks=b},cu=function(b){var E=this,C=!0,A,R;cu.prototype.init.call(this),b=b||{},this.baseMediaDecodeTime=b.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var P={};this.transmuxPipeline_=P,P.type="aac",P.metadataStream=new vr.MetadataStream,P.aacStream=new m0,P.audioTimestampRolloverStream=new vr.TimestampRolloverStream("audio"),P.timedMetadataTimestampRolloverStream=new vr.TimestampRolloverStream("timed-metadata"),P.adtsStream=new Fh,P.coalesceStream=new va(b,P.metadataStream),P.headOfPipeline=P.aacStream,P.aacStream.pipe(P.audioTimestampRolloverStream).pipe(P.adtsStream),P.aacStream.pipe(P.timedMetadataTimestampRolloverStream).pipe(P.metadataStream).pipe(P.coalesceStream),P.metadataStream.on("timestamp",function(J){P.aacStream.setTimestamp(J.timeStamp)}),P.aacStream.on("data",function(J){J.type!=="timed-metadata"&&J.type!=="audio"||P.audioSegmentStream||(R=R||{timelineStartInfo:{baseMediaDecodeTime:E.baseMediaDecodeTime},codec:"adts",type:"audio"},P.coalesceStream.numberOfTracks++,P.audioSegmentStream=new Za(R,b),P.audioSegmentStream.on("log",E.getLogTrigger_("audioSegmentStream")),P.audioSegmentStream.on("timingInfo",E.trigger.bind(E,"audioTimingInfo")),P.adtsStream.pipe(P.audioSegmentStream).pipe(P.coalesceStream),E.trigger("trackinfo",{hasAudio:!!R,hasVideo:!!A}))}),P.coalesceStream.on("data",this.trigger.bind(this,"data")),P.coalesceStream.on("done",this.trigger.bind(this,"done")),$h(this,P)},this.setupTsPipeline=function(){var P={};this.transmuxPipeline_=P,P.type="ts",P.metadataStream=new vr.MetadataStream,P.packetStream=new vr.TransportPacketStream,P.parseStream=new vr.TransportParseStream,P.elementaryStream=new vr.ElementaryStream,P.timestampRolloverStream=new vr.TimestampRolloverStream,P.adtsStream=new Fh,P.h264Stream=new f0,P.captionStream=new vr.CaptionStream(b),P.coalesceStream=new va(b,P.metadataStream),P.headOfPipeline=P.packetStream,P.packetStream.pipe(P.parseStream).pipe(P.elementaryStream).pipe(P.timestampRolloverStream),P.timestampRolloverStream.pipe(P.h264Stream),P.timestampRolloverStream.pipe(P.adtsStream),P.timestampRolloverStream.pipe(P.metadataStream).pipe(P.coalesceStream),P.h264Stream.pipe(P.captionStream).pipe(P.coalesceStream),P.elementaryStream.on("data",function(J){var se;if(J.type==="metadata"){for(se=J.tracks.length;se--;)!A&&J.tracks[se].type==="video"?(A=J.tracks[se],A.timelineStartInfo.baseMediaDecodeTime=E.baseMediaDecodeTime):!R&&J.tracks[se].type==="audio"&&(R=J.tracks[se],R.timelineStartInfo.baseMediaDecodeTime=E.baseMediaDecodeTime);A&&!P.videoSegmentStream&&(P.coalesceStream.numberOfTracks++,P.videoSegmentStream=new uu(A,b),P.videoSegmentStream.on("log",E.getLogTrigger_("videoSegmentStream")),P.videoSegmentStream.on("timelineStartInfo",function(ae){R&&!b.keepOriginalTimestamps&&(R.timelineStartInfo=ae,P.audioSegmentStream.setEarliestDts(ae.dts-E.baseMediaDecodeTime))}),P.videoSegmentStream.on("processedGopsInfo",E.trigger.bind(E,"gopInfo")),P.videoSegmentStream.on("segmentTimingInfo",E.trigger.bind(E,"videoSegmentTimingInfo")),P.videoSegmentStream.on("baseMediaDecodeTime",function(ae){R&&P.audioSegmentStream.setVideoBaseMediaDecodeTime(ae)}),P.videoSegmentStream.on("timingInfo",E.trigger.bind(E,"videoTimingInfo")),P.h264Stream.pipe(P.videoSegmentStream).pipe(P.coalesceStream)),R&&!P.audioSegmentStream&&(P.coalesceStream.numberOfTracks++,P.audioSegmentStream=new Za(R,b),P.audioSegmentStream.on("log",E.getLogTrigger_("audioSegmentStream")),P.audioSegmentStream.on("timingInfo",E.trigger.bind(E,"audioTimingInfo")),P.audioSegmentStream.on("segmentTimingInfo",E.trigger.bind(E,"audioSegmentTimingInfo")),P.adtsStream.pipe(P.audioSegmentStream).pipe(P.coalesceStream)),E.trigger("trackinfo",{hasAudio:!!R,hasVideo:!!A})}}),P.coalesceStream.on("data",this.trigger.bind(this,"data")),P.coalesceStream.on("id3Frame",function(J){J.dispatchType=P.metadataStream.dispatchType,E.trigger("id3Frame",J)}),P.coalesceStream.on("caption",this.trigger.bind(this,"caption")),P.coalesceStream.on("done",this.trigger.bind(this,"done")),$h(this,P)},this.setBaseMediaDecodeTime=function(P){var J=this.transmuxPipeline_;b.keepOriginalTimestamps||(this.baseMediaDecodeTime=P),R&&(R.timelineStartInfo.dts=void 0,R.timelineStartInfo.pts=void 0,Un.clearDtsInfo(R),J.audioTimestampRolloverStream&&J.audioTimestampRolloverStream.discontinuity()),A&&(J.videoSegmentStream&&(J.videoSegmentStream.gopCache_=[]),A.timelineStartInfo.dts=void 0,A.timelineStartInfo.pts=void 0,Un.clearDtsInfo(A),J.captionStream.reset()),J.timestampRolloverStream&&J.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(P){R&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(P)},this.setRemux=function(P){var J=this.transmuxPipeline_;b.remux=P,J&&J.coalesceStream&&J.coalesceStream.setRemux(P)},this.alignGopsWith=function(P){A&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(P)},this.getLogTrigger_=function(P){var J=this;return function(se){se.stream=P,J.trigger("log",se)}},this.push=function(P){if(C){var J=p0(P);J&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!J&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),C=!1}this.transmuxPipeline_.headOfPipeline.push(P)},this.flush=function(){C=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}},cu.prototype=new Qa;var y0={Transmuxer:cu},v0=function(b){return b>>>0},x0=function(b){return("00"+b.toString(16)).slice(-2)},Ja={toUnsigned:v0,toHexString:x0},ll=function(b){var E="";return E+=String.fromCharCode(b[0]),E+=String.fromCharCode(b[1]),E+=String.fromCharCode(b[2]),E+=String.fromCharCode(b[3]),E},Gh=ll,zh=Ja.toUnsigned,qh=Gh,Uc=function(b,E){var C=[],A,R,P,J,se;if(!E.length)return null;for(A=0;A1?A+R:b.byteLength,P===E[0]&&(E.length===1?C.push(b.subarray(A+8,J)):(se=Uc(b.subarray(A+8,J),E.slice(1)),se.length&&(C=C.concat(se)))),A=J;return C},du=Uc,Kh=Ja.toUnsigned,eo=r.getUint64,b0=function(b){var E={version:b[0],flags:new Uint8Array(b.subarray(1,4))};return E.version===1?E.baseMediaDecodeTime=eo(b.subarray(4)):E.baseMediaDecodeTime=Kh(b[4]<<24|b[5]<<16|b[6]<<8|b[7]),E},jc=b0,T0=function(b){var E=new DataView(b.buffer,b.byteOffset,b.byteLength),C={version:b[0],flags:new Uint8Array(b.subarray(1,4)),trackId:E.getUint32(4)},A=C.flags[2]&1,R=C.flags[2]&2,P=C.flags[2]&8,J=C.flags[2]&16,se=C.flags[2]&32,ae=C.flags[0]&65536,ce=C.flags[0]&131072,ge;return ge=8,A&&(ge+=4,C.baseDataOffset=E.getUint32(12),ge+=4),R&&(C.sampleDescriptionIndex=E.getUint32(ge),ge+=4),P&&(C.defaultSampleDuration=E.getUint32(ge),ge+=4),J&&(C.defaultSampleSize=E.getUint32(ge),ge+=4),se&&(C.defaultSampleFlags=E.getUint32(ge)),ae&&(C.durationIsEmpty=!0),!A&&ce&&(C.baseDataOffsetIsMoof=!0),C},$c=T0,Yh=function(b){return{isLeading:(b[0]&12)>>>2,dependsOn:b[0]&3,isDependedOn:(b[1]&192)>>>6,hasRedundancy:(b[1]&48)>>>4,paddingValue:(b[1]&14)>>>1,isNonSyncSample:b[1]&1,degradationPriority:b[2]<<8|b[3]}},ul=Yh,to=ul,_0=function(b){var E={version:b[0],flags:new Uint8Array(b.subarray(1,4)),samples:[]},C=new DataView(b.buffer,b.byteOffset,b.byteLength),A=E.flags[2]&1,R=E.flags[2]&4,P=E.flags[1]&1,J=E.flags[1]&2,se=E.flags[1]&4,ae=E.flags[1]&8,ce=C.getUint32(4),ge=8,Pe;for(A&&(E.dataOffset=C.getInt32(ge),ge+=4),R&&ce&&(Pe={flags:to(b.subarray(ge,ge+4))},ge+=4,P&&(Pe.duration=C.getUint32(ge),ge+=4),J&&(Pe.size=C.getUint32(ge),ge+=4),ae&&(E.version===1?Pe.compositionTimeOffset=C.getInt32(ge):Pe.compositionTimeOffset=C.getUint32(ge),ge+=4),E.samples.push(Pe),ce--);ce--;)Pe={},P&&(Pe.duration=C.getUint32(ge),ge+=4),J&&(Pe.size=C.getUint32(ge),ge+=4),se&&(Pe.flags=to(b.subarray(ge,ge+4)),ge+=4),ae&&(E.version===1?Pe.compositionTimeOffset=C.getInt32(ge):Pe.compositionTimeOffset=C.getUint32(ge),ge+=4),E.samples.push(Pe);return E},cl=_0,Hc={tfdt:jc,trun:cl},Vc={parseTfdt:Hc.tfdt,parseTrun:Hc.trun},Gc=function(b){for(var E=0,C=String.fromCharCode(b[E]),A="";C!=="\0";)A+=C,E++,C=String.fromCharCode(b[E]);return A+=C,A},zc={uint8ToCString:Gc},dl=zc.uint8ToCString,Wh=r.getUint64,Xh=function(b){var E=4,C=b[0],A,R,P,J,se,ae,ce,ge;if(C===0){A=dl(b.subarray(E)),E+=A.length,R=dl(b.subarray(E)),E+=R.length;var Pe=new DataView(b.buffer);P=Pe.getUint32(E),E+=4,se=Pe.getUint32(E),E+=4,ae=Pe.getUint32(E),E+=4,ce=Pe.getUint32(E),E+=4}else if(C===1){var Pe=new DataView(b.buffer);P=Pe.getUint32(E),E+=4,J=Wh(b.subarray(E)),E+=8,ae=Pe.getUint32(E),E+=4,ce=Pe.getUint32(E),E+=4,A=dl(b.subarray(E)),E+=A.length,R=dl(b.subarray(E)),E+=R.length}ge=new Uint8Array(b.subarray(E,b.byteLength));var ut={scheme_id_uri:A,value:R,timescale:P||1,presentation_time:J,presentation_time_delta:se,event_duration:ae,id:ce,message_data:ge};return E0(C,ut)?ut:void 0},S0=function(b,E,C,A){return b||b===0?b/E:A+C/E},E0=function(b,E){var C=E.scheme_id_uri!=="\0",A=b===0&&Qh(E.presentation_time_delta)&&C,R=b===1&&Qh(E.presentation_time)&&C;return!(b>1)&&A||R},Qh=function(b){return b!==void 0||b!==null},w0={parseEmsgBox:Xh,scaleTime:S0},hl;typeof window<"u"?hl=window:typeof s<"u"?hl=s:typeof self<"u"?hl=self:hl={};var tn=hl,Or=Ja.toUnsigned,io=Ja.toHexString,rs=du,xa=Gh,hu=w0,qc=$c,A0=cl,so=jc,Kc=r.getUint64,no,fu,Yc,Mr,ba,fl,Wc,xr=tn,Zh=ti.parseId3Frames;no=function(b){var E={},C=rs(b,["moov","trak"]);return C.reduce(function(A,R){var P,J,se,ae,ce;return P=rs(R,["tkhd"])[0],!P||(J=P[0],se=J===0?12:20,ae=Or(P[se]<<24|P[se+1]<<16|P[se+2]<<8|P[se+3]),ce=rs(R,["mdia","mdhd"])[0],!ce)?null:(J=ce[0],se=J===0?12:20,A[ae]=Or(ce[se]<<24|ce[se+1]<<16|ce[se+2]<<8|ce[se+3]),A)},E)},fu=function(b,E){var C;C=rs(E,["moof","traf"]);var A=C.reduce(function(R,P){var J=rs(P,["tfhd"])[0],se=Or(J[4]<<24|J[5]<<16|J[6]<<8|J[7]),ae=b[se]||9e4,ce=rs(P,["tfdt"])[0],ge=new DataView(ce.buffer,ce.byteOffset,ce.byteLength),Pe;ce[0]===1?Pe=Kc(ce.subarray(4,12)):Pe=ge.getUint32(4);let ut;return typeof Pe=="bigint"?ut=Pe/xr.BigInt(ae):typeof Pe=="number"&&!isNaN(Pe)&&(ut=Pe/ae),ut11?(R.codec+=".",R.codec+=io(je[9]),R.codec+=io(je[10]),R.codec+=io(je[11])):R.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(R.codec)?(je=ut.subarray(28),vt=xa(je.subarray(4,8)),vt==="esds"&&je.length>20&&je[19]!==0?(R.codec+="."+io(je[19]),R.codec+="."+io(je[20]>>>2&63).replace(/^0/,"")):R.codec="mp4a.40.2"):R.codec=R.codec.toLowerCase())}var qt=rs(A,["mdia","mdhd"])[0];qt&&(R.timescale=fl(qt)),C.push(R)}),C},Wc=function(b,E=0){var C=rs(b,["emsg"]);return C.map(A=>{var R=hu.parseEmsgBox(new Uint8Array(A)),P=Zh(R.message_data);return{cueTime:hu.scaleTime(R.presentation_time,R.timescale,R.presentation_time_delta,E),duration:hu.scaleTime(R.event_duration,R.timescale),frames:P}})};var ro={findBox:rs,parseType:xa,timescale:no,startTime:fu,compositionStartTime:Yc,videoTrackIds:Mr,tracks:ba,getTimescaleFromMediaHeader:fl,getEmsgID3:Wc};const{parseTrun:Jh}=Vc,{findBox:ef}=ro;var tf=tn,C0=function(b){var E=ef(b,["moof","traf"]),C=ef(b,["mdat"]),A=[];return C.forEach(function(R,P){var J=E[P];A.push({mdat:R,traf:J})}),A},sf=function(b,E,C){var A=E,R=C.defaultSampleDuration||0,P=C.defaultSampleSize||0,J=C.trackId,se=[];return b.forEach(function(ae){var ce=Jh(ae),ge=ce.samples;ge.forEach(function(Pe){Pe.duration===void 0&&(Pe.duration=R),Pe.size===void 0&&(Pe.size=P),Pe.trackId=J,Pe.dts=A,Pe.compositionTimeOffset===void 0&&(Pe.compositionTimeOffset=0),typeof A=="bigint"?(Pe.pts=A+tf.BigInt(Pe.compositionTimeOffset),A+=tf.BigInt(Pe.duration)):(Pe.pts=A+Pe.compositionTimeOffset,A+=Pe.duration)}),se=se.concat(ge)}),se},Xc={getMdatTrafPairs:C0,parseSamples:sf},Qc=Ci.discardEmulationPreventionBytes,jn=ht.CaptionStream,ao=du,xn=jc,oo=$c,{getMdatTrafPairs:Zc,parseSamples:mu}=Xc,pu=function(b,E){for(var C=b,A=0;A0?xn(ge[0]).baseMediaDecodeTime:0,ut=ao(J,["trun"]),je,vt;E===ce&&ut.length>0&&(je=mu(ut,Pe,ae),vt=Jc(P,je,ce),C[ce]||(C[ce]={seiNals:[],logs:[]}),C[ce].seiNals=C[ce].seiNals.concat(vt.seiNals),C[ce].logs=C[ce].logs.concat(vt.logs))}),C},nf=function(b,E,C){var A;if(E===null)return null;A=Ta(b,E);var R=A[E]||{};return{seiNals:R.seiNals,logs:R.logs,timescale:C}},gu=function(){var b=!1,E,C,A,R,P,J;this.isInitialized=function(){return b},this.init=function(se){E=new jn,b=!0,J=se?se.isPartial:!1,E.on("data",function(ae){ae.startTime=ae.startPts/R,ae.endTime=ae.endPts/R,P.captions.push(ae),P.captionStreams[ae.stream]=!0}),E.on("log",function(ae){P.logs.push(ae)})},this.isNewInit=function(se,ae){return se&&se.length===0||ae&&typeof ae=="object"&&Object.keys(ae).length===0?!1:A!==se[0]||R!==ae[A]},this.parse=function(se,ae,ce){var ge;if(this.isInitialized()){if(!ae||!ce)return null;if(this.isNewInit(ae,ce))A=ae[0],R=ce[A];else if(A===null||!R)return C.push(se),null}else return null;for(;C.length>0;){var Pe=C.shift();this.parse(Pe,ae,ce)}return ge=nf(se,A,R),ge&&ge.logs&&(P.logs=P.logs.concat(ge.logs)),ge===null||!ge.seiNals?P.logs.length?{logs:P.logs,captions:[],captionStreams:[]}:null:(this.pushNals(ge.seiNals),this.flushStream(),P)},this.pushNals=function(se){if(!this.isInitialized()||!se||se.length===0)return null;se.forEach(function(ae){E.push(ae)})},this.flushStream=function(){if(!this.isInitialized())return null;J?E.partialFlush():E.flush()},this.clearParsedCaptions=function(){P.captions=[],P.captionStreams={},P.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;E.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){C=[],A=null,R=null,P?this.clearParsedCaptions():P={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},lo=gu;const{parseTfdt:k0}=Vc,ps=du,{getTimescaleFromMediaHeader:ed}=ro,{parseSamples:br,getMdatTrafPairs:rf}=Xc;var Pr=function(){let b=9e4;this.init=function(E){const C=ps(E,["moov","trak","mdia","mdhd"])[0];C&&(b=ed(C))},this.parseSegment=function(E){const C=[],A=rf(E);let R=0;return A.forEach(function(P){const J=P.mdat,se=P.traf,ae=ps(se,["tfdt"])[0],ce=ps(se,["tfhd"])[0],ge=ps(se,["trun"]);if(ae&&(R=k0(ae).baseMediaDecodeTime),ge.length&&ce){const Pe=br(ge,R,ce);let ut=0;Pe.forEach(function(je){const vt="utf-8",qt=new TextDecoder(vt),bs=J.slice(ut,ut+je.size);if(ps(bs,["vtte"])[0]){ut+=je.size;return}ps(bs,["vttc"]).forEach(function(yl){const Qi=ps(yl,["payl"])[0],_a=ps(yl,["sttg"])[0],Tr=je.pts/b,Hr=(je.pts+je.duration)/b;let Ri,nr;if(Qi)try{Ri=qt.decode(Qi)}catch(Fs){console.error(Fs)}if(_a)try{nr=qt.decode(_a)}catch(Fs){console.error(Fs)}je.duration&&Ri&&C.push({cueText:Ri,start:Tr,end:Hr,settings:nr})}),ut+=je.size})}}),C}},ml=ve,id=function(b){var E=b[1]&31;return E<<=8,E|=b[2],E},uo=function(b){return!!(b[1]&64)},pl=function(b){var E=0;return(b[3]&48)>>>4>1&&(E+=b[4]+1),E},bn=function(b,E){var C=id(b);return C===0?"pat":C===E?"pmt":E?"pes":null},co=function(b){var E=uo(b),C=4+pl(b);return E&&(C+=b[C]+1),(b[C+10]&31)<<8|b[C+11]},ho=function(b){var E={},C=uo(b),A=4+pl(b);if(C&&(A+=b[A]+1),!!(b[A+5]&1)){var R,P,J;R=(b[A+1]&15)<<8|b[A+2],P=3+R-4,J=(b[A+10]&15)<<8|b[A+11];for(var se=12+J;se=b.byteLength)return null;var A=null,R;return R=b[C+7],R&192&&(A={},A.pts=(b[C+9]&14)<<27|(b[C+10]&255)<<20|(b[C+11]&254)<<12|(b[C+12]&255)<<5|(b[C+13]&254)>>>3,A.pts*=4,A.pts+=(b[C+13]&6)>>>1,A.dts=A.pts,R&64&&(A.dts=(b[C+14]&14)<<27|(b[C+15]&255)<<20|(b[C+16]&254)<<12|(b[C+17]&255)<<5|(b[C+18]&254)>>>3,A.dts*=4,A.dts+=(b[C+18]&6)>>>1)),A},sn=function(b){switch(b){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},Tn=function(b){for(var E=4+pl(b),C=b.subarray(E),A=0,R=0,P=!1,J;R3&&(J=sn(C[R+3]&31),J==="slice_layer_without_partitioning_rbsp_idr"&&(P=!0)),P},Br={parseType:bn,parsePat:co,parsePmt:ho,parsePayloadUnitStartIndicator:uo,parsePesType:yu,parsePesTime:gl,videoPacketContainsKeyFrame:Tn},$n=ve,Gs=Ye.handleRollover,li={};li.ts=Br,li.aac=Pc;var Fr=Xe.ONE_SECOND_IN_TS,Is=188,_n=71,af=function(b,E){for(var C=0,A=Is,R,P;A=0;){if(b[A]===_n&&(b[R]===_n||R===b.byteLength)){if(P=b.subarray(A,R),J=li.ts.parseType(P,E.pid),J==="pes"&&(se=li.ts.parsePesType(P,E.table),ae=li.ts.parsePayloadUnitStartIndicator(P),se==="audio"&&ae&&(ce=li.ts.parsePesTime(P),ce&&(ce.type="audio",C.audio.push(ce),ge=!0))),ge)break;A-=Is,R-=Is;continue}A--,R--}},Gi=function(b,E,C){for(var A=0,R=Is,P,J,se,ae,ce,ge,Pe,ut,je=!1,vt={data:[],size:0};R=0;){if(b[A]===_n&&b[R]===_n){if(P=b.subarray(A,R),J=li.ts.parseType(P,E.pid),J==="pes"&&(se=li.ts.parsePesType(P,E.table),ae=li.ts.parsePayloadUnitStartIndicator(P),se==="video"&&ae&&(ce=li.ts.parsePesTime(P),ce&&(ce.type="video",C.video.push(ce),je=!0))),je)break;A-=Is,R-=Is;continue}A--,R--}},mi=function(b,E){if(b.audio&&b.audio.length){var C=E;(typeof C>"u"||isNaN(C))&&(C=b.audio[0].dts),b.audio.forEach(function(P){P.dts=Gs(P.dts,C),P.pts=Gs(P.pts,C),P.dtsTime=P.dts/Fr,P.ptsTime=P.pts/Fr})}if(b.video&&b.video.length){var A=E;if((typeof A>"u"||isNaN(A))&&(A=b.video[0].dts),b.video.forEach(function(P){P.dts=Gs(P.dts,A),P.pts=Gs(P.pts,A),P.dtsTime=P.dts/Fr,P.ptsTime=P.pts/Fr}),b.firstKeyFrame){var R=b.firstKeyFrame;R.dts=Gs(R.dts,A),R.pts=Gs(R.pts,A),R.dtsTime=R.dts/Fr,R.ptsTime=R.pts/Fr}}},Ur=function(b){for(var E=!1,C=0,A=null,R=null,P=0,J=0,se;b.length-J>=3;){var ae=li.aac.parseType(b,J);switch(ae){case"timed-metadata":if(b.length-J<10){E=!0;break}if(P=li.aac.parseId3TagSize(b,J),P>b.length){E=!0;break}R===null&&(se=b.subarray(J,J+P),R=li.aac.parseAacTimestamp(se)),J+=P;break;case"audio":if(b.length-J<7){E=!0;break}if(P=li.aac.parseAdtsSize(b,J),P>b.length){E=!0;break}A===null&&(se=b.subarray(J,J+P),A=li.aac.parseSampleRate(se)),C++,J+=P;break;default:J++;break}if(E)return null}if(A===null||R===null)return null;var ce=Fr/A,ge={audio:[{type:"audio",dts:R,pts:R},{type:"audio",dts:R+C*1024*ce,pts:R+C*1024*ce}]};return ge},Sn=function(b){var E={pid:null,table:null},C={};af(b,E);for(var A in E.table)if(E.table.hasOwnProperty(A)){var R=E.table[A];switch(R){case $n.H264_STREAM_TYPE:C.video=[],Gi(b,E,C),C.video.length===0&&delete C.video;break;case $n.ADTS_STREAM_TYPE:C.audio=[],ws(b,E,C),C.audio.length===0&&delete C.audio;break}}return C},sd=function(b,E){var C=li.aac.isLikelyAacData(b),A;return C?A=Ur(b):A=Sn(b),!A||!A.audio&&!A.video?null:(mi(A,E),A)},jr={inspect:sd,parseAudioPes_:ws};const of=function(b,E){E.on("data",function(C){const A=C.initSegment;C.initSegment={data:A.buffer,byteOffset:A.byteOffset,byteLength:A.byteLength};const R=C.data;C.data=R.buffer,b.postMessage({action:"data",segment:C,byteOffset:R.byteOffset,byteLength:R.byteLength},[C.data])}),E.on("done",function(C){b.postMessage({action:"done"})}),E.on("gopInfo",function(C){b.postMessage({action:"gopInfo",gopInfo:C})}),E.on("videoSegmentTimingInfo",function(C){const A={start:{decode:Xe.videoTsToSeconds(C.start.dts),presentation:Xe.videoTsToSeconds(C.start.pts)},end:{decode:Xe.videoTsToSeconds(C.end.dts),presentation:Xe.videoTsToSeconds(C.end.pts)},baseMediaDecodeTime:Xe.videoTsToSeconds(C.baseMediaDecodeTime)};C.prependedContentDuration&&(A.prependedContentDuration=Xe.videoTsToSeconds(C.prependedContentDuration)),b.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:A})}),E.on("audioSegmentTimingInfo",function(C){const A={start:{decode:Xe.videoTsToSeconds(C.start.dts),presentation:Xe.videoTsToSeconds(C.start.pts)},end:{decode:Xe.videoTsToSeconds(C.end.dts),presentation:Xe.videoTsToSeconds(C.end.pts)},baseMediaDecodeTime:Xe.videoTsToSeconds(C.baseMediaDecodeTime)};C.prependedContentDuration&&(A.prependedContentDuration=Xe.videoTsToSeconds(C.prependedContentDuration)),b.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:A})}),E.on("id3Frame",function(C){b.postMessage({action:"id3Frame",id3Frame:C})}),E.on("caption",function(C){b.postMessage({action:"caption",caption:C})}),E.on("trackinfo",function(C){b.postMessage({action:"trackinfo",trackInfo:C})}),E.on("audioTimingInfo",function(C){b.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:Xe.videoTsToSeconds(C.start),end:Xe.videoTsToSeconds(C.end)}})}),E.on("videoTimingInfo",function(C){b.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:Xe.videoTsToSeconds(C.start),end:Xe.videoTsToSeconds(C.end)}})}),E.on("log",function(C){b.postMessage({action:"log",log:C})})};class nd{constructor(E,C){this.options=C||{},this.self=E,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new y0.Transmuxer(this.options),of(this.self,this.transmuxer)}pushMp4Captions(E){this.captionParser||(this.captionParser=new lo,this.captionParser.init());const C=new Uint8Array(E.data,E.byteOffset,E.byteLength),A=this.captionParser.parse(C,E.trackIds,E.timescales);this.self.postMessage({action:"mp4Captions",captions:A&&A.captions||[],logs:A&&A.logs||[],data:C.buffer},[C.buffer])}initMp4WebVttParser(E){this.webVttParser||(this.webVttParser=new Pr);const C=new Uint8Array(E.data,E.byteOffset,E.byteLength);this.webVttParser.init(C)}getMp4WebVttText(E){this.webVttParser||(this.webVttParser=new Pr);const C=new Uint8Array(E.data,E.byteOffset,E.byteLength),A=this.webVttParser.parseSegment(C);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:A||[],data:C.buffer},[C.buffer])}probeMp4StartTime({timescales:E,data:C}){const A=ro.startTime(E,C);this.self.postMessage({action:"probeMp4StartTime",startTime:A,data:C},[C.buffer])}probeMp4Tracks({data:E}){const C=ro.tracks(E);this.self.postMessage({action:"probeMp4Tracks",tracks:C,data:E},[E.buffer])}probeEmsgID3({data:E,offset:C}){const A=ro.getEmsgID3(E,C);this.self.postMessage({action:"probeEmsgID3",id3Frames:A,emsgData:E},[E.buffer])}probeTs({data:E,baseStartTime:C}){const A=typeof C=="number"&&!isNaN(C)?C*Xe.ONE_SECOND_IN_TS:void 0,R=jr.inspect(E,A);let P=null;R&&(P={hasVideo:R.video&&R.video.length===2||!1,hasAudio:R.audio&&R.audio.length===2||!1},P.hasVideo&&(P.videoStart=R.video[0].ptsTime),P.hasAudio&&(P.audioStart=R.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:P,data:E},[E.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(E){const C=new Uint8Array(E.data,E.byteOffset,E.byteLength);this.transmuxer.push(C)}reset(){this.transmuxer.reset()}setTimestampOffset(E){const C=E.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(Xe.secondsToVideoTs(C)))}setAudioAppendStart(E){this.transmuxer.setAudioAppendStart(Math.ceil(Xe.secondsToVideoTs(E.appendStart)))}setRemux(E){this.transmuxer.setRemux(E.remux)}flush(E){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(E){this.transmuxer.alignGopsWith(E.gopsToAlignWith.slice())}}self.onmessage=function(b){if(b.data.action==="init"&&b.data.options){this.messageHandlers=new nd(self,b.data.options);return}this.messageHandlers||(this.messageHandlers=new nd(self)),b.data&&b.data.action&&b.data.action!=="init"&&this.messageHandlers[b.data.action]&&this.messageHandlers[b.data.action](b.data)}}));var IB=Rk(RB);const NB=(s,e,t)=>{const{type:i,initSegment:n,captions:r,captionStreams:o,metadata:u,videoFrameDtsTime:c,videoFramePtsTime:d}=s.data.segment;e.buffer.push({captions:r,captionStreams:o,metadata:u});const f=s.data.segment.boxes||{data:s.data.segment.data},p={type:i,data:new Uint8Array(f.data,f.data.byteOffset,f.data.byteLength),initSegment:new Uint8Array(n.data,n.byteOffset,n.byteLength)};typeof c<"u"&&(p.videoFrameDtsTime=c),typeof d<"u"&&(p.videoFramePtsTime=d),t(p)},OB=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},MB=(s,e)=>{e.gopInfo=s.data.gopInfo},Ok=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:n,remux:r,onData:o,onTrackInfo:u,onAudioTimingInfo:c,onVideoTimingInfo:d,onVideoSegmentTimingInfo:f,onAudioSegmentTimingInfo:p,onId3:g,onCaptions:y,onDone:x,onEndedTimeline:_,onTransmuxerLog:w,isEndOfTimeline:D,segment:I,triggerSegmentEventFn:L}=s,B={buffer:[]};let j=D;const V=z=>{e.currentTransmux===s&&(z.data.action==="data"&&NB(z,B,o),z.data.action==="trackinfo"&&u(z.data.trackInfo),z.data.action==="gopInfo"&&MB(z,B),z.data.action==="audioTimingInfo"&&c(z.data.audioTimingInfo),z.data.action==="videoTimingInfo"&&d(z.data.videoTimingInfo),z.data.action==="videoSegmentTimingInfo"&&f(z.data.videoSegmentTimingInfo),z.data.action==="audioSegmentTimingInfo"&&p(z.data.audioSegmentTimingInfo),z.data.action==="id3Frame"&&g([z.data.id3Frame],z.data.id3Frame.dispatchType),z.data.action==="caption"&&y(z.data.caption),z.data.action==="endedtimeline"&&(j=!1,_()),z.data.action==="log"&&w(z.data.log),z.data.type==="transmuxed"&&(j||(e.onmessage=null,OB({transmuxedData:B,callback:x}),Mk(e))))},M=()=>{const z={message:"Received an error message from the transmuxer worker",metadata:{errorType:Ae.Error.StreamingFailedToTransmuxSegment,segmentInfo:Ml({segment:I})}};x(null,z)};if(e.onmessage=V,e.onerror=M,i&&e.postMessage({action:"setAudioAppendStart",appendStart:i}),Array.isArray(n)&&e.postMessage({action:"alignGopsWith",gopsToAlignWith:n}),typeof r<"u"&&e.postMessage({action:"setRemux",remux:r}),t.byteLength){const z=t instanceof ArrayBuffer?t:t.buffer,O=t instanceof ArrayBuffer?0:t.byteOffset;L({type:"segmenttransmuxingstart",segment:I}),e.postMessage({action:"push",data:z,byteOffset:O,byteLength:t.byteLength},[z])}D&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},Mk=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():Ok(s.currentTransmux))},GE=(s,e)=>{s.postMessage({action:e}),Mk(s)},Pk=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,GE(e,s);return}e.transmuxQueue.push(GE.bind(null,e,s))},PB=s=>{Pk("reset",s)},BB=s=>{Pk("endTimeline",s)},Bk=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,Ok(s);return}s.transmuxer.transmuxQueue.push(s)},FB=s=>{const e=new IB;e.currentTransmux=null,e.transmuxQueue=[];const t=e.terminate;return e.terminate=()=>(e.currentTransmux=null,e.transmuxQueue.length=0,t.call(e)),e.postMessage({action:"init",options:s}),e};var Wy={reset:PB,endTimeline:BB,transmux:Bk,createTransmuxer:FB};const rc=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,n=Es({},s,{endAction:null,transmuxer:null,callback:null}),r=o=>{o.data.action===t&&(e.removeEventListener("message",r),o.data.data&&(o.data.data=new Uint8Array(o.data.data,s.byteOffset||0,s.byteLength||o.data.data.byteLength),s.data&&(s.data=o.data.data)),i(o.data))};if(e.addEventListener("message",r),s.data){const o=s.data instanceof ArrayBuffer;n.byteOffset=o?0:s.data.byteOffset,n.byteLength=s.data.byteLength;const u=[o?s.data:s.data.buffer];e.postMessage(n,u)}else e.postMessage(n)},na={FAILURE:2,TIMEOUT:-101,ABORTED:-102},Fk="wvtt",ox=s=>{s.forEach(e=>{e.abort()})},UB=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),jB=s=>{const e=s.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-e.requestTime||0};return i.bytesReceived=s.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8*1e3),i},wb=(s,e)=>{const{requestType:t}=e,i=Vl({requestType:t,request:e,error:s});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:na.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:na.ABORTED,xhr:e,metadata:i}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:na.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:na.FAILURE,xhr:e,metadata:i}:null},zE=(s,e,t,i)=>(n,r)=>{const o=r.response,u=wb(n,r);if(u)return t(u,s);if(o.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:na.FAILURE,xhr:r},s);const c=new DataView(o),d=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let p=0;p{e===Fk&&s.transmuxer.postMessage({action:"initMp4WebVttParser",data:s.map.bytes})},HB=(s,e,t)=>{e===Fk&&rc({action:"getMp4WebVttText",data:s.bytes,transmuxer:s.transmuxer,callback:({data:i,mp4VttCues:n})=>{s.bytes=i,t(null,s,{mp4VttCues:n})}})},Uk=(s,e)=>{const t=Yx(s.map.bytes);if(t!=="mp4"){const i=s.map.resolvedUri||s.map.uri,n=t||"unknown";return e({internal:!0,message:`Found unsupported ${n} container for initialization segment at URL: ${i}`,code:na.FAILURE,metadata:{mediaType:n}})}rc({action:"probeMp4Tracks",data:s.map.bytes,transmuxer:s.transmuxer,callback:({tracks:i,data:n})=>(s.map.bytes=n,i.forEach(function(r){s.map.tracks=s.map.tracks||{},!s.map.tracks[r.type]&&(s.map.tracks[r.type]=r,typeof r.id=="number"&&r.timescale&&(s.map.timescales=s.map.timescales||{},s.map.timescales[r.id]=r.timescale),r.type==="text"&&$B(s,r.codec))}),e(null))})},VB=({segment:s,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,n)=>{const r=wb(i,n);if(r)return e(r,s);const o=new Uint8Array(n.response);if(t({type:"segmentloaded",segment:s}),s.map.key)return s.map.encryptedBytes=o,e(null,s);s.map.bytes=o,Uk(s,function(u){if(u)return u.xhr=n,u.status=n.status,e(u,s);e(null,s)})},GB=({segment:s,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(n,r)=>{const o=wb(n,r);if(o)return e(o,s);i({type:"segmentloaded",segment:s});const u=t==="arraybuffer"||!r.responseText?r.response:DB(r.responseText.substring(s.lastReachedChar||0));return s.stats=UB(r),s.key?s.encryptedBytes=new Uint8Array(u):s.bytes=new Uint8Array(u),e(null,s)},zB=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:y})=>{const x=s.map&&s.map.tracks||{},_=!!(x.audio&&x.video);let w=i.bind(null,s,"audio","start");const D=i.bind(null,s,"audio","end");let I=i.bind(null,s,"video","start");const L=i.bind(null,s,"video","end"),B=()=>Bk({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:_,onData:j=>{j.type=j.type==="combined"?"video":j.type,f(s,j)},onTrackInfo:j=>{t&&(_&&(j.isMuxed=!0),t(s,j))},onAudioTimingInfo:j=>{w&&typeof j.start<"u"&&(w(j.start),w=null),D&&typeof j.end<"u"&&D(j.end)},onVideoTimingInfo:j=>{I&&typeof j.start<"u"&&(I(j.start),I=null),L&&typeof j.end<"u"&&L(j.end)},onVideoSegmentTimingInfo:j=>{const V={pts:{start:j.start.presentation,end:j.end.presentation},dts:{start:j.start.decode,end:j.end.decode}};y({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:V}),n(j)},onAudioSegmentTimingInfo:j=>{const V={pts:{start:j.start.pts,end:j.end.pts},dts:{start:j.start.dts,end:j.end.dts}};y({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:V}),r(j)},onId3:(j,V)=>{o(s,j,V)},onCaptions:j=>{u(s,[j])},isEndOfTimeline:c,onEndedTimeline:()=>{d()},onTransmuxerLog:g,onDone:(j,V)=>{p&&(j.type=j.type==="combined"?"video":j.type,y({type:"segmenttransmuxingcomplete",segment:s}),p(V,s,j))},segment:s,triggerSegmentEventFn:y});rc({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:j=>{s.bytes=e=j.data;const V=j.result;V&&(t(s,{hasAudio:V.hasAudio,hasVideo:V.hasVideo,isMuxed:_}),t=null),B()}})},jk=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:y})=>{let x=new Uint8Array(e);if(h3(x)){s.isFmp4=!0;const{tracks:_}=s.map;if(_.text&&(!_.audio||!_.video)){f(s,{data:x,type:"text"}),HB(s,_.text.codec,p);return}const D={isFmp4:!0,hasVideo:!!_.video,hasAudio:!!_.audio};_.audio&&_.audio.codec&&_.audio.codec!=="enca"&&(D.audioCodec=_.audio.codec),_.video&&_.video.codec&&_.video.codec!=="encv"&&(D.videoCodec=_.video.codec),_.video&&_.audio&&(D.isMuxed=!0),t(s,D);const I=(L,B)=>{f(s,{data:x,type:D.hasAudio&&!D.isMuxed?"audio":"video"}),B&&B.length&&o(s,B),L&&L.length&&u(s,L),p(null,s,{})};rc({action:"probeMp4StartTime",timescales:s.map.timescales,data:x,transmuxer:s.transmuxer,callback:({data:L,startTime:B})=>{e=L.buffer,s.bytes=x=L,D.hasAudio&&!D.isMuxed&&i(s,"audio","start",B),D.hasVideo&&i(s,"video","start",B),rc({action:"probeEmsgID3",data:x,transmuxer:s.transmuxer,offset:B,callback:({emsgData:j,id3Frames:V})=>{if(e=j.buffer,s.bytes=x=j,!_.video||!j.byteLength||!s.transmuxer){I(void 0,V);return}rc({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:x,timescales:s.map.timescales,trackIds:[_.video.id],callback:M=>{e=M.data.buffer,s.bytes=x=M.data,M.logs.forEach(function(z){g(Di(z,{stream:"mp4CaptionParser"}))}),I(M.captions,V)}})}})}});return}if(!s.transmuxer){p(null,s,{});return}if(typeof s.container>"u"&&(s.container=Yx(x)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),p(null,s,{});return}zB({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:y})},$k=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i,segment:n,doneFn:r},o){const u=d=>{if(d.data.source===s){i.removeEventListener("message",u);const f=d.data.decrypted;o(new Uint8Array(f.bytes,f.byteOffset,f.byteLength))}};i.onerror=()=>{const d="An error occurred in the decryption worker",f=Ml({segment:n}),p={message:d,metadata:{error:new Error(d),errorType:Ae.Error.StreamingFailedToDecryptSegment,segmentInfo:f,keyInfo:{uri:n.key.resolvedUri||n.map.key.resolvedUri}}};r(p,n)},i.addEventListener("message",u);let c;e.bytes.slice?c=e.bytes.slice():c=new Uint32Array(Array.prototype.slice.call(e.bytes)),i.postMessage(wk({source:s,encrypted:t,key:c,iv:e.iv}),[t.buffer,c.buffer])},qB=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:y})=>{y({type:"segmentdecryptionstart"}),$k({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s,segment:e,doneFn:p},x=>{e.bytes=x,y({type:"segmentdecryptioncomplete",segment:e}),jk({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:y})})},KB=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:y})=>{let x=0,_=!1;return(w,D)=>{if(!_){if(w)return _=!0,ox(s),p(w,D);if(x+=1,x===s.length){const I=function(){if(D.encryptedBytes)return qB({decryptionWorker:e,segment:D,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:y});jk({segment:D,bytes:D.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:g,triggerSegmentEventFn:y})};if(D.endOfAllRequests=Date.now(),D.map&&D.map.encryptedBytes&&!D.map.bytes)return y({type:"segmentdecryptionstart",segment:D}),$k({decryptionWorker:e,id:D.requestId+"-init",encryptedBytes:D.map.encryptedBytes,key:D.map.key,segment:D,doneFn:p},L=>{D.map.bytes=L,y({type:"segmentdecryptioncomplete",segment:D}),Uk(D,B=>{if(B)return ox(s),p(B,D);I()})});I()}}}},YB=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},WB=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f})=>p=>{if(!p.target.aborted)return s.stats=Di(s.stats,jB(p)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(p,s)},XB=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:n,progressFn:r,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:g,endedTimelineFn:y,dataFn:x,doneFn:_,onTransmuxerLog:w,triggerSegmentEventFn:D})=>{const I=[],L=KB({activeXhrs:I,decryptionWorker:t,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:g,endedTimelineFn:y,dataFn:x,doneFn:_,onTransmuxerLog:w,triggerSegmentEventFn:D});if(i.key&&!i.key.bytes){const z=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&z.push(i.map.key);const O=Di(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),N=zE(i,z,L,D),q={uri:i.key.resolvedUri};D({type:"segmentkeyloadstart",segment:i,keyInfo:q});const Q=s(O,N);I.push(Q)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const Q=Di(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),Y=zE(i,[i.map.key],L,D),re={uri:i.map.key.resolvedUri};D({type:"segmentkeyloadstart",segment:i,keyInfo:re});const Z=s(Q,Y);I.push(Z)}const O=Di(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:rx(i.map),requestType:"segment-media-initialization"}),N=VB({segment:i,finishProcessingFn:L,triggerSegmentEventFn:D});D({type:"segmentloadstart",segment:i});const q=s(O,N);I.push(q)}const B=Di(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:rx(i),requestType:"segment"}),j=GB({segment:i,finishProcessingFn:L,responseType:B.responseType,triggerSegmentEventFn:D});D({type:"segmentloadstart",segment:i});const V=s(B,j);V.addEventListener("progress",WB({segment:i,progressFn:r,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:g,endedTimelineFn:y,dataFn:x})),I.push(V);const M={};return I.forEach(z=>{z.addEventListener("loadend",YB({loadendState:M,abortFn:n}))}),()=>ox(I)},dm=pr("PlaylistSelector"),qE=function(s){if(!s||!s.playlist)return;const e=s.playlist;return JSON.stringify({id:e.id,bandwidth:s.bandwidth,width:s.width,height:s.height,codecs:e.attributes&&e.attributes.CODECS||""})},ac=function(s,e){if(!s)return"";const t=ue.getComputedStyle(s);return t?t[e]:""},oc=function(s,e){const t=s.slice();s.sort(function(i,n){const r=e(i,n);return r===0?t.indexOf(i)-t.indexOf(n):r})},Ab=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||ue.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||ue.Number.MAX_VALUE,t-i},QB=function(s,e){let t,i;return s.attributes.RESOLUTION&&s.attributes.RESOLUTION.width&&(t=s.attributes.RESOLUTION.width),t=t||ue.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||ue.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let Hk=function(s){const{main:e,bandwidth:t,playerWidth:i,playerHeight:n,playerObjectFit:r,limitRenditionByPlayerDimensions:o,playlistController:u}=s;if(!e)return;const c={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:o};let d=e.playlists;On.isAudioOnly(e)&&(d=u.getAudioTrackPlaylists_(),c.audioOnly=!0);let f=d.map(M=>{let z;const O=M.attributes&&M.attributes.RESOLUTION&&M.attributes.RESOLUTION.width,N=M.attributes&&M.attributes.RESOLUTION&&M.attributes.RESOLUTION.height;return z=M.attributes&&M.attributes.BANDWIDTH,z=z||ue.Number.MAX_VALUE,{bandwidth:z,width:O,height:N,playlist:M}});oc(f,(M,z)=>M.bandwidth-z.bandwidth),f=f.filter(M=>!On.isIncompatible(M.playlist));let p=f.filter(M=>On.isEnabled(M.playlist));p.length||(p=f.filter(M=>!On.isDisabled(M.playlist)));const g=p.filter(M=>M.bandwidth*$s.BANDWIDTH_VARIANCEM.bandwidth===y.bandwidth)[0];if(o===!1){const M=x||p[0]||f[0];if(M&&M.playlist){let z="sortedPlaylistReps";return x&&(z="bandwidthBestRep"),p[0]&&(z="enabledPlaylistReps"),dm(`choosing ${qE(M)} using ${z} with options`,c),M.playlist}return dm("could not choose a playlist with options",c),null}const _=g.filter(M=>M.width&&M.height);oc(_,(M,z)=>M.width-z.width);const w=_.filter(M=>M.width===i&&M.height===n);y=w[w.length-1];const D=w.filter(M=>M.bandwidth===y.bandwidth)[0];let I,L,B;D||(I=_.filter(M=>r==="cover"?M.width>i&&M.height>n:M.width>i||M.height>n),L=I.filter(M=>M.width===I[0].width&&M.height===I[0].height),y=L[L.length-1],B=L.filter(M=>M.bandwidth===y.bandwidth)[0]);let j;if(u.leastPixelDiffSelector){const M=_.map(z=>(z.pixelDiff=Math.abs(z.width-i)+Math.abs(z.height-n),z));oc(M,(z,O)=>z.pixelDiff===O.pixelDiff?O.bandwidth-z.bandwidth:z.pixelDiff-O.pixelDiff),j=M[0]}const V=j||B||D||x||p[0]||f[0];if(V&&V.playlist){let M="sortedPlaylistReps";return j?M="leastPixelDiffRep":B?M="resolutionPlusOneRep":D?M="resolutionBestRep":x?M="bandwidthBestRep":p[0]&&(M="enabledPlaylistReps"),dm(`choosing ${qE(V)} using ${M} with options`,c),V.playlist}return dm("could not choose a playlist with options",c),null};const KE=function(){let s=this.useDevicePixelRatio&&ue.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),Hk({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(ac(this.tech_.el(),"width"),10)*s,playerHeight:parseInt(ac(this.tech_.el(),"height"),10)*s,playerObjectFit:this.usePlayerObjectFit?ac(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},ZB=function(s){let e=-1,t=-1;if(s<0||s>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){let i=this.useDevicePixelRatio&&ue.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(i=this.customPixelRatio),e<0&&(e=this.systemBandwidth,t=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==t&&(e=s*this.systemBandwidth+(1-s)*e,t=this.systemBandwidth),Hk({main:this.playlists.main,bandwidth:e,playerWidth:parseInt(ac(this.tech_.el(),"width"),10)*i,playerHeight:parseInt(ac(this.tech_.el(),"height"),10)*i,playerObjectFit:this.usePlayerObjectFit?ac(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},JB=function(s){const{main:e,currentTime:t,bandwidth:i,duration:n,segmentDuration:r,timeUntilRebuffer:o,currentTimeline:u,syncController:c}=s,d=e.playlists.filter(x=>!On.isIncompatible(x));let f=d.filter(On.isEnabled);f.length||(f=d.filter(x=>!On.isDisabled(x)));const g=f.filter(On.hasAttribute.bind(null,"BANDWIDTH")).map(x=>{const w=c.getSyncPoint(x,n,u,t)?1:2,I=On.estimateSegmentRequestTime(r,i,x)*w-o;return{playlist:x,rebufferingImpact:I}}),y=g.filter(x=>x.rebufferingImpact<=0);return oc(y,(x,_)=>Ab(_.playlist,x.playlist)),y.length?y[0]:(oc(g,(x,_)=>x.rebufferingImpact-_.rebufferingImpact),g[0]||null)},eF=function(){const s=this.playlists.main.playlists.filter(On.isEnabled);return oc(s,(t,i)=>Ab(t,i)),s.filter(t=>!!rh(this.playlists.main,t).video)[0]||null},tF=s=>{let e=0,t;return s.bytes&&(t=new Uint8Array(s.bytes),s.segments.forEach(i=>{t.set(i,e),e+=i.byteLength})),t};function Vk(s){try{return new URL(s).pathname.split("/").slice(-2).join("/")}catch{return""}}const iF=function(s,e,t){if(!s[t]){e.trigger({type:"usage",name:"vhs-608"});let i=t;/^cc708_/.test(t)&&(i="SERVICE"+t.split("_")[1]);const n=e.textTracks().getTrackById(i);if(n)s[t]=n;else{const r=e.options_.vhs&&e.options_.vhs.captionServices||{};let o=t,u=t,c=!1;const d=r[i];d&&(o=d.label,u=d.language,c=d.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:c,label:o,language:u},!1).track}}},sF=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=ue.WebKitDataCue||ue.VTTCue;e.forEach(n=>{const r=n.stream;n.content?n.content.forEach(o=>{const u=new i(n.startTime+t,n.endTime+t,o.text);u.line=o.line,u.align="left",u.position=o.position,u.positionAlign="line-left",s[r].addCue(u)}):s[r].addCue(new i(n.startTime+t,n.endTime+t,n.text))})},nF=function(s){Object.defineProperties(s.frame,{id:{get(){return Ae.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),s.value.key}},value:{get(){return Ae.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),s.value.data}},privateData:{get(){return Ae.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),s.value.data}}})},rF=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const n=ue.WebKitDataCue||ue.VTTCue,r=s.metadataTrack_;if(!r||(e.forEach(f=>{const p=f.cueTime+t;typeof p!="number"||ue.isNaN(p)||p<0||!(p<1/0)||!f.frames||!f.frames.length||f.frames.forEach(g=>{const y=new n(p,p,g.value||g.url||g.data||"");y.frame=g,y.value=g,nF(y),r.addCue(y)})}),!r.cues||!r.cues.length))return;const o=r.cues,u=[];for(let f=0;f{const g=f[p.startTime]||[];return g.push(p),f[p.startTime]=g,f},{}),d=Object.keys(c).sort((f,p)=>Number(f)-Number(p));d.forEach((f,p)=>{const g=c[f],y=isFinite(i)?i:f,x=Number(d[p+1])||y;g.forEach(_=>{_.endTime=x})})},aF={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},oF=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),lF=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=ue.WebKitDataCue||ue.VTTCue;e.forEach(n=>{for(const r of Object.keys(n)){if(oF.has(r))continue;const o=new i(n.startTime,n.endTime,"");o.id=n.id,o.type="com.apple.quicktime.HLS",o.value={key:aF[r],data:n[r]},(r==="scte35Out"||r==="scte35In")&&(o.value.data=new Uint8Array(o.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(o)}n.processDateRange()})},YE=(s,e,t)=>{s.metadataTrack_||(s.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,Ae.browser.IS_ANY_SAFARI||(s.metadataTrack_.inBandMetadataTrackDispatchType=e))},Yd=function(s,e,t){let i,n;if(t&&t.cues)for(i=t.cues.length;i--;)n=t.cues[i],n.startTime>=s&&n.endTime<=e&&t.removeCue(n)},uF=function(s){const e=s.cues;if(!e)return;const t={};for(let i=e.length-1;i>=0;i--){const n=e[i],r=`${n.startTime}-${n.endTime}-${n.text}`;t[r]?s.removeCue(n):t[r]=n}},cF=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*Bl.ONE_SECOND_IN_TS);let n;for(n=0;ni);n++);return s.slice(n)},dF=(s,e,t)=>{if(!e.length)return s;if(t)return e.slice();const i=e[0].pts;let n=0;for(n;n=i);n++);return s.slice(0,n).concat(e)},hF=(s,e,t,i)=>{const n=Math.ceil((e-i)*Bl.ONE_SECOND_IN_TS),r=Math.ceil((t-i)*Bl.ONE_SECOND_IN_TS),o=s.slice();let u=s.length;for(;u--&&!(s[u].pts<=r););if(u===-1)return o;let c=u+1;for(;c--&&!(s[c].pts<=n););return c=Math.max(c,0),o.splice(c,u-c+1),o},fF=function(s,e){if(!s&&!e||!s&&e||s&&!e)return!1;if(s===e)return!0;const t=Object.keys(s).sort(),i=Object.keys(e).sort();if(t.length!==i.length)return!1;for(let n=0;nt))return r}return i.length===0?0:i[i.length-1]},Ud=1,pF=500,WE=s=>typeof s=="number"&&isFinite(s),hm=1/60,gF=(s,e,t)=>s!=="main"||!e||!t?null:!t.hasAudio&&!t.hasVideo?"Neither audio nor video found in segment.":e.hasVideo&&!t.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!e.hasVideo&&t.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null,yF=(s,e,t)=>{let i=e-$s.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const n=e-t;return Math.min(n,i)},Fu=s=>{const{startOfSegment:e,duration:t,segment:i,part:n,playlist:{mediaSequence:r,id:o,segments:u=[]},mediaIndex:c,partIndex:d,timeline:f}=s,p=u.length-1;let g="mediaIndex/partIndex increment";s.getMediaInfoForTime?g=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(g="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(g+=` with independent ${s.independent}`);const y=typeof d=="number",x=s.segment.uri?"segment":"pre-segment",_=y?ok({preloadSegment:i})-1:0;return`${x} [${r+c}/${r+p}]`+(y?` part [${d}/${_}]`:"")+` segment start/end [${i.start} => ${i.end}]`+(y?` part start/end [${n.start} => ${n.end}]`:"")+` startOfSegment [${e}] duration [${t}] timeline [${f}] selected by [${g}] playlist [${o}]`},XE=s=>`${s}TimingInfo`,vF=({segmentTimeline:s,currentTimeline:e,startOfSegment:t,buffered:i,overrideCheck:n})=>!n&&s===e?null:s{if(e===t)return!1;if(i==="audio"){const r=s.lastTimelineChange({type:"main"});return!r||r.to!==t}if(i==="main"&&n){const r=s.pendingTimelineChange({type:"audio"});return!(r&&r.to===t)}return!1},xF=s=>{if(!s)return!1;const e=s.pendingTimelineChange({type:"audio"}),t=s.pendingTimelineChange({type:"main"}),i=e&&t,n=i&&e.to!==t.to;return!!(i&&e.from!==-1&&t.from!==-1&&n)},bF=s=>{const e=s.timelineChangeController_.pendingTimelineChange({type:"audio"}),t=s.timelineChangeController_.pendingTimelineChange({type:"main"});return e&&t&&e.to{const e=s.pendingSegment_;if(!e)return;if(lx({timelineChangeController:s.timelineChangeController_,currentTimeline:s.currentTimeline_,segmentTimeline:e.timeline,loaderType:s.loaderType_,audioDisabled:s.audioDisabled_})&&xF(s.timelineChangeController_)){if(bF(s)){s.timelineChangeController_.trigger("audioTimelineBehind");return}s.timelineChangeController_.trigger("fixBadTimelineChange")}},TF=s=>{let e=0;return["video","audio"].forEach(function(t){const i=s[`${t}TimingInfo`];if(!i)return;const{start:n,end:r}=i;let o;typeof n=="bigint"||typeof r=="bigint"?o=ue.BigInt(r)-ue.BigInt(n):typeof n=="number"&&typeof r=="number"&&(o=r-n),typeof o<"u"&&o>e&&(e=o)}),typeof e=="bigint"&&es?Math.round(s)>e+ia:!1,_F=(s,e)=>{if(e!=="hls")return null;const t=TF({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,n=QE({segmentDuration:t,maxDuration:i*2}),r=QE({segmentDuration:t,maxDuration:i}),o=`Segment with index ${s.mediaIndex} from playlist ${s.playlist.id} has a duration of ${t} when the reported duration is ${s.duration} and the target duration is ${i}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return n||r?{severity:n?"warn":"info",message:o}:null},Ml=({type:s,segment:e})=>{if(!e)return;const t=!!(e.key||e.map&&e.map.ke),i=!!(e.map&&!e.map.bytes),n=e.startOfSegment===void 0?e.start:e.startOfSegment;return{type:s||e.type,uri:e.resolvedUri||e.uri,start:n,duration:e.duration,isEncrypted:t,isMediaInitialization:i}};class ux extends Ae.EventTarget{constructor(e,t={}){if(super(),!e)throw new TypeError("Initialization settings are required");if(typeof e.currentTime!="function")throw new TypeError("No currentTime getter specified");if(!e.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",()=>{this.isEndOfStream_()||(this.ended_=!1)}),this.fetchAtBuffer_=!1,this.logger_=pr(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(i){i!==this.state_&&(this.logger_(`${this.state_} -> ${i}`),this.state_=i,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():Oo(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger(Es({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():Oo(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger(Es({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():Oo(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():Oo(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return Wy.createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&ue.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){if(this.state!=="WAITING"){this.pendingSegment_&&(this.pendingSegment_=null),this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);return}this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,ue.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return this.state==="APPENDING"&&!this.pendingSegment_?(this.state="READY",!0):!this.pendingSegment_||this.pendingSegment_.requestId!==e}error(e){return typeof e<"u"&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&Wy.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return Vs();if(this.loaderType_==="main"){const{hasAudio:t,hasVideo:i,isMuxed:n}=e;if(i&&t&&!this.audioDisabled_&&!n)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;const i=fp(e);let n=this.initSegments_[i];return t&&!n&&e.bytes&&(this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),n||e}segmentKey(e,t=!1){if(!e)return null;const i=Ak(e);let n=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!n&&e.bytes&&(this.keyCache_[i]=n={resolvedUri:e.resolvedUri,bytes:e.bytes});const r={resolvedUri:(n||e).resolvedUri};return n&&(r.bytes=n.bytes),r}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),!!this.playlist_){if(this.state==="INIT"&&this.couldBeginLoading_())return this.init_();!this.couldBeginLoading_()||this.state!=="READY"&&this.state!=="INIT"||(this.state="READY")}}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e||this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)return;const i=this.playlist_,n=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,this.state==="INIT"&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},this.loaderType_==="main"&&this.syncController_.setDateTimeMappingForStart(e));let r=null;if(i&&(i.id?r=i.id:i.uri&&(r=i.uri)),this.logger_(`playlist update [${r} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update: +currentTime: ${this.currentTime_()} +bufferedEnd: ${Ky(this.buffered_())} +`,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),this.state==="INIT"&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri){this.mediaIndex!==null&&(!e.endList&&typeof e.partTargetDuration=="number"?this.resetLoader():this.resyncLoader()),this.currentMediaInfo_=void 0,this.trigger("playlistupdate");return}const o=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${o}]`),this.mediaIndex!==null)if(this.mediaIndex-=o,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const u=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!u.parts||!u.parts.length||!u.parts[this.partIndex])){const c=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=c}}n&&(n.mediaIndex-=o,n.mediaIndex<0?(n.mediaIndex=null,n.partIndex=null):(n.mediaIndex>=0&&(n.segment=e.segments[n.mediaIndex]),n.partIndex>=0&&n.segment.parts&&(n.part=n.segment.parts[n.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(ue.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return this.checkBufferTimeout_===null}resetEverything(e){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&Wy.reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;const e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;this.sourceType_==="hls"&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=()=>{},n=!1){if(t===1/0&&(t=this.duration_()),t<=e){this.logger_("skipping remove because end ${end} is <= start ${start}");return}if(!this.sourceUpdater_||!this.getMediaInfo_()){this.logger_("skipping remove because no source updater or starting media info");return}let r=1;const o=()=>{r--,r===0&&i()};(n||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,o)),(n||this.loaderType_==="main")&&(this.gopBuffer_=hF(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,o));for(const u in this.inbandTextTracks_)Yd(e,t,this.inbandTextTracks_[u]);Yd(e,t,this.segmentMetadataTrack_),o()}monitorBuffer_(){this.checkBufferTimeout_&&ue.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=ue.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&ue.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=ue.setTimeout(this.monitorBufferTick_.bind(this),pF)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:Ml({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const n=typeof e=="number"&&t.segments[e],r=e+1===t.segments.length,o=!n||!n.parts||i+1===n.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&r&&o}chooseNextRequest_(){const e=this.buffered_(),t=Ky(e)||0,i=Tb(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),o=this.playlist_.segments;if(!o.length||n||r)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const u={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(u.isSyncRequest)u.mediaIndex=mF(this.currentTimeline_,o,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${u.mediaIndex}`);else if(this.mediaIndex!==null){const g=o[this.mediaIndex],y=typeof this.partIndex=="number"?this.partIndex:-1;u.startOfSegment=g.end?g.end:t,g.parts&&g.parts[y+1]?(u.mediaIndex=this.mediaIndex,u.partIndex=y+1):u.mediaIndex=this.mediaIndex+1}else{let g,y,x;const _=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch: +For TargetTime: ${_}. +CurrentTime: ${this.currentTime_()} +BufferedEnd: ${t} +Fetch At Buffer: ${this.fetchAtBuffer_} +`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const w=this.getSyncInfoFromMediaSequenceSync_(_);if(!w){const D="No sync info found while using media sequence sync";return this.error({message:D,metadata:{errorType:Ae.Error.StreamingFailedToSelectNextSegment,error:new Error(D)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${w.start} --> ${w.end})`),g=w.segmentIndex,y=w.partIndex,x=w.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const w=On.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:_,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});g=w.segmentIndex,y=w.partIndex,x=w.startTime}u.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${_}`:`currentTime ${_}`,u.mediaIndex=g,u.startOfSegment=x,u.partIndex=y,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${u.mediaIndex} `)}const c=o[u.mediaIndex];let d=c&&typeof u.partIndex=="number"&&c.parts&&c.parts[u.partIndex];if(!c||typeof u.partIndex=="number"&&!d)return null;typeof u.partIndex!="number"&&c.parts&&(u.partIndex=0,d=c.parts[0]);const f=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&d&&!f&&!d.independent)if(u.partIndex===0){const g=o[u.mediaIndex-1],y=g.parts&&g.parts.length&&g.parts[g.parts.length-1];y&&y.independent&&(u.mediaIndex-=1,u.partIndex=g.parts.length-1,u.independent="previous segment")}else c.parts[u.partIndex-1].independent&&(u.partIndex-=1,u.independent="previous part");const p=this.mediaSource_&&this.mediaSource_.readyState==="ended";return u.mediaIndex>=o.length-1&&p&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,u.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(u))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;const t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);const i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;const n=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return n?(n.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),n):null}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:n,startOfSegment:r,isSyncRequest:o,partIndex:u,forceTimestampOffset:c,getMediaInfoForTime:d}=e,f=i.segments[n],p=typeof u=="number"&&f.parts[u],g={requestId:"segment-loader-"+Math.random(),uri:p&&p.resolvedUri||f.resolvedUri,mediaIndex:n,partIndex:p?u:null,isSyncRequest:o,startOfSegment:r,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:f.timeline,duration:p&&p.duration||f.duration,segment:f,part:p,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:d,independent:t},y=typeof c<"u"?c:this.isPendingTimestampOffset_;g.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:f.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:y});const x=Ky(this.sourceUpdater_.audioBuffered());return typeof x=="number"&&(g.audioAppendStart=x-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(g.gopsToAlignWith=cF(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),g}timestampOffsetForSegment_(e){return vF(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH||Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;const t=this.currentTime_(),i=e.bandwidth,n=this.pendingSegment_.duration,r=On.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),o=j4(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=o)return;const u=JB({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:n,timeUntilRebuffer:o,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!u)return;const d=r-o-u.rebufferingImpact;let f=.5;o<=ia&&(f=1),!(!u.playlist||u.playlist.uri===this.playlist_.uri||d{r[o.stream]=r[o.stream]||{startTime:1/0,captions:[],endTime:0};const u=r[o.stream];u.startTime=Math.min(u.startTime,o.startTime+n),u.endTime=Math.max(u.endTime,o.endTime+n),u.captions.push(o)}),Object.keys(r).forEach(o=>{const{startTime:u,endTime:c,captions:d}=r[o],f=this.inbandTextTracks_;this.logger_(`adding cues from ${u} -> ${c} for ${o}`),iF(f,this.vhs_.tech_,o),Yd(u,c,f[o]),sF({captionArray:d,inbandTextTracks:f,timestampOffset:n})}),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(!this.pendingSegment_.hasAppendedData_){this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i));return}this.addMetadataToTextTrack(i,t,this.duration_())}processMetadataQueue_(){this.metadataQueue_.id3.forEach(e=>e()),this.metadataQueue_.caption.forEach(e=>e()),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){const e=this.callQueue_;this.callQueue_=[],e.forEach(t=>t())}processLoadQueue_(){const e=this.loadQueue_;this.loadQueue_=[],e.forEach(t=>t())}hasEnoughInfoToLoad_(){if(this.loaderType_!=="audio")return!0;const e=this.pendingSegment_;return e?this.getCurrentMediaInfo_()?!lx({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}):!0:!1}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()||this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;const{hasAudio:i,hasVideo:n,isMuxed:r}=t;return!(n&&!e.videoTimingInfo||i&&!this.audioDisabled_&&!r&&!e.audioTimingInfo||lx({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_()){Oo(this),this.callQueue_.push(this.handleData_.bind(this,e,t));return}const i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),this.mediaSource_.readyState!=="closed"){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[XE(t.type)].start;else{const n=this.getCurrentMediaInfo_(),r=this.loaderType_==="main"&&n&&n.hasVideo;let o;r&&(o=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:r,firstVideoFrameTimeForData:o,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:this.loaderType_==="main"});const n=this.chooseNextRequest_();if(n.mediaIndex!==i.mediaIndex||n.partIndex!==i.partIndex){this.logger_("sync segment was incorrect, not appending");return}this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){this.loaderType_==="main"&&typeof e.timestampOffset=="number"&&!e.changedTimestampOffset&&(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:n}){if(i){const r=fp(i);if(this.activeInitSegmentId_===r)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=r}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=n,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},n){const r=this.sourceUpdater_.audioBuffered(),o=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+Fl(r).join(", ")),o.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+Fl(o).join(", "));const u=r.length?r.start(0):0,c=r.length?r.end(r.length-1):0,d=o.length?o.start(0):0,f=o.length?o.end(o.length-1):0;if(c-u<=Ud&&f-d<=Ud){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${Fl(r).join(", ")}, video buffer: ${Fl(o).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const g=this.currentTime_()-Ud;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${g}`),this.remove(0,g,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${Ud}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=ue.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},Ud*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},n){if(n){if(n.code===vk){this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i});return}this.logger_("Received non QUOTA_EXCEEDED_ERR on append",n),this.error({message:`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:Ae.Error.StreamingFailedToAppendSegment}}),this.trigger("appenderror")}}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:n,bytes:r}){if(!r){const u=[n];let c=n.byteLength;i&&(u.unshift(i),c+=i.byteLength),r=tF({bytes:c,segments:u})}const o={segmentInfo:Ml({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:o}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:r},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:r}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const n=this.pendingSegment_.segment,r=`${e}TimingInfo`;n[r]||(n[r]={}),n[r].transmuxerPrependedSeconds=i.prependedContentDuration||0,n[r].transmuxedPresentationStart=i.start.presentation,n[r].transmuxedDecodeStart=i.start.decode,n[r].transmuxedPresentationEnd=i.end.presentation,n[r].transmuxedDecodeEnd=i.end.decode,n[r].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:n}=t;if(!n||!n.byteLength||i==="audio"&&this.audioDisabled_)return;const r=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:r,data:n})}loadSegment_(e){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),typeof e.timestampOffset=="number"&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_()){Oo(this),this.loadQueue_.push(()=>{const t=Es({},e,{forceTimestampOffset:!0});Es(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});return}this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),n=this.mediaIndex!==null,r=e.timeline!==this.currentTimeline_&&e.timeline>0,o=i||n&&r;this.logger_(`Requesting +${Vk(e.uri)} +${Fu(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=XB({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:o,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:u,level:c,stream:d})=>{this.logger_(`${Fu(e)} logged from transmuxer stream ${d} as a ${c}: ${u}`)},triggerSegmentEventFn:({type:u,segment:c,keyInfo:d,trackInfo:f,timingInfo:p})=>{const y={segmentInfo:Ml({segment:c})};d&&(y.keyInfo=d),f&&(y.trackInfo=f),p&&(y.timingInfo=p),this.trigger({type:u,metadata:y})}})}trimBackBuffer_(e){const t=yF(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,n=e.segment.key||e.segment.map&&e.segment.map.key,r=e.segment.map&&!e.segment.map.bytes,o={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:n,isMediaInitialization:r},u=e.playlist.segments[e.mediaIndex-1];if(u&&u.timeline===t.timeline&&(u.videoTimingInfo?o.baseStartTime=u.videoTimingInfo.transmuxedDecodeEnd:u.audioTimingInfo&&(o.baseStartTime=u.audioTimingInfo.transmuxedDecodeEnd)),t.key){const c=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);o.key=this.segmentKey(t.key),o.key.iv=c}return t.map&&(o.map=this.initSegmentForMap(t.map)),o}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e"u"||d.end!==n+r?n:u.start}waitForAppendsToComplete_(e){const t=this.getCurrentMediaInfo_(e);if(!t){this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),this.trigger("error");return}const{hasAudio:i,hasVideo:n,isMuxed:r}=t,o=this.loaderType_==="main"&&n,u=!this.audioDisabled_&&i&&!r;if(e.waitingOnAppends=0,!e.hasAppendedData_){!e.timingInfo&&typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),this.checkAppendsDone_(e);return}o&&e.waitingOnAppends++,u&&e.waitingOnAppends++,o&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),u&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))}checkAppendsDone_(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,e.waitingOnAppends===0&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(e){const t=gF(this.loaderType_,this.getCurrentMediaInfo_(),e);return t?(this.error({message:t,playlistExclusionDuration:1/0}),this.trigger("error"),!0):!1}updateSourceBufferTimestampOffset_(e){if(e.timestampOffset===null||typeof e.timingInfo.start!="number"||e.changedTimestampOffset||this.loaderType_!=="main")return;let t=!1;e.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e.segment.videoTimingInfo,audioTimingInfo:e.segment.audioTimingInfo,timingInfo:e.timingInfo}),e.changedTimestampOffset=!0,e.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(e.timestampOffset),t=!0),e.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(e.timestampOffset),t=!0),t&&this.trigger("timestampoffset")}getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e,audioTimingInfo:t,timingInfo:i}){return this.useDtsForTimestampOffset_?e&&typeof e.transmuxedDecodeStart=="number"?e.transmuxedDecodeStart:t&&typeof t.transmuxedDecodeStart=="number"?t.transmuxedDecodeStart:i.start:i.start}updateTimingInfoEnd_(e){e.timingInfo=e.timingInfo||{};const t=this.getMediaInfo_(),n=this.loaderType_==="main"&&t&&t.hasVideo&&e.videoTimingInfo?e.videoTimingInfo:e.audioTimingInfo;n&&(e.timingInfo.end=typeof n.end=="number"?n.end:n.start+e.duration)}handleAppendsDone_(){if(this.pendingSegment_){const c={segmentInfo:Ml({type:this.loaderType_,segment:this.pendingSegment_})};this.trigger({type:"appendsdone",metadata:c})}if(!this.pendingSegment_){this.state="READY",this.paused()||this.monitorBuffer_();return}const e=this.pendingSegment_;e.part&&e.part.syncInfo?e.part.syncInfo.markAppended():e.segment.syncInfo&&e.segment.syncInfo.markAppended(),this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:this.loaderType_==="main"});const t=_F(e,this.sourceType_);if(t&&(t.severity==="warn"?Ae.log.warn(t.message):this.logger_(t.message)),this.recordThroughput_(e),this.pendingSegment_=null,this.state="READY",e.isSyncRequest&&(this.trigger("syncinfoupdate"),!e.hasAppendedData_)){this.logger_(`Throwing away un-appended sync request ${Fu(e)}`);return}this.logger_(`Appended ${Fu(e)}`),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),this.loaderType_==="main"&&!this.audioDisabled_&&this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");const i=e.segment,n=e.part,r=i.end&&this.currentTime_()-i.end>e.playlist.targetDuration*3,o=n&&n.end&&this.currentTime_()-n.end>e.playlist.partTargetDuration*3;if(r||o){this.logger_(`bad ${r?"segment":"part"} ${Fu(e)}`),this.resetEverything();return}this.mediaIndex!==null&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duratione.toUpperCase())},SF=["video","audio"],cx=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},EF=(s,e)=>{for(let t=0;t{if(e.queue.length===0)return;let t=0,i=e.queue[t];if(i.type==="mediaSource"){!e.updating()&&e.mediaSource.readyState!=="closed"&&(e.queue.shift(),i.action(e),i.doneFn&&i.doneFn(),lc("audio",e),lc("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||cx(s,e))){if(i.type!==s){if(t=EF(s,e.queue),t===null)return;i=e.queue[t]}if(e.queue.splice(t,1),e.queuePending[s]=i,i.action(s,e),!i.doneFn){e.queuePending[s]=null,lc(s,e);return}}},zk=(s,e)=>{const t=e[`${s}Buffer`],i=Gk(s);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[s]=null,e[`${s}Buffer`]=null)},Jr=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,Kn={appendBuffer:(s,e,t)=>(i,n)=>{const r=n[`${i}Buffer`];if(Jr(n.mediaSource,r)){n.logger_(`Appending segment ${e.mediaIndex}'s ${s.length} bytes to ${i}Buffer`);try{r.appendBuffer(s)}catch(o){n.logger_(`Error with code ${o.code} `+(o.code===vk?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),n.queuePending[i]=null,t(o)}}},remove:(s,e)=>(t,i)=>{const n=i[`${t}Buffer`];if(Jr(i.mediaSource,n)){i.logger_(`Removing ${s} to ${e} from ${t}Buffer`);try{n.remove(s,e)}catch{i.logger_(`Remove ${s} to ${e} from ${t}Buffer failed`)}}},timestampOffset:s=>(e,t)=>{const i=t[`${e}Buffer`];Jr(t.mediaSource,i)&&(t.logger_(`Setting ${e}timestampOffset to ${s}`),i.timestampOffset=s)},callback:s=>(e,t)=>{s()},endOfStream:s=>e=>{if(e.mediaSource.readyState==="open"){e.logger_(`Calling mediaSource endOfStream(${s||""})`);try{e.mediaSource.endOfStream(s)}catch(t){Ae.log.warn("Failed to call media source endOfStream",t)}}},duration:s=>e=>{e.logger_(`Setting mediaSource duration to ${s}`);try{e.mediaSource.duration=s}catch(t){Ae.log.warn("Failed to set media source duration",t)}},abort:()=>(s,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${s}Buffer`];if(Jr(e.mediaSource,t)){e.logger_(`calling abort on ${s}Buffer`);try{t.abort()}catch(i){Ae.log.warn(`Failed to abort on ${s}Buffer`,i)}}},addSourceBuffer:(s,e)=>t=>{const i=Gk(s),n=pc(e);t.logger_(`Adding ${s}Buffer with codec ${e} to mediaSource`);const r=t.mediaSource.addSourceBuffer(n);r.addEventListener("updateend",t[`on${i}UpdateEnd_`]),r.addEventListener("error",t[`on${i}Error_`]),t.codecs[s]=e,t[`${s}Buffer`]=r},removeSourceBuffer:s=>e=>{const t=e[`${s}Buffer`];if(zk(s,e),!!Jr(e.mediaSource,t)){e.logger_(`Removing ${s}Buffer with codec ${e.codecs[s]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){Ae.log.warn(`Failed to removeSourceBuffer ${s}Buffer`,i)}}},changeType:s=>(e,t)=>{const i=t[`${e}Buffer`],n=pc(s);if(!Jr(t.mediaSource,i))return;const r=s.substring(0,s.indexOf(".")),o=t.codecs[e];if(o.substring(0,o.indexOf("."))===r)return;const c={codecsChangeInfo:{from:o,to:s}};t.trigger({type:"codecschange",metadata:c}),t.logger_(`changing ${e}Buffer codec from ${o} to ${s}`);try{i.changeType(n),t.codecs[e]=s}catch(d){c.errorType=Ae.Error.StreamingCodecsChangeError,c.error=d,d.metadata=c,t.error_=d,t.trigger("error"),Ae.log.warn(`Failed to changeType on ${e}Buffer`,d)}}},Yn=({type:s,sourceUpdater:e,action:t,doneFn:i,name:n})=>{e.queue.push({type:s,action:t,doneFn:i,name:n}),lc(s,e)},ZE=(s,e)=>t=>{const i=e[`${s}Buffered`](),n=B4(i);if(e.logger_(`received "updateend" event for ${s} Source Buffer: `,n),e.queuePending[s]){const r=e.queuePending[s].doneFn;e.queuePending[s]=null,r&&r(e[`${s}Error_`])}lc(s,e)};class qk extends Ae.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>lc("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=pr("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=ZE("video",this),this.onAudioUpdateEnd_=ZE("audio",this),this.onVideoError_=t=>{this.videoError_=t},this.onAudioError_=t=>{this.audioError_=t},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(e,t){Yn({type:"mediaSource",sourceUpdater:this,action:Kn.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){Yn({type:e,sourceUpdater:this,action:Kn.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){Ae.log.error("removeSourceBuffer is not supported!");return}Yn({type:"mediaSource",sourceUpdater:this,action:Kn.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!Ae.browser.IS_FIREFOX&&ue.MediaSource&&ue.MediaSource.prototype&&typeof ue.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return ue.SourceBuffer&&ue.SourceBuffer.prototype&&typeof ue.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){Ae.log.error("changeType is not supported!");return}Yn({type:e,sourceUpdater:this,action:Kn.changeType(t),name:"changeType"})}addOrChangeSourceBuffers(e){if(!e||typeof e!="object"||Object.keys(e).length===0)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach(t=>{const i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)})}appendBuffer(e,t){const{segmentInfo:i,type:n,bytes:r}=e;if(this.processedAppend_=!0,n==="audio"&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([e,t]),this.logger_(`delayed audio append of ${r.length} until video append`);return}const o=t;if(Yn({type:n,sourceUpdater:this,action:Kn.appendBuffer(r,i||{mediaIndex:-1},o),doneFn:t,name:"appendBuffer"}),n==="video"){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const u=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${u.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,u.forEach(c=>{this.appendBuffer.apply(this,c)})}}audioBuffered(){return Jr(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:Vs()}videoBuffered(){return Jr(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:Vs()}buffered(){const e=Jr(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=Jr(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():U4(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=$a){Yn({type:"mediaSource",sourceUpdater:this,action:Kn.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=$a){typeof e!="string"&&(e=void 0),Yn({type:"mediaSource",sourceUpdater:this,action:Kn.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=$a){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}Yn({type:"audio",sourceUpdater:this,action:Kn.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=$a){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}Yn({type:"video",sourceUpdater:this,action:Kn.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(cx("audio",this)||cx("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(Yn({type:"audio",sourceUpdater:this,action:Kn.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(Yn({type:"video",sourceUpdater:this,action:Kn.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&Yn({type:"audio",sourceUpdater:this,action:Kn.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&Yn({type:"video",sourceUpdater:this,action:Kn.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),SF.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>zk(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const JE=s=>decodeURIComponent(escape(String.fromCharCode.apply(null,s))),wF=s=>{const e=new Uint8Array(s);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},e2=new Uint8Array(` + +`.split("").map(s=>s.charCodeAt(0)));class AF extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class CF extends ux{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return Vs();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return Vs([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=fp(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const r=e2.byteLength+e.bytes.byteLength,o=new Uint8Array(r);o.set(e.bytes),o.set(e2,e.bytes.byteLength),this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:o}}return n||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return typeof e>"u"?this.subtitlesTrack_:(this.subtitlesTrack_=e,this.state==="INIT"&&this.couldBeginLoading_()&&this.init_(),this.subtitlesTrack_)}remove(e,t){Yd(e,t,this.subtitlesTrack_)}fillBuffer_(){const e=this.chooseNextRequest_();if(e){if(this.syncController_.timestampOffsetForTimeline(e.timeline)===null){const t=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};this.syncController_.one("timestampoffset",t),this.state="WAITING_ON_TIMELINE";return}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,i){if(!this.subtitlesTrack_){this.state="READY";return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_){this.state="READY",this.mediaRequestsAborted+=1;return}if(e){e.code===na.TIMEOUT&&this.handleTimeout_(),e.code===na.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}const n=this.pendingSegment_,r=i.mp4VttCues&&i.mp4VttCues.length;r&&(n.mp4VttCues=i.mp4VttCues),this.saveBandwidthRelatedStats_(n.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const o=n.segment;if(o.map&&(o.map.bytes=t.map.bytes),n.bytes=t.bytes,typeof ue.WebVTT!="function"&&typeof this.loadVttJs=="function"){this.state="WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,i),()=>this.stopForError({message:"Error loading vtt.js"}));return}o.requested=!0;try{this.parseVTTCues_(n)}catch(u){this.stopForError({message:u.message,metadata:{errorType:Ae.Error.StreamingVttParserError,error:u}});return}if(r||this.updateTimeMapping_(n,this.syncController_.timelines[n.timeline],this.playlist_),n.cues.length?n.timingInfo={start:n.cues[0].startTime,end:n.cues[n.cues.length-1].endTime}:n.timingInfo={start:n.startOfSegment,end:n.startOfSegment+n.duration},n.isSyncRequest){this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY";return}n.byteLength=n.bytes.byteLength,this.mediaSecondsLoaded+=o.duration,n.cues.forEach(u=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new ue.VTTCue(u.startTime,u.endTime,u.text):u)}),uF(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){const i=e&&e.type==="vtt",n=t&&t.type==="text";i&&n&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){const t=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(i=>{const n=i.start+t,r=i.end+t,o=new ue.VTTCue(n,r,i.cueText);i.settings&&i.settings.split(" ").forEach(u=>{const c=u.split(":"),d=c[0],f=c[1];o[d]=isNaN(f)?f:Number(f)}),e.cues.push(o)})}parseVTTCues_(e){let t,i=!1;if(typeof ue.WebVTT!="function")throw new AF;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof ue.TextDecoder=="function"?t=new ue.TextDecoder("utf8"):(t=ue.WebVTT.StringDecoder(),i=!0);const n=new ue.WebVTT.Parser(ue,ue.vttjs,t);if(n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=o=>{e.timestampmap=o},n.onparsingerror=o=>{Ae.log.warn("Error encountered when parsing cues: "+o.message)},e.segment.map){let o=e.segment.map.bytes;i&&(o=JE(o)),n.parse(o)}let r=e.bytes;i&&(r=JE(r)),n.parse(r),n.flush()}updateTimeMapping_(e,t,i){const n=e.segment;if(!t)return;if(!e.cues.length){n.empty=!0;return}const{MPEGTS:r,LOCAL:o}=e.timestampmap,c=r/Bl.ONE_SECOND_IN_TS-o+t.mapping;if(e.cues.forEach(d=>{const f=d.endTime-d.startTime,p=this.handleRollover_(d.startTime+c,t.time);d.startTime=Math.max(p,0),d.endTime=Math.max(p+f,0)}),!i.syncInfo){const d=e.cues[0].startTime,f=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(d,f-n.duration)}}}handleRollover_(e,t){if(t===null)return e;let i=e*Bl.ONE_SECOND_IN_TS;const n=t*Bl.ONE_SECOND_IN_TS;let r;for(n4294967296;)i+=r;return i/Bl.ONE_SECOND_IN_TS}}const kF=function(s,e){const t=s.cues;for(let i=0;i=n.adStartTime&&e<=n.adEndTime)return n}return null},DF=function(s,e,t=0){if(!s.segments)return;let i=t,n;for(let r=0;r=this.start&&e0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}}class Kk{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){const{mediaSequence:i,segments:n}=e;if(this.isReliable_=this.isReliablePlaylist_(i,n),!!this.isReliable_)return this.updateStorage_(n,i,this.calculateBaseTime_(i,n,t))}getSyncInfoForTime(e){for(const{segmentSyncInfo:t,partsSyncInfo:i}of this.storage_.values())if(i.length){for(const n of i)if(n.isInRange(e))return n}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,i){const n=new Map;let r=` +`,o=i,u=t;this.start_=o,e.forEach((c,d)=>{const f=this.storage_.get(u),p=o,g=p+c.duration,y=!!(f&&f.segmentSyncInfo&&f.segmentSyncInfo.isAppended),x=new t2({start:p,end:g,appended:y,segmentIndex:d});c.syncInfo=x;let _=o;const w=(c.parts||[]).map((D,I)=>{const L=_,B=_+D.duration,j=!!(f&&f.partsSyncInfo&&f.partsSyncInfo[I]&&f.partsSyncInfo[I].isAppended),V=new t2({start:L,end:B,appended:j,segmentIndex:d,partIndex:I});return _=B,r+=`Media Sequence: ${u}.${I} | Range: ${L} --> ${B} | Appended: ${j} +`,D.syncInfo=V,V});n.set(u,new LF(x,w)),r+=`${Vk(c.resolvedUri)} | Media Sequence: ${u} | Range: ${p} --> ${g} | Appended: ${y} +`,u++,o=g}),this.end_=o,this.storage_=n,this.diagnostics_=r}calculateBaseTime_(e,t,i){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const n=Math.min(...this.storage_.keys());if(et!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(s,e,t,i,n,r)=>{const o=s.getMediaSequenceSync(r);if(!o||!o.isReliable)return null;const u=o.getSyncInfoForTime(n);return u?{time:u.start,partIndex:u.partIndex,segmentIndex:u.segmentIndex}:null}},{name:"ProgramDateTime",run:(s,e,t,i,n)=>{if(!Object.keys(s.timelineToDatetimeMappings).length)return null;let r=null,o=null;const u=ex(e);n=n||0;for(let c=0;c{let r=null,o=null;n=n||0;const u=ex(e);for(let c=0;c=y)&&(o=y,r={time:g,segmentIndex:f.segmentIndex,partIndex:f.partIndex})}}return r}},{name:"Discontinuity",run:(s,e,t,i,n)=>{let r=null;if(n=n||0,e.discontinuityStarts&&e.discontinuityStarts.length){let o=null;for(let u=0;u=p)&&(o=p,r={time:f.time,segmentIndex:c,partIndex:null})}}}return r}},{name:"Playlist",run:(s,e,t,i,n)=>e.syncInfo?{time:e.syncInfo.time,segmentIndex:e.syncInfo.mediaSequence-e.mediaSequence,partIndex:null}:null}];class IF extends Ae.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new Kk,i=new i2(t),n=new i2(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:n},this.logger_=pr("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,n,r){if(t!==1/0)return Xy.find(({name:c})=>c==="VOD").run(this,e,t);const o=this.runStrategies_(e,t,i,n,r);if(!o.length)return null;for(const u of o){const{syncPoint:c,strategy:d}=u,{segmentIndex:f,time:p}=c;if(f<0)continue;const g=e.segments[f],y=p,x=y+g.duration;if(this.logger_(`Strategy: ${d}. Current time: ${n}. selected segment: ${f}. Time: [${y} -> ${x}]}`),n>=y&&n0&&(n.time*=-1),Math.abs(n.time+nh({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n,r){const o=[];for(let u=0;uRF){Ae.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);return}for(let n=i-1;n>=0;n--){const r=e.segments[n];if(r&&typeof r.start<"u"){t.syncInfo={mediaSequence:e.mediaSequence+n,time:r.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),n=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:n.start}));const r=n.dateTimeObject;n.discontinuity&&t&&r&&(this.timelineToDatetimeMappings[n.timeline]=-(r.getTime()/1e3))}timestampOffsetForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].time}mappingForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){const n=e.segment,r=e.part;let o=this.timelines[e.timeline],u,c;if(typeof e.timestampOffset=="number")o={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=o,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${o.time}] [mapping: ${o.mapping}]`)),u=e.startOfSegment,c=t.end+o.mapping;else if(o)u=t.start+o.mapping,c=t.end+o.mapping;else return!1;return r&&(r.start=u,r.end=c),(!n.start||uc){let d;u<0?d=i.start-nh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):d=i.end+nh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[o]={time:d,accuracy:c}}}}dispose(){this.trigger("dispose"),this.off()}}class NF extends Ae.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return typeof t=="number"&&typeof i=="number"&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){if(typeof t=="number"&&typeof i=="number"){this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e];const n={timelineChangeInfo:{from:t,to:i}};this.trigger({type:"timelinechange",metadata:n})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const OF=Ik(Nk(function(){var s=(function(){function _(){this.listeners={}}var w=_.prototype;return w.on=function(I,L){this.listeners[I]||(this.listeners[I]=[]),this.listeners[I].push(L)},w.off=function(I,L){if(!this.listeners[I])return!1;var B=this.listeners[I].indexOf(L);return this.listeners[I]=this.listeners[I].slice(0),this.listeners[I].splice(B,1),B>-1},w.trigger=function(I){var L=this.listeners[I];if(L)if(arguments.length===2)for(var B=L.length,j=0;j>7)*283)^B]=B;for(j=V=0;!I[j];j^=O||1,V=z[V]||1)for(Q=V^V<<1^V<<2^V<<3^V<<4,Q=Q>>8^Q&255^99,I[j]=Q,L[Q]=j,q=M[N=M[O=M[j]]],re=q*16843009^N*65537^O*257^j*16843008,Y=M[Q]*257^Q*16843008,B=0;B<4;B++)w[B][j]=Y=Y<<24^Y>>>8,D[B][Q]=re=re<<24^re>>>8;for(B=0;B<5;B++)w[B]=w[B].slice(0),D[B]=D[B].slice(0);return _};let i=null;class n{constructor(w){i||(i=t()),this._tables=[[i[0][0].slice(),i[0][1].slice(),i[0][2].slice(),i[0][3].slice(),i[0][4].slice()],[i[1][0].slice(),i[1][1].slice(),i[1][2].slice(),i[1][3].slice(),i[1][4].slice()]];let D,I,L;const B=this._tables[0][4],j=this._tables[1],V=w.length;let M=1;if(V!==4&&V!==6&&V!==8)throw new Error("Invalid aes key size");const z=w.slice(0),O=[];for(this._key=[z,O],D=V;D<4*V+28;D++)L=z[D-1],(D%V===0||V===8&&D%V===4)&&(L=B[L>>>24]<<24^B[L>>16&255]<<16^B[L>>8&255]<<8^B[L&255],D%V===0&&(L=L<<8^L>>>24^M<<24,M=M<<1^(M>>7)*283)),z[D]=z[D-V]^L;for(I=0;D;I++,D--)L=z[I&3?D:D-4],D<=4||I<4?O[I]=L:O[I]=j[0][B[L>>>24]]^j[1][B[L>>16&255]]^j[2][B[L>>8&255]]^j[3][B[L&255]]}decrypt(w,D,I,L,B,j){const V=this._key[1];let M=w^V[0],z=L^V[1],O=I^V[2],N=D^V[3],q,Q,Y;const re=V.length/4-2;let Z,H=4;const K=this._tables[1],ie=K[0],te=K[1],ne=K[2],$=K[3],ee=K[4];for(Z=0;Z>>24]^te[z>>16&255]^ne[O>>8&255]^$[N&255]^V[H],Q=ie[z>>>24]^te[O>>16&255]^ne[N>>8&255]^$[M&255]^V[H+1],Y=ie[O>>>24]^te[N>>16&255]^ne[M>>8&255]^$[z&255]^V[H+2],N=ie[N>>>24]^te[M>>16&255]^ne[z>>8&255]^$[O&255]^V[H+3],H+=4,M=q,z=Q,O=Y;for(Z=0;Z<4;Z++)B[(3&-Z)+j]=ee[M>>>24]<<24^ee[z>>16&255]<<16^ee[O>>8&255]<<8^ee[N&255]^V[H++],q=M,M=z,z=O,O=N,N=q}}class r extends s{constructor(){super(s),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(w){this.jobs.push(w),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const o=function(_){return _<<24|(_&65280)<<8|(_&16711680)>>8|_>>>24},u=function(_,w,D){const I=new Int32Array(_.buffer,_.byteOffset,_.byteLength>>2),L=new n(Array.prototype.slice.call(w)),B=new Uint8Array(_.byteLength),j=new Int32Array(B.buffer);let V,M,z,O,N,q,Q,Y,re;for(V=D[0],M=D[1],z=D[2],O=D[3],re=0;re{const I=_[D];g(I)?w[D]={bytes:I.buffer,byteOffset:I.byteOffset,byteLength:I.byteLength}:w[D]=I}),w};self.onmessage=function(_){const w=_.data,D=new Uint8Array(w.encrypted.bytes,w.encrypted.byteOffset,w.encrypted.byteLength),I=new Uint32Array(w.key.bytes,w.key.byteOffset,w.key.byteLength/4),L=new Uint32Array(w.iv.bytes,w.iv.byteOffset,w.iv.byteLength/4);new c(D,I,L,function(B,j){self.postMessage(x({source:w.source,decrypted:j}),[j.buffer])})}}));var MF=Rk(OF);const PF=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},Yk=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},dx=(s,e)=>{e.activePlaylistLoader=s,s.load()},BF=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:n}}=e,r=n.activeTrack(),o=n.getActiveGroup(),u=n.activePlaylistLoader,c=n.lastGroup_;if(!(o&&c&&o.id===c.id)&&(n.lastGroup_=o,n.lastTrack_=r,Yk(t,n),!(!o||o.isMainPlaylist))){if(!o.playlistLoader){u&&i.resetEverything();return}t.resyncLoader(),dx(o.playlistLoader,n)}},FF=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},UF=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:n},mediaTypes:{[s]:r}}=e,o=r.activeTrack(),u=r.getActiveGroup(),c=r.activePlaylistLoader,d=r.lastTrack_;if(!(d&&o&&d.id===o.id)&&(r.lastGroup_=u,r.lastTrack_=o,Yk(i,r),!!u)){if(u.isMainPlaylist){if(!o||!d||o.id===d.id)return;const f=e.vhs.playlistController_,p=f.selectPlaylist();if(f.media()===p)return;r.logger_(`track change. Switching main audio from ${d.id} to ${o.id}`),t.pause(),n.resetEverything(),f.fastQualityChange_(p);return}if(s==="AUDIO"){if(!u.playlistLoader){n.setAudio(!0),n.resetEverything();return}i.setAudio(!0),n.setAudio(!1)}if(c===u.playlistLoader){dx(u.playlistLoader,r);return}i.track&&i.track(o),i.resetEverything(),dx(u.playlistLoader,r)}},mp={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,n=t.activeTrack(),r=t.activeGroup(),o=(r.filter(c=>c.default)[0]||r[0]).id,u=t.tracks[o];if(n===u){i({error:{message:"Problem encountered loading the default audio track."}});return}Ae.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const c in t.tracks)t.tracks[c].enabled=t.tracks[c]===u;t.onTrackChanged()},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:t}}=e;Ae.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},s2={AUDIO:(s,e,t)=>{if(!e)return;const{tech:i,requestOptions:n,segmentLoaders:{[s]:r}}=t;e.on("loadedmetadata",()=>{const o=e.media();r.playlist(o,n),(!i.paused()||o.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",mp[s](s,t))},SUBTITLES:(s,e,t)=>{const{tech:i,requestOptions:n,segmentLoaders:{[s]:r},mediaTypes:{[s]:o}}=t;e.on("loadedmetadata",()=>{const u=e.media();r.playlist(u,n),r.track(o.activeTrack()),(!i.paused()||u.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",mp[s](s,t))}},jF={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:n},requestOptions:r,main:{mediaGroups:o},mediaTypes:{[s]:{groups:u,tracks:c,logger_:d}},mainPlaylistLoader:f}=e,p=Ih(f.main);(!o[s]||Object.keys(o[s]).length===0)&&(o[s]={main:{default:{default:!0}}},p&&(o[s].main.default.playlists=f.main.playlists));for(const g in o[s]){u[g]||(u[g]=[]);for(const y in o[s][g]){let x=o[s][g][y],_;if(p?(d(`AUDIO group '${g}' label '${y}' is a main playlist`),x.isMainPlaylist=!0,_=null):i==="vhs-json"&&x.playlists?_=new Qu(x.playlists[0],t,r):x.resolvedUri?_=new Qu(x.resolvedUri,t,r):x.playlists&&i==="dash"?_=new ax(x.playlists[0],t,r,f):_=null,x=Di({id:y,playlistLoader:_},x),s2[s](s,x.playlistLoader,e),u[g].push(x),typeof c[y]>"u"){const w=new Ae.AudioTrack({id:y,kind:PF(x),enabled:!1,language:x.language,default:x.default,label:y});c[y]=w}}}n.on("error",mp[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:n,segmentLoaders:{[s]:r},requestOptions:o,main:{mediaGroups:u},mediaTypes:{[s]:{groups:c,tracks:d}},mainPlaylistLoader:f}=e;for(const p in u[s]){c[p]||(c[p]=[]);for(const g in u[s][p]){if(!i.options_.useForcedSubtitles&&u[s][p][g].forced)continue;let y=u[s][p][g],x;if(n==="hls")x=new Qu(y.resolvedUri,i,o);else if(n==="dash"){if(!y.playlists.filter(w=>w.excludeUntil!==1/0).length)return;x=new ax(y.playlists[0],i,o,f)}else n==="vhs-json"&&(x=new Qu(y.playlists?y.playlists[0]:y.resolvedUri,i,o));if(y=Di({id:g,playlistLoader:x},y),s2[s](s,y.playlistLoader,e),c[p].push(y),typeof d[g]>"u"){const _=t.addRemoteTextTrack({id:g,kind:"subtitles",default:y.default&&y.autoselect,language:y.language,label:g},!1).track;d[g]=_}}}r.on("error",mp[s](s,e))},"CLOSED-CAPTIONS":(s,e)=>{const{tech:t,main:{mediaGroups:i},mediaTypes:{[s]:{groups:n,tracks:r}}}=e;for(const o in i[s]){n[o]||(n[o]=[]);for(const u in i[s][o]){const c=i[s][o][u];if(!/^(?:CC|SERVICE)/.test(c.instreamId))continue;const d=t.options_.vhs&&t.options_.vhs.captionServices||{};let f={label:u,language:c.language,instreamId:c.instreamId,default:c.default&&c.autoselect};if(d[f.instreamId]&&(f=Di(f,d[f.instreamId])),f.default===void 0&&delete f.default,n[o].push(Di({id:u},c)),typeof r[u]>"u"){const p=t.addRemoteTextTrack({id:f.instreamId,kind:"captions",default:f.default,language:f.language,label:f.label},!1).track;r[u]=p}}}}},Wk=(s,e)=>{for(let t=0;tt=>{const{mainPlaylistLoader:i,mediaTypes:{[s]:{groups:n}}}=e,r=i.media();if(!r)return null;let o=null;r.attributes[s]&&(o=n[r.attributes[s]]);const u=Object.keys(n);if(!o)if(s==="AUDIO"&&u.length>1&&Ih(e.main))for(let c=0;c"u"?o:t===null||!o?null:o.filter(c=>c.id===t.id)[0]||null},HF={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:{tracks:t}}}=e;for(const i in t)if(t[i].enabled)return t[i];return null},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:{tracks:t}}}=e;for(const i in t)if(t[i].mode==="showing"||t[i].mode==="hidden")return t[i];return null}},VF=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},GF=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(d=>{jF[d](d,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:n,segmentLoaders:{["AUDIO"]:r,main:o}}=s;["AUDIO","SUBTITLES"].forEach(d=>{e[d].activeGroup=$F(d,s),e[d].activeTrack=HF[d](d,s),e[d].onGroupChanged=BF(d,s),e[d].onGroupChanging=FF(d,s),e[d].onTrackChanged=UF(d,s),e[d].getActiveGroup=VF(d,s)});const u=e.AUDIO.activeGroup();if(u){const d=(u.filter(p=>p.default)[0]||u[0]).id;e.AUDIO.tracks[d].enabled=!0,e.AUDIO.onGroupChanged(),e.AUDIO.onTrackChanged(),e.AUDIO.getActiveGroup().playlistLoader?(o.setAudio(!1),r.setAudio(!0)):o.setAudio(!0)}t.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanging())});const c=()=>{e.AUDIO.onTrackChanged(),i.trigger({type:"usage",name:"vhs-audio-change"})};i.audioTracks().addEventListener("change",c),i.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),n.on("dispose",()=>{i.audioTracks().removeEventListener("change",c),i.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),i.clearTracks("audio");for(const d in e.AUDIO.tracks)i.audioTracks().addTrack(e.AUDIO.tracks[d])},zF=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:$a,activeTrack:$a,getActiveGroup:$a,onGroupChanged:$a,onTrackChanged:$a,lastTrack_:null,logger_:pr(`MediaGroups[${e}]`)}}),s};class n2{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){e===1&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=Nn(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(t=>[t.ID,t])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}let qF=class extends Ae.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new n2,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=pr("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const i=t.serverUri||t.serverURL;if(!i){this.logger_(`steering manifest URL is ${i}, cannot request steering manifest.`),this.trigger("error");return}if(i.startsWith("data:")){this.decodeDataUriManifest_(i.substring(i.indexOf(",")+1));return}this.steeringManifest.reloadUri=Nn(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const i=e?t:this.getRequestURI(t);if(!i){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}const n={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:n}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(r,o)=>{if(r){if(o.status===410){this.logger_(`manifest request 410 ${r}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),this.excludedSteeringManifestURLs.add(i);return}if(o.status===429){const d=o.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${r}.`),this.logger_(`content steering will retry in ${d} seconds.`),this.startTTLTimeout_(parseInt(d,10));return}this.logger_(`manifest failed to load ${r}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:n});let u;try{u=JSON.parse(this.request_.responseText)}catch(d){const f={errorType:Ae.Error.StreamingContentSteeringParserError,error:d};this.trigger({type:"error",metadata:f})}this.assignSteeringProperties_(u);const c={contentSteeringInfo:n.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:c}),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new ue.URL(e),i=new ue.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(ue.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new ue.URL(e),i=this.getPathway(),n=this.getBandwidth_();if(i){const r=`_${this.manifestType_}_pathway`;t.searchParams.set(r,i)}if(n){const r=`_${this.manifestType_}_throughput`;t.searchParams.set(r,n)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger("error");return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const i=(n=>{for(const r of n)if(this.availablePathways_.has(r))return r;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==i&&(this.currentPathway=i,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=n=>this.excludedSteeringManifestURLs.has(n);if(this.proxyServerUrl_){const n=this.setProxyServerUrl_(e);if(!t(n))return n}const i=this.setSteeringParams_(e);return t(i)?null:i}startTTLTimeout_(e=this.steeringManifest.ttl){const t=e*1e3;this.ttlTimeout_=ue.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){ue.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new n2}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(Nn(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}};const KF=(s,e)=>{let t=null;return(...i)=>{clearTimeout(t),t=setTimeout(()=>{s.apply(null,i)},e)}},YF=10;let Mo;const WF=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],XF=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},QF=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:o,bufferBasedABR:u,log:c}){if(!i)return Ae.log.warn("We received no playlist to switch to. Please check your stream."),!1;const d=`allowing switch ${s&&s.id||"null"} -> ${i.id}`;if(!s)return c(`${d} as current playlist is not set`),!0;if(i.id===s.id)return!1;const f=!!Xu(e,t).length;if(!s.endList)return!f&&typeof s.partTargetDuration=="number"?(c(`not ${d} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(c(`${d} as current playlist is live`),!0);const p=Tb(e,t),g=u?$s.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:$s.MAX_BUFFER_LOW_WATER_LINE;if(ox)&&p>=n){let _=`${d} as forwardBuffer >= bufferLowWaterLine (${p} >= ${n})`;return u&&(_+=` and next bandwidth > current bandwidth (${y} > ${x})`),c(_),!0}return c(`not ${d} as no switching criteria met`),!1};class ZF extends Ae.EventTarget{constructor(e){super(),this.fastQualityChange_=KF(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:n,bandwidth:r,externVhs:o,useCueTags:u,playlistExclusionDuration:c,enableLowInitialPlaylist:d,sourceType:f,cacheEncryptionKeys:p,bufferBasedABR:g,leastPixelDiffSelector:y,captionServices:x,experimentalUseMMS:_}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:w}=e;(w===null||typeof w>"u")&&(w=1/0),Mo=o,this.bufferBasedABR=!!g,this.leastPixelDiffSelector=!!y,this.withCredentials=i,this.tech_=n,this.vhs_=n.vhs,this.player_=e.player_,this.sourceType_=f,this.useCueTags_=u,this.playlistExclusionDuration=c,this.maxPlaylistRetries=w,this.enableLowInitialPlaylist=d,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:w,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=zF(),_&&ue.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new ue.ManagedMediaSource,this.usingManagedMediaSource_=!0,Ae.log("Using ManagedMediaSource")):ue.MediaSource&&(this.mediaSource=new ue.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=Vs(),this.hasPlayed_=!1,this.syncController_=new IF(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new MF,this.sourceUpdater_=new qk(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new NF,this.keyStatusMap_=new Map;const D={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:x,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:r,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:p,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new ax(t,this.vhs_,Di(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Qu(t,this.vhs_,Di(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new ux(Di(D,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new ux(Di(D,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new CF(Di(D,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((B,j)=>{function V(){n.off("vttjserror",M),B()}function M(){n.off("vttjsloaded",V),j()}n.one("vttjsloaded",V),n.one("vttjserror",M),n.addWebVttScript_()})}),e);const I=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new qF(this.vhs_.xhr,I),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),WF.forEach(B=>{this[B+"_"]=XF.bind(this,B)}),this.logger_=pr("pc"),this.triggeredFmp4Usage=!1,this.tech_.preload()==="none"?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const L=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(L,()=>{const B=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-B,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const n=this.media(),r=n&&(n.id||n.uri),o=e&&(e.id||e.uri);if(r&&r!==o){this.logger_(`switch media ${r} -> ${o} from ${t}`);const u={renditionInfo:{id:o,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:u}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],i=t?t.activeGroup():null,n=this.contentSteeringController_.getPathway();if(i&&n){const o=(i.length?i[0].playlists:i.playlists).filter(u=>u.attributes.serviceLocation===n);o.length&&this.mediaTypes_[e].activePlaylistLoader.media(o[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=ue.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(ue.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const i=e.mediaGroups.AUDIO,n=Object.keys(i);let r;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)r=this.mediaTypes_.AUDIO.activeTrack();else{const u=i.main||n.length&&i[n[0]];for(const c in u)if(u[c].default){r={label:c};break}}if(!r)return t;const o=[];for(const u in i)if(i[u][r.label]){const c=i[u][r.label];if(c.playlists&&c.playlists.length)o.push.apply(o,c.playlists);else if(c.uri)o.push(c);else if(e.playlists.length)for(let d=0;d{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;tx(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,t.endList&&this.tech_.preload()!=="none"&&(this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.mainSegmentLoader_.load()),GF({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),t),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let t=this.mainPlaylistLoader_.media();if(!t){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let i;if(this.enableLowInitialPlaylist&&(i=this.selectInitialPlaylist()),i||(i=this.selectPlaylist()),!i||!this.shouldSwitchToMedia_(i)||(this.initialMedia_=i,this.switchMedia_(this.initialMedia_,"initial"),!(this.sourceType_==="vhs-json"&&this.initialMedia_.segments)))return;t=this.initialMedia_}this.handleUpdatedMediaPlaylist(t)}),this.mainPlaylistLoader_.on("error",()=>{const t=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:t.playlist,error:t})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;tx(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,this.sourceType_==="dash"&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const t=this.mainPlaylistLoader_.media();if(t.lastExcludeReason_==="playlist-unchanged")return;this.stuckAtPlaylistEnd_(t)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(t=>{this.mainPlaylistLoader_.on(t,i=>{this.player_.trigger(Es({},i))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const i=e.mediaGroups||{};let n=!0;const r=Object.keys(i.AUDIO);for(const o in i.AUDIO)for(const u in i.AUDIO[o])i.AUDIO[o][u].uri||(n=!1);n&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Mo.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),r.length&&Object.keys(i.AUDIO[r[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),n=this.bufferLowWaterLine(),r=this.bufferHighWaterLine(),o=this.tech_.buffered();return QF({buffered:o,currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const i=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:i.playlist,error:i})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const i=this.audioSegmentLoader_.pendingSegment_;if(!i||!i.segment||!i.segment.syncInfo)return;const n=i.segment.syncInfo.end+.01;this.tech_.setCurrentTime(n)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",i=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:YF}))});const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const i=this.getCodecsOrExclude_();i&&this.sourceUpdater_.addOrChangeSourceBuffers(i)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(i=>{this.mainSegmentLoader_.on(i,n=>{this.player_.trigger(Es({},n))}),this.audioSegmentLoader_.on(i,n=>{this.player_.trigger(Es({},n))}),this.subtitleSegmentLoader_.on(i,n=>{this.player_.trigger(Es({},n))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_("skipping fastQualityChange because new media is same as old");return}this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime(){})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();!t||t.hasVideo?e=e&&this.audioSegmentLoader_.ended_:e=this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const i=this.syncController_.getExpiredTime(e,this.duration());if(i===null)return!1;const n=Mo.Playlist.playlistEnd(e,i),r=this.tech_.currentTime(),o=this.tech_.buffered();if(!o.length)return n-r<=sa;const u=o.end(o.length-1);return u-r<=sa&&n-u<=sa}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,this.mediaSource.readyState!=="open"?this.trigger("error"):this.sourceUpdater_.endOfStream("network");return}e.playlistErrors_++;const n=this.mainPlaylistLoader_.main.playlists,r=n.filter(r0),o=r.length===1&&r[0]===e;if(n.length===1&&i!==1/0)return Ae.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(o);if(o){if(this.main().contentSteering){const x=this.pathwayAttribute_(e),_=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(x),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(x)},_);return}let y=!1;n.forEach(x=>{if(x===e)return;const _=x.excludeUntil;typeof _<"u"&&_!==1/0&&(y=!0,delete x.excludeUntil)}),y&&(Ae.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let u;e.playlistErrors_>this.maxPlaylistRetries?u=1/0:u=Date.now()+i*1e3,e.excludeUntil=u,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const c=this.selectPlaylist();if(!c){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}const d=t.internal?this.logger_:Ae.log.warn,f=t.message?" "+t.message:"";d(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${f} Switching to playlist ${c.id}.`),c.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),c.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const p=c.targetDuration/2*1e3||5*1e3,g=typeof c.lastRequest=="number"&&Date.now()-c.lastRequest<=p;return this.switchMedia_(c,"exclude",o||g)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const i=[],n=e==="all";(n||e==="main")&&i.push(this.mainPlaylistLoader_);const r=[];(n||e==="audio")&&r.push("AUDIO"),(n||e==="subtitle")&&(r.push("CLOSED-CAPTIONS"),r.push("SUBTITLES")),r.forEach(o=>{const u=this.mediaTypes_[o]&&this.mediaTypes_[o].activePlaylistLoader;u&&i.push(u)}),["main","audio","subtitle"].forEach(o=>{const u=this[`${o}SegmentLoader_`];u&&(e===o||e==="all")&&i.push(u)}),i.forEach(o=>t.forEach(u=>{typeof o[u]=="function"&&o[u]()}))}setCurrentTime(e){const t=Xu(this.tech_.buffered(),e);if(!(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media())||!this.mainPlaylistLoader_.media().segments)return 0;if(t&&t.length)return e;this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Mo.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){const i=e.media();if(!i)return null;const n=this.syncController_.getMediaSequenceSync(t);if(n&&n.isReliable){const u=n.start,c=n.end;if(!isFinite(u)||!isFinite(c))return null;const d=Mo.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),f=Math.max(u,c-d);return Vs([[u,f]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(r===null)return null;const o=Mo.Playlist.seekable(i,r,Mo.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return o.length?o:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),n=e.end(0),r=t.start(0),o=t.end(0);return r>n||i>o?e:Vs([[Math.max(i,r),Math.min(n,o)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const i=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_||i&&i.length&&this.seekable_.length&&i.start(0)===this.seekable_.start(0)&&i.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${rk(this.seekable_)}]`);const n={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:n}),this.tech_.trigger("seekablechanged")}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),this.mediaSource.readyState!=="open"){this.updateDuration_=this.updateDuration.bind(this,e),this.mediaSource.addEventListener("sourceopen",this.updateDuration_);return}if(e){const n=this.seekable();if(!n.length)return;(isNaN(this.mediaSource.duration)||this.mediaSource.duration0&&(i=Math.max(i,t.end(t.length-1))),this.mediaSource.duration!==i&&this.sourceUpdater_.setDuration(i)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{const t=this.mediaTypes_[e].groups;for(const i in t)t[i].forEach(n=>{n.playlistLoader&&n.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),i=e?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return!(!t||!i)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const i=rh(this.main(),t),n={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=i.video||e.main.videoCodec||jM),e.main.isMuxed&&(n.video+=`,${i.audio||e.main.audioCodec||KS}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(n.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||KS,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!n.audio&&!n.video){this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}const o=(d,f)=>d?eh(f,this.usingManagedMediaSource_):Ly(f),u={};let c;if(["video","audio"].forEach(function(d){if(n.hasOwnProperty(d)&&!o(e[d].isFmp4,n[d])){const f=e[d].isFmp4?"browser":"muxer";u[f]=u[f]||[],u[f].push(n[d]),d==="audio"&&(c=f)}}),r&&c&&t.attributes.AUDIO){const d=t.attributes.AUDIO;this.main().playlists.forEach(f=>{(f.attributes&&f.attributes.AUDIO)===d&&f!==t&&(f.excludeUntil=1/0)}),this.logger_(`excluding audio group ${d} as ${c} does not support codec(s): "${n.audio}"`)}if(Object.keys(u).length){const d=Object.keys(u).reduce((f,p)=>(f&&(f+=", "),f+=`${p} does not support codec(s): "${u[p].join(",")}"`,f),"")+".";this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:d},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const d=[];if(["video","audio"].forEach(f=>{const p=(Zr(this.sourceUpdater_.codecs[f]||"")[0]||{}).type,g=(Zr(n[f]||"")[0]||{}).type;p&&g&&p.toLowerCase()!==g.toLowerCase()&&d.push(`"${this.sourceUpdater_.codecs[f]}" -> "${n[f]}"`)}),d.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${d.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0});return}}return n}tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!=="open"||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach(i=>{const n=e[i];if(t.indexOf(n.id)!==-1)return;t.push(n.id);const r=rh(this.main,n),o=[];r.audio&&!Ly(r.audio)&&!eh(r.audio,this.usingManagedMediaSource_)&&o.push(`audio codec ${r.audio}`),r.video&&!Ly(r.video)&&!eh(r.video,this.usingManagedMediaSource_)&&o.push(`video codec ${r.video}`),r.text&&r.text==="stpp.ttml.im1t"&&o.push(`text codec ${r.text}`),o.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${o.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=ph(Zr(e)),r=jE(n),o=n.video&&Zr(n.video)[0]||null,u=n.audio&&Zr(n.audio)[0]||null;Object.keys(i).forEach(c=>{const d=i[c];if(t.indexOf(d.id)!==-1||d.excludeUntil===1/0)return;t.push(d.id);const f=[],p=rh(this.mainPlaylistLoader_.main,d),g=jE(p);if(!(!p.audio&&!p.video)){if(g!==r&&f.push(`codec count "${g}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const y=p.video&&Zr(p.video)[0]||null,x=p.audio&&Zr(p.audio)[0]||null;y&&o&&y.type.toLowerCase()!==o.type.toLowerCase()&&f.push(`video codec "${y.type}" !== "${o.type}"`),x&&u&&x.type.toLowerCase()!==u.type.toLowerCase()&&f.push(`audio codec "${x.type}" !== "${u.type}"`)}f.length&&(d.excludeUntil=1/0,this.logger_(`excluding ${d.id}: ${f.join(" && ")}`))}})}updateAdCues_(e){let t=0;const i=this.seekable();i.length&&(t=i.start(0)),DF(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=$s.GOAL_BUFFER_LENGTH,i=$s.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,$s.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=$s.BUFFER_LOW_WATER_LINE,i=$s.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,$s.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,$s.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:n)}bufferHighWaterLine(){return $s.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){YE(this.inbandTextTracks_,"com.apple.streaming",this.tech_),lF({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();YE(this.inbandTextTracks_,e,this.tech_),rF({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:n,videoDuration:i})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(t=>{this.contentSteeringController_.on(t,i=>{this.trigger(Es({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),o=[];for(const u of t.playlists){const c=u.attributes.serviceLocation;if(c&&(o.push(c),!r.has(c)))return!0}return!!(!o.length&&r.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const i=this.main().playlists,n=new Set;let r=!1;Object.keys(i).forEach(o=>{const u=i[o],c=this.pathwayAttribute_(u),d=c&&e!==c;u.excludeUntil===1/0&&u.lastExcludeReason_==="content-steering"&&!d&&(delete u.excludeUntil,delete u.lastExcludeReason_,r=!0);const p=!u.excludeUntil&&u.excludeUntil!==1/0;!n.has(u.id)&&d&&p&&(n.add(u.id),u.excludeUntil=1/0,u.lastExcludeReason_="content-steering",this.logger_(`excluding ${u.id} for ${u.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_==="DASH"&&Object.keys(this.mediaTypes_).forEach(o=>{const u=this.mediaTypes_[o];if(u.activePlaylistLoader){const c=u.activePlaylistLoader.media_;c&&c.attributes.serviceLocation!==e&&(r=!0)}}),r&&this.changeSegmentPathway_()}handlePathwayClones_(){const t=this.main().playlists,i=this.contentSteeringController_.currentPathwayClones,n=this.contentSteeringController_.nextPathwayClones;if(i&&i.size||n&&n.size){for(const[o,u]of i.entries())n.get(o)||(this.mainPlaylistLoader_.updateOrDeleteClone(u),this.contentSteeringController_.excludePathway(o));for(const[o,u]of n.entries()){const c=i.get(o);if(!c){t.filter(f=>f.attributes["PATHWAY-ID"]===u["BASE-ID"]).forEach(f=>{this.mainPlaylistLoader_.addClonePathway(u,f)}),this.contentSteeringController_.addAvailablePathway(o);continue}this.equalPathwayClones_(c,u)||(this.mainPlaylistLoader_.updateOrDeleteClone(u,!0),this.contentSteeringController_.addAvailablePathway(o))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...n])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const i=e["URI-REPLACEMENT"].PARAMS,n=t["URI-REPLACEMENT"].PARAMS;for(const r in i)if(i[r]!==n[r])return!1;for(const r in n)if(i[r]!==n[r])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_==="DASH"&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(i=>{const n=this.mainPlaylistLoader_.getKeyIdSet(i);!n||!n.size||n.forEach(r=>{const o="usable",u=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===o,c=i.lastExcludeReason_===t&&i.excludeUntil===1/0;u?u&&c&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${r} is ${o}`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${r} doesn't exist in the keyStatusMap or is not ${o}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(i=>{const n=i&&i.attributes&&i.attributes.RESOLUTION&&i.attributes.RESOLUTION.height<720,r=i.excludeUntil===1/0&&i.lastExcludeReason_===t;n&&r&&(delete i.excludeUntil,Ae.log.warn(`enabling non-HD playlist ${i.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){const r=(typeof e=="string"?e:wF(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${r} added to the keyStatusMap`),this.keyStatusMap_.set(r,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}const JF=(s,e,t)=>i=>{const n=s.main.playlists[e],r=Sb(n),o=r0(n);if(typeof i>"u")return o;i?delete n.disabled:n.disabled=!0;const u={renditionInfo:{id:e,bandwidth:n.attributes.BANDWIDTH,resolution:n.attributes.RESOLUTION,codecs:n.attributes.CODECS},cause:"fast-quality"};return i!==o&&!r&&(i?(t(n),s.trigger({type:"renditionenabled",metadata:u})):s.trigger({type:"renditiondisabled",metadata:u})),i};class e8{constructor(e,t,i){const{playlistController_:n}=e,r=n.fastQualityChange_.bind(n);if(t.attributes){const o=t.attributes.RESOLUTION;this.width=o&&o.width,this.height=o&&o.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=rh(n.main(),t),this.playlist=t,this.id=i,this.enabled=JF(e.playlists,t.id,r)}}const t8=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=Ih(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!Sb(i)).map((i,n)=>new e8(s,i,i.id)):[]}},r2=["seeking","seeked","pause","playing","error"];class i8 extends Ae.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=pr("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),o=this.playlistController_,u=["main","subtitle","audio"],c={};u.forEach(f=>{c[f]={reset:()=>this.resetSegmentDownloads_(f),updateend:()=>this.checkSegmentDownloads_(f)},o[`${f}SegmentLoader_`].on("appendsdone",c[f].updateend),o[`${f}SegmentLoader_`].on("playlistupdate",c[f].reset),this.tech_.on(["seeked","seeking"],c[f].reset)});const d=f=>{["main","audio"].forEach(p=>{o[`${p}SegmentLoader_`][f]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),d("off"))},this.clearSeekingAppendCheck_=()=>d("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),d("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",n),this.tech_.on(r2,r),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",n),this.tech_.off(r2,r),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),u.forEach(f=>{o[`${f}SegmentLoader_`].off("appendsdone",c[f].updateend),o[`${f}SegmentLoader_`].off("playlistupdate",c[f].reset),this.tech_.off(["seeked","seeking"],c[f].reset)}),this.checkCurrentTimeTimeout_&&ue.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&ue.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=ue.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,i=t[`${e}SegmentLoader_`],n=i.buffered_(),r=$4(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,r){const o={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:o}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:Fl(n)}),!(this[`${e}StalledDownloads_`]<10)&&(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),e!=="subtitle"&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+sa>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(Vs([this.lastRecordedTime,e]));const i={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:i}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const t=this.seekable(),i=this.tech_.currentTime(),n=this.afterSeekableWindow_(t,i,this.media(),this.allowSeeksWithinUnsafeLiveWindow);let r;if(n&&(r=t.end(t.length-1)),this.beforeSeekableWindow_(t,i)){const x=t.start(0);r=x+(x===t.end(0)?0:sa)}if(typeof r<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${rk(t)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;const o=this.playlistController_.sourceUpdater_,u=this.tech_.buffered(),c=o.audioBuffer?o.audioBuffered():null,d=o.videoBuffer?o.videoBuffered():null,f=this.media(),p=f.partTargetDuration?f.partTargetDuration:(f.targetDuration-ia)*2,g=[c,d];for(let x=0;x ${i.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const u=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${u}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(u),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const i=this.tech_.vhs.playlistController_.sourceUpdater_,n=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const o=cm(n,t);return o.length>0?(this.logger_(`Stopped at ${t} and seeking to ${o.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,i,n=!1){if(!e.length)return!1;let r=e.end(e.length-1)+sa;const o=!i.endList,u=typeof i.partTargetDuration=="number";return o&&(u||n)&&(r=e.end(e.length-1)+i.targetDuration*3),t>r}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t2)return{start:r,end:o}}return null}}const s8={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},Xk=function(s,e){let t=0,i=0;const n=Di(s8,e);s.ready(()=>{s.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const r=function(){i&&s.currentTime(i)},o=function(f){f!=null&&(i=s.duration()!==1/0&&s.currentTime()||0,s.one("loadedmetadata",r),s.src(f),s.trigger({type:"usage",name:"vhs-error-reload"}),s.play())},u=function(){if(Date.now()-t{Object.defineProperty(hs,s,{get(){return Ae.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),$s[s]},set(e){if(Ae.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){Ae.log.warn(`value of Vhs.${s} must be greater than or equal to 0`);return}$s[s]=e}})});const Zk="videojs-vhs",Jk=function(s,e){const t=e.media();let i=-1;for(let n=0;n{s.addQualityLevel(t)}),Jk(s,e.playlists)};hs.canPlaySource=function(){return Ae.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const c8=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=ph(Zr(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const n=pc(i.video),r=pc(i.audio),o={};for(const u in s)o[u]={},r&&(o[u].audioContentType=r),n&&(o[u].videoContentType=n),e.contentProtection&&e.contentProtection[u]&&e.contentProtection[u].pssh&&(o[u].pssh=e.contentProtection[u].pssh),typeof s[u]=="string"&&(o[u].url=s[u]);return Di(s,o)},d8=(s,e)=>s.reduce((t,i)=>{if(!i.contentProtection)return t;const n=e.reduce((r,o)=>{const u=i.contentProtection[o];return u&&u.pssh&&(r[o]={pssh:u.pssh}),r},{});return Object.keys(n).length&&t.push(n),t},[]),h8=({player:s,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!s.eme.initializeMediaKeys)return Promise.resolve();const n=t?i.concat([t]):i,r=d8(n,Object.keys(e)),o=[],u=[];return r.forEach(c=>{u.push(new Promise((d,f)=>{s.tech_.one("keysessioncreated",d)})),o.push(new Promise((d,f)=>{s.eme.initializeMediaKeys({keySystems:c},p=>{if(p){f(p);return}d()})}))}),Promise.race([Promise.all(o),Promise.race(u)])},f8=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const n=c8(e,t,i);return n?(s.currentSource().keySystems=n,n&&!s.eme?(Ae.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},eD=()=>{if(!ue.localStorage)return null;const s=ue.localStorage.getItem(Zk);if(!s)return null;try{return JSON.parse(s)}catch{return null}},m8=s=>{if(!ue.localStorage)return!1;let e=eD();e=e?Di(e,s):s;try{ue.localStorage.setItem(Zk,JSON.stringify(e))}catch{return!1}return e},p8=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,tD=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},iD=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},sD=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},nD=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};hs.supportsNativeHls=(function(){if(!st||!st.createElement)return!1;const s=st.createElement("video");return Ae.getTech("Html5").isSupported()?["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(t){return/maybe|probably/i.test(s.canPlayType(t))}):!1})();hs.supportsNativeDash=(function(){return!st||!st.createElement||!Ae.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(st.createElement("video").canPlayType("application/dash+xml"))})();hs.supportsTypeNatively=s=>s==="hls"?hs.supportsNativeHls:s==="dash"?hs.supportsNativeDash:!1;hs.isSupported=function(){return Ae.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};hs.xhr.onRequest=function(s){tD(hs.xhr,s)};hs.xhr.onResponse=function(s){iD(hs.xhr,s)};hs.xhr.offRequest=function(s){sD(hs.xhr,s)};hs.xhr.offResponse=function(s){nD(hs.xhr,s)};const g8=Ae.getComponent("Component");class rD extends g8{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=pr("VhsHandler"),t.options_&&t.options_.playerId){const n=Ae.getPlayer(t.options_.playerId);this.player_=n}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(st,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const r=st.fullscreenElement||st.webkitFullscreenElement||st.mozFullScreenElement||st.msFullscreenElement;r&&r.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,"seeking",function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,"error",function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,"play",this.play)}setOptions_(e={}){if(this.options_=Di(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions!==!1,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.usePlayerObjectFit=this.options_.usePlayerObjectFit||!1,this.options_.useBandwidthFromLocalStorage=typeof this.source_.useBandwidthFromLocalStorage<"u"?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=typeof this.options_.useNetworkInformationApi<"u"?this.options_.useNetworkInformationApi:!0,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=this.options_.llhls!==!1,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,typeof this.options_.playlistExclusionDuration!="number"&&(this.options_.playlistExclusionDuration=60),typeof this.options_.bandwidth!="number"&&this.options_.useBandwidthFromLocalStorage){const i=eD();i&&i.bandwidth&&(this.options_.bandwidth=i.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),i&&i.throughput&&(this.options_.throughput=i.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}typeof this.options_.bandwidth!="number"&&(this.options_.bandwidth=$s.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===$s.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","usePlayerObjectFit","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(i=>{typeof this.source_[i]<"u"&&(this.options_[i]=this.source_[i])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio,this.usePlayerObjectFit=this.options_.usePlayerObjectFit;const t=this.options_.customPixelRatio;typeof t=="number"&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=p8(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=hs,this.options_.sourceType=AA(t),this.options_.seekTo=r=>{this.tech_.setCurrentTime(r)},this.options_.player_=this.player_,this.playlistController_=new ZF(this.options_);const i=Di({liveRangeSafeTimeDelta:sa},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new i8(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const r=Ae.players[this.tech_.options_.playerId];let o=this.playlistController_.error;typeof o=="object"&&!o.code?o.code=3:typeof o=="string"&&(o={message:o,code:3}),r.error(o)});const n=this.options_.bufferBasedABR?hs.movingAverageBandwidthSelector(.55):hs.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=hs.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(r){this.playlistController_.selectPlaylist=r.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(r){this.playlistController_.mainSegmentLoader_.throughput.rate=r,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let r=this.playlistController_.mainSegmentLoader_.bandwidth;const o=ue.navigator.connection||ue.navigator.mozConnection||ue.navigator.webkitConnection,u=1e7;if(this.options_.useNetworkInformationApi&&o){const c=o.downlink*1e3*1e3;c>=u&&r>=u?r=Math.max(r,c):r=c}return r},set(r){this.playlistController_.mainSegmentLoader_.bandwidth=r,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const r=1/(this.bandwidth||1);let o;return this.throughput>0?o=1/this.throughput:o=0,Math.floor(1/(r+o))},set(){Ae.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>Fl(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>Fl(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&m8({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{t8(this)}),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",()=>{this.setupEme_()}),this.on(this.playlistController_,"progress",function(){this.tech_.trigger("progress")}),this.on(this.playlistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=ue.URL.createObjectURL(this.playlistController_.mediaSource),(Ae.browser.IS_ANY_SAFARI||Ae.browser.IS_IOS)&&this.options_.overrideNative&&this.options_.sourceType==="hls"&&typeof this.tech_.addSourceElement=="function"?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),h8({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(t=>{this.logger_("error while creating EME key session",t),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=f8({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on("keystatuschange",i=>{this.playlistController_.updatePlaylistByKeyStatus(i.keyId,i.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){const e=Ae.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{u8(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{Jk(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":Qk,"mux.js":r8,"mpd-parser":a8,"m3u8-parser":o8,"aes-decrypter":l8}}version(){return this.constructor.version()}canChangeType(){return qk.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&ue.URL.revokeObjectURL&&(ue.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return bB({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return Dk({programTime:e,playlist:this.playlistController_.media(),retryCount:n,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{tD(this.xhr,e)},this.xhr.onResponse=e=>{iD(this.xhr,e)},this.xhr.offRequest=e=>{sD(this.xhr,e)},this.xhr.offResponse=e=>{nD(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){const e=["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"],t=["gapjumped","playedrangeschanged"];e.forEach(i=>{this.playlistController_.on(i,n=>{this.player_.trigger(Es({},n))})}),t.forEach(i=>{this.playbackWatcher_.on(i,n=>{this.player_.trigger(Es({},n))})})}}const pp={name:"videojs-http-streaming",VERSION:Qk,canHandleSource(s,e={}){const t=Di(Ae.options,e);return!t.vhs.experimentalUseMMS&&!eh("avc1.4d400d,mp4a.40.2",!1)?!1:pp.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=Di(Ae.options,t);return e.vhs=new rD(s,e,i),e.vhs.xhr=Ek(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=AA(s);if(!t)return"";const i=pp.getOverrideNative(e);return!hs.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(s={}){const{vhs:e={}}=s,t=!(Ae.browser.IS_ANY_SAFARI||Ae.browser.IS_IOS),{overrideNative:i=t}=e;return i}},y8=()=>eh("avc1.4d400d,mp4a.40.2",!0);y8()&&Ae.getTech("Html5").registerSourceHandler(pp,0);Ae.VhsHandler=rD;Ae.VhsSourceHandler=pp;Ae.Vhs=hs;Ae.use||Ae.registerComponent("Vhs",hs);Ae.options.vhs=Ae.options.vhs||{};(!Ae.getPlugin||!Ae.getPlugin("reloadSourceOnError"))&&Ae.registerPlugin("reloadSourceOnError",n8);const Ku=s=>(s||"").replaceAll("\\","/").split("/").pop()||"",aD=s=>s.startsWith("HOT ")?s.slice(4):s;function a2(s){if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`}function v8(s){if(typeof s!="number"||!Number.isFinite(s)||s<=0)return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=100?0:t>=10?1:2;return`${t.toFixed(n)} ${e[i]}`}const x8=s=>{const e=Ku(s||""),t=aD(e);if(!t)return"—";const i=t.replace(/\.[^.]+$/,""),n=i.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(n?.[1])return n[1];const r=i.lastIndexOf("_");return r>0?i.slice(0,r):i},b8=s=>{const e=s,t=e.sizeBytes??e.fileSizeBytes??e.bytes??e.size??null;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null};function qr(...s){return s.filter(Boolean).join(" ")}function T8(s){const[e,t]=k.useState(!1);return k.useEffect(()=>{if(typeof window>"u")return;const i=window.matchMedia(s),n=()=>t(i.matches);return n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}},[s]),e}function _8({job:s,expanded:e,onClose:t,onToggleExpand:i,modelKey:n,isHot:r=!1,isFavorite:o=!1,isLiked:u=!1,isWatching:c=!1,onKeep:d,onDelete:f,onToggleHot:p,onToggleFavorite:g,onToggleLike:y,onToggleWatch:x,onStopJob:_,startMuted:w=V5}){const D=k.useMemo(()=>Ku(s.output?.trim()||"")||s.id,[s.output,s.id]),I=k.useMemo(()=>Ku(s.output?.trim()||""),[s.output]),L=I.startsWith("HOT "),B=k.useMemo(()=>{const ve=(n||"").trim();return ve||x8(s.output)},[n,s.output]),j=k.useMemo(()=>aD(I),[I]),V=k.useMemo(()=>{const ve=Date.parse(String(s.startedAt||"")),Ce=Date.parse(String(s.endedAt||""));if(Number.isFinite(ve)&&Number.isFinite(Ce)&&Ce>ve)return a2(Ce-ve);const he=s.durationSeconds;return typeof he=="number"&&Number.isFinite(he)&&he>0?a2(he*1e3):"—"},[s]),M=k.useMemo(()=>v8(b8(s)),[s]);k.useEffect(()=>{const ve=Ce=>Ce.key==="Escape"&&t();return window.addEventListener("keydown",ve),()=>window.removeEventListener("keydown",ve)},[t]);const z=k.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s.id)}&file=index_hq.m3u8`,[s.id]),[O,N]=k.useState(s.status!=="running");k.useEffect(()=>{if(s.status!=="running"){N(!0);return}let ve=!0;const Ce=new AbortController;return N(!1),(async()=>{for(let ye=0;ye<100&&ve&&!Ce.signal.aborted;ye++){try{if((await fetch(z,{method:"HEAD",cache:"no-store",signal:Ce.signal})).status===200){ve&&N(!0);return}}catch{}await new Promise(me=>setTimeout(me,600))}})(),()=>{ve=!1,Ce.abort()}},[s.status,z]);const q=k.useMemo(()=>{if(s.status==="running")return O?{src:z,type:"application/x-mpegURL"}:{src:"",type:"application/x-mpegURL"};const ve=Ku(s.output?.trim()||"");return ve?{src:`/api/record/video?file=${encodeURIComponent(ve)}`,type:"video/mp4"}:{src:`/api/record/video?id=${encodeURIComponent(s.id)}`,type:"video/mp4"}},[s.status,s.output,s.id,O,z]),Q=k.useRef(null),Y=k.useRef(null),re=k.useRef(null),[Z,H]=k.useState(!1),[K,ie]=k.useState(56);k.useEffect(()=>{if(!Z)return;const ve=Y.current;if(!ve||ve.isDisposed?.())return;const Ce=ve.el();if(!Ce)return;const he=Ce.querySelector(".vjs-control-bar");if(!he)return;const ye=()=>{const Qe=Math.round(he.getBoundingClientRect().height||0);Qe>0&&ie(Qe)};ye();let me=null;return typeof ResizeObserver<"u"&&(me=new ResizeObserver(ye),me.observe(he)),window.addEventListener("resize",ye),()=>{window.removeEventListener("resize",ye),me?.disconnect()}},[Z,e]),k.useEffect(()=>H(!0),[]),k.useLayoutEffect(()=>{if(!Z||!Q.current||Y.current)return;const ve=document.createElement("video");ve.className="video-js vjs-big-play-centered w-full h-full",ve.setAttribute("playsinline","true"),Q.current.appendChild(ve),re.current=ve;const Ce=Ae(ve,{autoplay:!0,muted:w,controls:!0,preload:"metadata",playsinline:!0,responsive:!0,fluid:!1,fill:!0,controlBar:{skipButtons:{backward:10,forward:10},children:["playToggle","progressControl","currentTimeDisplay","timeDivider","durationDisplay","volumePanel","playbackRateMenuButton","fullscreenToggle"]},playbackRates:[.5,1,1.25,1.5,2]});return Y.current=Ce,()=>{try{Y.current&&(Y.current.dispose(),Y.current=null)}finally{re.current&&(re.current.remove(),re.current=null)}}},[Z]),k.useEffect(()=>{if(!Z)return;const ve=Y.current;if(!ve||ve.isDisposed?.())return;const Ce=ve.currentTime()||0;if(ve.muted(w),!q.src)return;ve.src({src:q.src,type:q.type});const he=()=>{const ye=ve.play?.();ye&&typeof ye.catch=="function"&&ye.catch(()=>{})};ve.one("loadedmetadata",()=>{ve.isDisposed?.()||(Ce>0&&q.type!=="application/x-mpegURL"&&ve.currentTime(Ce),he())}),he()},[Z,q.src,q.type,w]),k.useEffect(()=>{if(!Z)return;const ve=Y.current;if(!ve||ve.isDisposed?.())return;const Ce=()=>{s.status==="running"&&N(!1)};return ve.on("error",Ce),()=>{try{ve.off("error",Ce)}catch{}}},[Z,s.status]),k.useEffect(()=>{const ve=Y.current;!ve||ve.isDisposed?.()||queueMicrotask(()=>ve.trigger("resize"))},[e]);const te=k.useCallback(()=>{const ve=Y.current;if(!(!ve||ve.isDisposed?.())){try{ve.pause(),ve.reset?.()}catch{}try{ve.src({src:"",type:"video/mp4"}),ve.load?.()}catch{}}},[]);k.useEffect(()=>{const ve=Ce=>{const ye=(Ce.detail?.file??"").trim();if(!ye)return;const me=Ku(s.output?.trim()||"");me&&me===ye&&te()};return window.addEventListener("player:release",ve),()=>window.removeEventListener("player:release",ve)},[s.output,te]),k.useEffect(()=>{const ve=Ce=>{const ye=(Ce.detail?.file??"").trim();if(!ye)return;const me=Ku(s.output?.trim()||"");me&&me===ye&&(te(),t())};return window.addEventListener("player:close",ve),()=>window.removeEventListener("player:close",ve)},[s.output,te,t]);const ne=!e,$=T8("(min-width: 640px)"),ee=ne&&$,le="player_window_v1",be=420,fe=280,_e=12,Me=320,et=200,Ge=()=>{if(typeof window>"u")return{w:0,h:0};const ve=window.visualViewport;if(ve&&Number.isFinite(ve.width)&&Number.isFinite(ve.height))return{w:Math.floor(ve.width),h:Math.floor(ve.height)};const Ce=document.documentElement;return{w:Ce?.clientWidth||window.innerWidth,h:Ce?.clientHeight||window.innerHeight}},lt=k.useCallback((ve,Ce)=>{if(typeof window>"u")return ve;const{w:he,h:ye}=Ge(),me=he-_e*2,Qe=ye-_e*2;let Ie=ve.w,Ye=ve.h;Ce&&Number.isFinite(Ce)&&Ce>.1?(Ie=Math.max(Me,Ie),Ye=Ie/Ce,Yeme&&(Ie=me,Ye=Ie/Ce),Ye>Qe&&(Ye=Qe,Ie=Ye*Ce)):(Ie=Math.max(Me,Math.min(Ie,me)),Ye=Math.max(et,Math.min(Ye,Qe)));let Ct=Math.max(_e,Math.min(ve.x,he-Ie-_e)),Je=Math.max(_e,Math.min(ve.y,ye-Ye-_e));return{x:Ct,y:Je,w:Ie,h:Ye}},[]),At=k.useCallback(()=>{if(typeof window>"u")return{x:_e,y:_e,w:be,h:fe};try{const Ie=window.localStorage.getItem(le);if(Ie){const Ye=JSON.parse(Ie);if(typeof Ye.x=="number"&&typeof Ye.y=="number"&&typeof Ye.w=="number"&&typeof Ye.h=="number"){const Ct=Ye.w,Je=Ye.h,Rt=Ye.x,Mt=Ye.y;return lt({x:Rt,y:Mt,w:Ct,h:Je},Ct/Je)}}}catch{}const{w:ve,h:Ce}=Ge(),he=be,ye=fe,me=Math.max(_e,ve-he-_e),Qe=Math.max(_e,Ce-ye-_e);return lt({x:me,y:Qe,w:he,h:ye},he/ye)},[lt]),[mt,Vt]=k.useState(()=>At()),Re=ee&&mt.w<380,dt=k.useCallback(ve=>{if(!(typeof window>"u"))try{window.localStorage.setItem(le,JSON.stringify(ve))}catch{}},[]),He=k.useRef(mt);k.useEffect(()=>{He.current=mt},[mt]),k.useEffect(()=>{ee&&Vt(At())},[ee,At]),k.useEffect(()=>{if(!ee)return;const ve=()=>Vt(Ce=>lt(Ce,Ce.w/Ce.h));return window.addEventListener("resize",ve),()=>window.removeEventListener("resize",ve)},[ee,lt]),k.useEffect(()=>{const ve=Y.current;if(!(!ve||ve.isDisposed?.()))return Tt.current!=null&&cancelAnimationFrame(Tt.current),Tt.current=requestAnimationFrame(()=>{Tt.current=null;try{ve.trigger("resize")}catch{}}),()=>{Tt.current!=null&&(cancelAnimationFrame(Tt.current),Tt.current=null)}},[ee,mt.w,mt.h]);const[tt,nt]=k.useState(!1),[ot,Ke]=k.useState(!1),pt=k.useRef(null),yt=k.useRef(null),Gt=k.useRef(null),Ut=k.useCallback(ve=>{const{w:Ce,h:he}=Ge(),ye=_e,me=Ce-ve.w-_e,Qe=he-ve.h-_e,Ye=ve.x+ve.w/2{const Ce=Gt.current;if(!Ce)return;const he=ve.clientX-Ce.sx,ye=ve.clientY-Ce.sy,me=Ce.start,Qe=lt({x:me.x+he,y:me.y+ye,w:me.w,h:me.h});yt.current={x:Qe.x,y:Qe.y},pt.current==null&&(pt.current=requestAnimationFrame(()=>{pt.current=null;const Ie=yt.current;Ie&&Vt(Ye=>({...Ye,x:Ie.x,y:Ie.y}))}))},[lt]),Zt=k.useCallback(()=>{Gt.current&&(Ke(!1),pt.current!=null&&(cancelAnimationFrame(pt.current),pt.current=null),Gt.current=null,window.removeEventListener("pointermove",ai),window.removeEventListener("pointerup",Zt),Vt(ve=>{const Ce=Ut(lt(ve));return queueMicrotask(()=>dt(Ce)),Ce}))},[ai,Ut,lt,dt]),$e=k.useCallback(ve=>{if(!ee||tt||ve.button!==0)return;ve.preventDefault(),ve.stopPropagation();const Ce=He.current;Gt.current={sx:ve.clientX,sy:ve.clientY,start:Ce},Ke(!0),window.addEventListener("pointermove",ai),window.addEventListener("pointerup",Zt)},[ee,tt,ai,Zt]),ct=k.useRef(null),it=k.useRef(null),Tt=k.useRef(null),Wt=k.useRef(null),Xe=k.useCallback(ve=>{const Ce=Wt.current;if(!Ce)return;const he=ve.clientX-Ce.sx,ye=ve.clientY-Ce.sy,me=Ce.ratio,Qe=Ce.dir.includes("w"),Ie=Ce.dir.includes("e"),Ye=Ce.dir.includes("n"),Ct=Ce.dir.includes("s");let Je=Ce.start.w,Rt=Ce.start.h,Mt=Ce.start.x,Kt=Ce.start.y;const{w:rt,h:at}=Ge(),ft=24,wt=Ce.start.x+Ce.start.w,It=Ce.start.y+Ce.start.h,ti=Math.abs(rt-_e-wt)<=ft,Vi=Math.abs(at-_e-It)<=ft,Js=Wi=>{Wi=Math.max(Me,Wi);let ts=Wi/me;return ts{Wi=Math.max(et,Wi);let ts=Wi*me;return ts=Math.abs(ye)){const ts=Ie?Ce.start.w+he:Ce.start.w-he,{newW:Xi,newH:Ya}=Js(ts);Je=Xi,Rt=Ya}else{const ts=Ct?Ce.start.h+ye:Ce.start.h-ye,{newW:Xi,newH:Ya}=ms(ts);Je=Xi,Rt=Ya}Qe&&(Mt=Ce.start.x+(Ce.start.w-Je)),Ye&&(Kt=Ce.start.y+(Ce.start.h-Rt))}else if(Ie||Qe){const Wi=Ie?Ce.start.w+he:Ce.start.w-he,{newW:ts,newH:Xi}=Js(Wi);Je=ts,Rt=Xi,Qe&&(Mt=Ce.start.x+(Ce.start.w-Je)),Kt=Vi?Ce.start.y+(Ce.start.h-Rt):Ce.start.y}else if(Ye||Ct){const Wi=Ct?Ce.start.h+ye:Ce.start.h-ye,{newW:ts,newH:Xi}=ms(Wi);Je=ts,Rt=Xi,Ye&&(Kt=Ce.start.y+(Ce.start.h-Rt)),ti?Mt=Ce.start.x+(Ce.start.w-Je):Mt=Ce.start.x}const Jo=lt({x:Mt,y:Kt,w:Je,h:Rt},me);it.current=Jo,ct.current==null&&(ct.current=requestAnimationFrame(()=>{ct.current=null;const Wi=it.current;Wi&&Vt(Wi)}))},[lt]),Ot=k.useCallback(()=>{Wt.current&&(nt(!1),ct.current!=null&&(cancelAnimationFrame(ct.current),ct.current=null),Wt.current=null,window.removeEventListener("pointermove",Xe),window.removeEventListener("pointerup",Ot),dt(He.current))},[Xe,dt]),kt=k.useCallback(ve=>Ce=>{if(!ee||Ce.button!==0)return;Ce.preventDefault(),Ce.stopPropagation();const he=He.current;Wt.current={dir:ve,sx:Ce.clientX,sy:Ce.clientY,start:he,ratio:he.w/he.h},nt(!0),window.addEventListener("pointermove",Xe),window.addEventListener("pointerup",Ot)},[ee,Xe,Ot]),[Xt,ni]=k.useState(!1),[hi,Ai]=k.useState(!1),[Nt,bt]=k.useState(!1),[xi,bi]=k.useState(!1),[G,W]=k.useState(!1);k.useEffect(()=>{if(!Z)return;const ve=Y.current;if(!ve||ve.isDisposed?.())return;const Ce=()=>{try{W(!!ve.paused?.())}catch{W(!1)}};return Ce(),ve.on("play",Ce),ve.on("pause",Ce),()=>{try{ve.off("play",Ce),ve.off("pause",Ce)}catch{}}},[Z]);const oe=k.useRef(null),Ee=k.useCallback(()=>{oe.current&&window.clearTimeout(oe.current),oe.current=null,bi(!1)},[]),Ze=k.useCallback(()=>{bi(!0),oe.current&&window.clearTimeout(oe.current),oe.current=window.setTimeout(()=>{bi(!1),oe.current=null},500)},[]);k.useEffect(()=>{e&&hi&&Ze()},[e,hi,Ze]),k.useEffect(()=>{const ve=Y.current;if(!ve||ve.isDisposed?.())return;let Ce=0;const he=performance.now(),ye=me=>{if(me-he<340){try{ve.trigger("resize")}catch{}Ce=requestAnimationFrame(ye)}};return Ce=requestAnimationFrame(ye),()=>cancelAnimationFrame(Ce)},[e]),k.useEffect(()=>()=>{oe.current&&window.clearTimeout(oe.current)},[]),k.useEffect(()=>{e||bi(!1)},[e]),k.useEffect(()=>{const ve=window.matchMedia?.("(hover: hover) and (pointer: fine)"),Ce=()=>Ai(!!ve?.matches);return Ce(),ve?.addEventListener?.("change",Ce),()=>ve?.removeEventListener?.("change",Ce)},[]),k.useEffect(()=>{ne||ni(!1)},[ne]);const Et=ne&&(hi?ee?Nt:Xt:!0),Jt=ee&&(Nt||ot||tt),[Li,Ji]=k.useState(!1);if(k.useEffect(()=>{s.status!=="running"&&Ji(!1)},[s.id,s.status]),!Z)return null;const Ci="inline-flex items-center justify-center rounded-md p-2 backdrop-blur transition bg-white/75 text-gray-900 ring-1 ring-black/10 hover:bg-white/90 dark:bg-black/40 dark:text-white dark:ring-white/10 dark:hover:bg-black/55 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500",Hi=String(s.phase??"").toLowerCase(),fi=s.status==="running",ns=Hi==="stopping"||Hi==="remuxing"||Hi==="moving",es=!_||!fi||ns||Li,Pi=v.jsx("div",{className:qr("flex items-center gap-1 min-w-0"),children:fi?v.jsxs(v.Fragment,{children:[v.jsx(_i,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:es,title:ns||Li?"Stoppe…":"Stop","aria-label":ns||Li?"Stoppe…":"Stop",onClick:async ve=>{if(ve.preventDefault(),ve.stopPropagation(),!es)try{Ji(!0),await _?.(s.id)}finally{Ji(!1)}},className:qr("shadow-none shrink-0",Re&&"px-2"),children:v.jsx("span",{className:"whitespace-nowrap",children:ns||Li?"Stoppe…":Re?"Stop":"Stoppen"})}),v.jsx(Ko,{job:s,variant:"overlay",collapseToMenu:!0,busy:ns||Li,isFavorite:o,isLiked:u,isWatching:c,onToggleWatch:x?ve=>x(ve):void 0,showHot:!1,showKeep:!1,showDelete:!1,onToggleFavorite:g?ve=>g(ve):void 0,onToggleLike:y?ve=>y(ve):void 0,order:["watch","favorite","like","details"],className:"gap-1 min-w-0 flex-1"})]}):v.jsx(Ko,{job:s,variant:"overlay",collapseToMenu:!0,isHot:r||L,isFavorite:o,isLiked:u,isWatching:c,onToggleWatch:x?ve=>x(ve):void 0,onToggleFavorite:g?ve=>g(ve):void 0,onToggleLike:y?ve=>y(ve):void 0,onToggleHot:p?async ve=>{te(),await new Promise(he=>setTimeout(he,150)),await p(ve),await new Promise(he=>setTimeout(he,0));const Ce=Y.current;if(Ce&&!Ce.isDisposed?.()){const he=Ce.play?.();he&&typeof he.catch=="function"&&he.catch(()=>{})}}:void 0,onKeep:d?async ve=>{te(),t(),await new Promise(Ce=>setTimeout(Ce,150)),await d(ve)}:void 0,onDelete:f?async ve=>{te(),t(),await new Promise(Ce=>setTimeout(Ce,150)),await f(ve)}:void 0,order:["watch","favorite","like","hot","details","keep","delete"],className:"gap-1 min-w-0 flex-1"})}),ei=e&&(!hi||xi||G)?K:0,Ht=`calc(${ei}px + env(safe-area-inset-bottom))`,Rs=`calc(${ei+8}px + env(safe-area-inset-bottom))`,Zs=e||ee,xe=v.jsx(za,{edgeToEdgeMobile:!0,noBodyPadding:!0,className:qr("relative flex flex-col shadow-2xl ring-1 ring-black/10 dark:ring-white/10","w-full",Zs&&"h-full",e?"rounded-2xl":ee?"rounded-lg":"rounded-none"),bodyClassName:"flex flex-col flex-1 min-h-0 p-0",children:v.jsxs("div",{className:qr("relative overflow-visible",e||ee?"flex-1 min-h-0":"aspect-video"),onMouseEnter:()=>{!ee||!hi||(bt(!0),ni(!0),Ze())},onMouseMove:()=>{!ee||!hi||Ze()},onMouseLeave:()=>{!ee||!hi||(bt(!1),ni(!1),Ee())},children:[ee?v.jsx("button",{type:"button","aria-label":"Player-Fenster verschieben",title:"Ziehen zum Verschieben (snapt an Kanten)",onPointerDown:$e,onClick:ve=>{ve.preventDefault(),ve.stopPropagation()},className:qr("absolute left-1/2 top-2 -translate-x-1/2","z-[80]","h-1.5 w-20 rounded-full","bg-white/90 shadow ring-1 ring-black/10","cursor-move active:cursor-grabbing","focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/70","transition-[opacity,transform] duration-150 ease-out",Jt?"opacity-100 translate-y-0 pointer-events-auto":"opacity-0 -translate-y-2 pointer-events-none")}):null,v.jsxs("div",{className:qr("relative w-full h-full",ne&&"vjs-mini",hi&&"vjs-controls-on-activity",hi&&xi&&"vjs-controls-active"),onMouseEnter:ne&&!ee?()=>{ni(!0),hi&&Ze()}:e&&hi?Ze:void 0,onMouseMove:hi?Ze:void 0,onMouseLeave:()=>{ne&&!ee&&ni(!1),hi&&!ee&&Ee()},onFocusCapture:e&&hi?()=>bi(!0):void 0,onBlurCapture:e&&hi?ve=>{const Ce=ve.relatedTarget;(!Ce||!ve.currentTarget.contains(Ce))&&Ee()}:void 0,children:[v.jsx("div",{ref:Q,className:"absolute inset-0"}),r||L?v.jsx("div",{className:"absolute left-2 top-2 z-20 pointer-events-none",children:v.jsx("span",{className:"shrink-0 rounded-md bg-amber-500/25 px-2 py-0.5 text-[11px] font-semibold text-white",children:"HOT"})}):null,v.jsxs("div",{className:qr("absolute inset-x-2 z-20 flex items-start justify-between gap-2","transition-[top] duration-150 ease-out",Jt?"top-5":"top-2"),children:[v.jsx("div",{className:"min-w-0 flex-1 pointer-events-auto overflow-visible",children:Pi}),v.jsxs("div",{className:"shrink-0 flex items-center gap-1 pointer-events-auto",children:[v.jsx("button",{type:"button",className:Ci,onClick:i,"aria-label":e?"Minimieren":"Maximieren",title:e?"Minimieren":"Maximieren",children:e?v.jsx(Y5,{className:"h-5 w-5"}):v.jsx(X5,{className:"h-5 w-5"})}),v.jsx("button",{type:"button",className:Ci,onClick:t,"aria-label":"Schließen",title:"Schließen",children:v.jsx($x,{className:"h-5 w-5"})})]})]}),v.jsx("div",{className:qr("player-ui pointer-events-none absolute inset-x-0 bg-gradient-to-t from-black/70 to-transparent","transition-all duration-200 ease-out",e?"h-28":Et?"bottom-7 h-24":"bottom-0 h-20"),style:e?{bottom:Ht}:void 0}),v.jsxs("div",{className:qr("player-ui pointer-events-none absolute inset-x-2 z-20 flex items-end justify-between gap-2","transition-all duration-200 ease-out",e?"":Et?"bottom-7":"bottom-2"),style:e?{bottom:Rs}:void 0,children:[v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"truncate text-sm font-semibold text-white",children:B}),v.jsx("div",{className:"truncate text-[11px] text-white/80",children:j||D})]}),v.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 text-[11px] text-white",children:[v.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-semibold",children:s.status}),v.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:V}),M!=="—"?v.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:M}):null]})]})]})]})}),{w:Ne,h:Oe}=Ge(),Fe={left:16,top:16,width:Math.max(0,Ne-32),height:Math.max(0,Oe-32)},ht=e?Fe:ee?{left:mt.x,top:mt.y,width:mt.w,height:mt.h}:void 0;return Sh.createPortal(v.jsx(v.Fragment,{children:e||ee?v.jsxs("div",{className:qr("fixed z-50",!tt&&!ot&&"transition-[left,top,width,height] duration-300 ease-[cubic-bezier(.2,.9,.2,1)]"),style:{...ht,willChange:tt?"left, top, width, height":void 0},children:[xe,ee?v.jsxs("div",{className:"pointer-events-none absolute inset-0",children:[v.jsx("div",{className:"pointer-events-auto absolute -left-1 top-2 bottom-2 w-3 cursor-ew-resize",onPointerDown:kt("w")}),v.jsx("div",{className:"pointer-events-auto absolute -right-1 top-2 bottom-2 w-3 cursor-ew-resize",onPointerDown:kt("e")}),v.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -top-1 h-3 cursor-ns-resize",onPointerDown:kt("n")}),v.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -bottom-1 h-3 cursor-ns-resize",onPointerDown:kt("s")}),v.jsx("div",{className:"pointer-events-auto absolute -left-1 -top-1 h-4 w-4 cursor-nwse-resize",onPointerDown:kt("nw")}),v.jsx("div",{className:"pointer-events-auto absolute -right-1 -top-1 h-4 w-4 cursor-nesw-resize",onPointerDown:kt("ne")}),v.jsx("div",{className:"pointer-events-auto absolute -left-1 -bottom-1 h-4 w-4 cursor-nesw-resize",onPointerDown:kt("sw")}),v.jsx("div",{className:"pointer-events-auto absolute -right-1 -bottom-1 h-4 w-4 cursor-nwse-resize",onPointerDown:kt("se")})]}):null]}):v.jsx("div",{className:"fixed z-50 left-0 right-0 bottom-0 w-full pb-[env(safe-area-inset-bottom)]",children:xe})}),document.body)}const gt=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},S8=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=E8},E8=Number.MAX_SAFE_INTEGER||9007199254740991;let Lt=(function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s})({}),we=(function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s})({}),U=(function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s})({});var di={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},_t={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Uu{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class w8{constructor(e,t,i,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Uu(e),this.fast_=new Uu(t),this.defaultTTFB_=n,this.ttfb_=new Uu(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Uu(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Uu(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Uu(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,n=e/1e3,r=i/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function A8(s,e,t){return(e=k8(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function $i(){return $i=Object.assign?Object.assign.bind():function(s){for(var e=1;e`):jo}function l2(s,e,t){return e[s]?e[s].bind(e):L8(s,t)}const fx=hx();function R8(s,e,t){const i=hx();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=l2(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return hx()}n.forEach(r=>{fx[r]=l2(r,s)})}else $i(fx,i);return i}const Mi=fx;function Xo(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function I8(s){return typeof self<"u"&&s===self.ManagedMediaSource}function oD(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(o=>i.indexOf(o)===-1)}function er(s,e=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(e){const f=d.indexOf("\0");return f!==-1?d.substring(0,f):d}return d.replace(/\0/g,"")}const t=s.length;let i,n,r,o="",u=0;for(;u>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:n=s[u++],o+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[u++],r=s[u++],o+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return o}function Xs(s){let e="";for(let t=0;t1||n===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!gt(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ss(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const n=t[e];n&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,n,r,o=!1){const{elementaryStreams:u}=this,c=u[e];if(!c){u[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:o};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,i),c.startDTS=Math.min(c.startDTS,n),c.endDTS=Math.max(c.endDTS,r)}}class M8 extends uD{constructor(e,t,i,n,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function cD(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||cD(t,e)}}function P8(s,e){const t=cD(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const c2=Math.pow(2,32)-1,B8=[].push,dD={video:1,audio:2,id3:3,text:4};function Ms(s){return String.fromCharCode.apply(null,s)}function hD(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function zt(s,e){const t=fD(s,e);return t<0?4294967296+t:t}function d2(s,e){let t=zt(s,e);return t*=Math.pow(2,32),t+=zt(s,e+4),t}function fD(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function F8(s){const e=s.byteLength;for(let t=0;t8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function ci(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n1?n+r:i;if(o===e[0])if(e.length===1)t.push(s.subarray(n+8,u));else{const c=ci(s.subarray(n+8,u),e.slice(1));c.length&&B8.apply(t,c)}n=u}return t}function U8(s){const e=[],t=s[0];let i=8;const n=zt(s,i);i+=4;let r=0,o=0;t===0?(r=zt(s,i),o=zt(s,i+4),i+=8):(r=d2(s,i),o=d2(s,i+8),i+=16),i+=2;let u=s.length+o;const c=hD(s,i);i+=2;for(let d=0;d>>31===1)return Mi.warn("SIDX has hierarchical references (not supported)"),null;const x=zt(s,f);f+=4,e.push({referenceSize:g,subsegmentDuration:x,info:{duration:x/n,start:u,end:u+g-1}}),u+=g,f+=4,i=f}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:c,references:e}}function mD(s){const e=[],t=ci(s,["moov","trak"]);for(let n=0;n{const r=zt(n,4),o=e[r];o&&(o.default={duration:zt(n,12),flags:zt(n,20)})}),e}function j8(s){const e=s.subarray(8),t=e.subarray(86),i=Ms(e.subarray(4,8));let n=i,r;const o=i==="enca"||i==="encv";if(o){const d=ci(e,[i])[0].subarray(i==="enca"?28:78);ci(d,["sinf"]).forEach(p=>{const g=ci(p,["schm"])[0];if(g){const y=Ms(g.subarray(4,8));if(y==="cbcs"||y==="cenc"){const x=ci(p,["frma"])[0];x&&(n=Ms(x))}}})}const u=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const c=ci(t,["avcC"])[0];c&&c.length>3&&(n+="."+mm(c[1])+mm(c[2])+mm(c[3]),r=fm(u==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=ci(e,[i])[0],d=ci(c.subarray(28),["esds"])[0];if(d&&d.length>7){let f=4;if(d[f++]!==3)break;f=Jy(d,f),f+=2;const p=d[f++];if(p&128&&(f+=2),p&64&&(f+=d[f++]),d[f++]!==4)break;f=Jy(d,f);const g=d[f++];if(g===64)n+="."+mm(g);else break;if(f+=12,d[f++]!==5)break;f=Jy(d,f);const y=d[f++];let x=(y&248)>>3;x===31&&(x+=1+((y&7)<<3)+((d[f]&224)>>5)),n+="."+x}break}case"hvc1":case"hev1":{const c=ci(t,["hvcC"])[0];if(c&&c.length>12){const d=c[1],f=["","A","B","C"][d>>6],p=d&31,g=zt(c,2),y=(d&32)>>5?"H":"L",x=c[12],_=c.subarray(6,12);n+="."+f+p,n+="."+$8(g).toString(16).toUpperCase(),n+="."+y+x;let w="";for(let D=_.length;D--;){const I=_[D];(I||w)&&(w="."+I.toString(16).toUpperCase()+w)}n+=w}r=fm(u=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=fm(n,t)||n;break}case"vp09":{const c=ci(t,["vpcC"])[0];if(c&&c.length>6){const d=c[4],f=c[5],p=c[6]>>4&15;n+="."+Qr(d)+"."+Qr(f)+"."+Qr(p)}break}case"av01":{const c=ci(t,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,f=c[1]&31,p=c[2]>>>7?"H":"M",g=(c[2]&64)>>6,y=(c[2]&32)>>5,x=d===2&&g?y?12:10:g?10:8,_=(c[2]&16)>>4,w=(c[2]&8)>>3,D=(c[2]&4)>>2,I=c[2]&3;n+="."+d+"."+Qr(f)+p+"."+Qr(x)+"."+_+"."+w+D+I+"."+Qr(1)+"."+Qr(1)+"."+Qr(1)+"."+0,r=fm("dav1",t)}break}}return{codec:n,encrypted:o,supplemental:r}}function fm(s,e){const t=ci(e,["dvvC"]),i=t.length?t[0]:ci(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+Qr(n)+"."+Qr(r)}}function $8(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function Jy(s,e){const t=e+5;for(;s[e++]&128&&e{const r=i.subarray(8,24);r.some(o=>o!==0)||(Mi.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Xs(r)} -> ${Xs(t)}`),i.set(t,8))})}function V8(s){const e=[];return pD(s,t=>e.push(t.subarray(8,24))),e}function pD(s,e){ci(s,["moov","trak"]).forEach(i=>{const n=ci(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let o=ci(r,["enca"]);const u=o.length>0;u||(o=ci(r,["encv"])),o.forEach(c=>{const d=u?c.subarray(28):c.subarray(78);ci(d,["sinf"]).forEach(p=>{const g=gD(p);g&&e(g,u)})})})}function gD(s){const e=ci(s,["schm"])[0];if(e){const t=Ms(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=ci(s,["schi","tenc"])[0];if(i)return i}}}function G8(s,e,t){const i={},n=ci(s,["moof","traf"]);for(let r=0;ri[r].duration)){let r=1/0,o=0;const u=ci(s,["sidx"]);for(let c=0;cp+g.info.duration||0,0);o=Math.max(o,f+d.earliestPresentationTime/d.timescale)}}o&>(o)&&Object.keys(i).forEach(c=>{i[c].duration||(i[c].duration=o*i[c].timescale-i[c].start)})}return i}function z8(s){const e={valid:null,remainder:null},t=ci(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function fr(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function h2(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let o=!1;return ci(i,["moof"]).map(c=>{const d=c.byteOffset-8;ci(c,["traf"]).map(p=>{const g=ci(p,["tfdt"]).map(y=>{const x=y[0];let _=zt(y,4);return x===1&&(_*=Math.pow(2,32),_+=zt(y,8)),_/n})[0];return g!==void 0&&(s=g),ci(p,["tfhd"]).map(y=>{const x=zt(y,4),_=zt(y,0)&16777215,w=(_&1)!==0,D=(_&2)!==0,I=(_&8)!==0;let L=0;const B=(_&16)!==0;let j=0;const V=(_&32)!==0;let M=8;x===r&&(w&&(M+=8),D&&(M+=4),I&&(L=zt(y,M),M+=4),B&&(j=zt(y,M),M+=4),V&&(M+=4),e.type==="video"&&(o=a0(e.codec)),ci(p,["trun"]).map(z=>{const O=z[0],N=zt(z,0)&16777215,q=(N&1)!==0;let Q=0;const Y=(N&4)!==0,re=(N&256)!==0;let Z=0;const H=(N&512)!==0;let K=0;const ie=(N&1024)!==0,te=(N&2048)!==0;let ne=0;const $=zt(z,4);let ee=8;q&&(Q=zt(z,ee),ee+=4),Y&&(ee+=4);let le=Q+d;for(let be=0;be<$;be++){if(re?(Z=zt(z,ee),ee+=4):Z=L,H?(K=zt(z,ee),ee+=4):K=j,ie&&(ee+=4),te&&(O===0?ne=zt(z,ee):ne=fD(z,ee),ee+=4),e.type===qi.VIDEO){let fe=0;for(;fe>1&63;return t===39||t===40}else return(e&31)===6}function Db(s,e,t,i){const n=yD(s);let r=0;r+=e;let o=0,u=0,c=0;for(;r=n.length)break;c=n[r++],o+=c}while(c===255);u=0;do{if(r>=n.length)break;c=n[r++],u+=c}while(c===255);const d=n.length-r;let f=r;if(ud){Mi.error(`Malformed SEI payload. ${u} is too small, only ${d} bytes left to parse.`);break}if(o===4){if(n[f++]===181){const g=hD(n,f);if(f+=2,g===49){const y=zt(n,f);if(f+=4,y===1195456820){const x=n[f++];if(x===3){const _=n[f++],w=31&_,D=64&_,I=D?2+w*3:0,L=new Uint8Array(I);if(D){L[0]=_;for(let B=1;B16){const p=[];for(let x=0;x<16;x++){const _=n[f++].toString(16);p.push(_.length==1?"0"+_:_),(x===3||x===5||x===7||x===9)&&p.push("-")}const g=u-16,y=new Uint8Array(g);for(let x=0;x>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(s,4),n=0,i=8;n0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const o=new Uint8Array(4);return t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),Y8([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,o,t)}function X8(s){const e=[];if(s instanceof ArrayBuffer){const t=s.byteLength;let i=0;for(;i+32>>24;if(r!==0&&r!==1)return{offset:t,size:e};const o=s.buffer,u=Xs(new Uint8Array(o,t+12,16));let c=null,d=null,f=0;if(r===0)f=28;else{const g=s.getUint32(28);if(!g||i<32+g*16)return{offset:t,size:e};c=[];for(let y=0;y/\(Windows.+Firefox\//i.test(navigator.userAgent),Ec={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Lb(s,e){const t=Ec[e];return!!t&&!!t[s.slice(0,4)]}function gh(s,e,t=!0){return!s.split(",").some(i=>!Rb(i,e,t))}function Rb(s,e,t=!0){var i;const n=Xo(t);return(i=n?.isTypeSupported(yh(s,e)))!=null?i:!1}function yh(s,e){return`${e}/mp4;codecs=${s}`}function f2(s){if(s){const e=s.substring(0,4);return Ec.video[e]}return 2}function gp(s){const e=vD();return s.split(",").reduce((t,i)=>{const r=e&&a0(i)?9:Ec.video[i];return r?(r*2+t)/(t?3:2):(Ec.audio[i]+t)/(t?2:1)},0)}const ev={};function Z8(s,e=!0){if(ev[s])return ev[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;nZ8(t.toLowerCase(),e))}function e6(s,e){const t=[];if(s){const i=s.split(",");for(let n=0;n4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(m2(s,"audio")||m2(s,"video")))return s;if(e){const t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function m2(s,e){return Lb(s,e)&&Rb(s,e)}function t6(s){const e=s.split(",");for(let t=0;t2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function i6(s){if(s.startsWith("av01.")){const e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function p2(s){const e=Xo(s)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function mx(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const s6={supported:!0,powerEfficient:!0,smooth:!0},n6={supported:!1,smooth:!1,powerEfficient:!1},xD={supported:!0,configurations:[],decodingInfoResults:[s6]};function bD(s,e){return{supported:!1,configurations:e,decodingInfoResults:[n6],error:s}}function r6(s,e,t,i,n,r){const o=s.videoCodec,u=s.audioCodec?s.audioGroups:null,c=r?.audioCodec,d=r?.channels,f=d?parseInt(d):c?1/0:2;let p=null;if(u!=null&&u.length)try{u.length===1&&u[0]?p=e.groups[u[0]].channels:p=u.reduce((g,y)=>{if(y){const x=e.groups[y];if(!x)throw new Error(`Audio track group ${y} not found`);Object.keys(x.channels).forEach(_=>{g[_]=(g[_]||0)+x.channels[_]})}return g},{2:0})}catch{return!0}return o!==void 0&&(o.split(",").some(g=>a0(g))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(n,8e6))||!!p&>(f)&&Object.keys(p).some(g=>parseInt(g)>f)}function TD(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(xD);const r=[],o=a6(s),u=o.length,c=o6(s,e,u>0),d=c.length;for(let f=u||1*d||1;f--;){const p={type:"media-source"};if(u&&(p.video=o[f%u]),d){p.audio=c[f%d];const g=p.audio.bitrate;p.video&&g&&(p.video.bitrate-=g)}r.push(p)}if(n){const f=navigator.userAgent;if(n.split(",").some(p=>a0(p))&&vD())return Promise.resolve(bD(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${f})`),r))}return Promise.all(r.map(f=>{const p=u6(f);return i[p]||(i[p]=t.decodingInfo(f))})).then(f=>({supported:!f.some(p=>!p.supported),configurations:r,decodingInfoResults:f})).catch(f=>({supported:!1,configurations:r,decodingInfoResults:[],error:f}))}function a6(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=_D(s),n=s.width||640,r=s.height||480,o=s.frameRate||30,u=s.videoRange.toLowerCase();return t?t.map(c=>{const d={contentType:yh(i6(c),"video"),width:n,height:r,bitrate:i,framerate:o};return u!=="sdr"&&(d.transferFunction=u),d}):[]}function o6(s,e,t){var i;const n=(i=s.audioCodec)==null?void 0:i.split(","),r=_D(s);return n&&s.audioGroups?s.audioGroups.reduce((o,u)=>{var c;const d=u?(c=e.groups[u])==null?void 0:c.tracks:null;return d?d.reduce((f,p)=>{if(p.groupId===u){const g=parseFloat(p.channels||"");n.forEach(y=>{const x={contentType:yh(y,"audio"),bitrate:t?l6(y,r):r};g&&(x.channels=""+g),f.push(x)})}return f},o):o},[]):[]}function l6(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function _D(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function u6(s){let e="";const{audio:t,video:i}=s;if(i){const n=mx(i.contentType);e+=`${n}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){const n=mx(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const px=["NONE","TYPE-0","TYPE-1",null];function c6(s){return px.indexOf(s)>-1}const vp=["SDR","PQ","HLG"];function d6(s){return!!s&&vp.indexOf(s)>-1}var Pm={No:"",Yes:"YES",v2:"v2"};function g2(s){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,n=i!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return v2(this._audioGroups,e)}hasSubtitleGroup(e){return v2(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function v2(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function h6(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function f6(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||vp.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&h6(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const m6=s=>{const e=new WeakSet;return(t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},Yi=(s,e)=>JSON.stringify(s,m6(e));function p6(s,e,t,i,n){const r=Object.keys(s),o=i?.channels,u=i?.audioCodec,c=n?.videoCodec,d=o&&parseInt(o)===2;let f=!1,p=!1,g=1/0,y=1/0,x=1/0,_=1/0,w=0,D=[];const{preferHDR:I,allowedVideoRanges:L}=f6(e,n);for(let z=r.length;z--;){const O=s[r[z]];f||(f=O.channels[2]>0),g=Math.min(g,O.minHeight),y=Math.min(y,O.minFramerate),x=Math.min(x,O.minBitrate),L.filter(q=>O.videoRanges[q]>0).length>0&&(p=!0)}g=gt(g)?g:0,y=gt(y)?y:0;const B=Math.max(1080,g),j=Math.max(30,y);x=gt(x)?x:t,t=Math.max(x,t),p||(e=void 0);const V=r.length>1;return{codecSet:r.reduce((z,O)=>{const N=s[O];if(O===z)return z;if(D=p?L.filter(q=>N.videoRanges[q]>0):[],V){if(N.minBitrate>t)return Kr(O,`min bitrate of ${N.minBitrate} > current estimate of ${t}`),z;if(!N.hasDefaultAudio)return Kr(O,"no renditions with default or auto-select sound found"),z;if(u&&O.indexOf(u.substring(0,4))%5!==0)return Kr(O,`audio codec preference "${u}" not found`),z;if(o&&!d){if(!N.channels[o])return Kr(O,`no renditions with ${o} channel sound found (channels options: ${Object.keys(N.channels)})`),z}else if((!u||d)&&f&&N.channels[2]===0)return Kr(O,"no renditions with stereo sound found"),z;if(N.minHeight>B)return Kr(O,`min resolution of ${N.minHeight} > maximum of ${B}`),z;if(N.minFramerate>j)return Kr(O,`min framerate of ${N.minFramerate} > maximum of ${j}`),z;if(!D.some(q=>N.videoRanges[q]>0))return Kr(O,`no variants with VIDEO-RANGE of ${Yi(D)} found`),z;if(c&&O.indexOf(c.substring(0,4))%5!==0)return Kr(O,`video codec preference "${c}" not found`),z;if(N.maxScore=gp(z)||N.fragmentError>s[z].fragmentError)?z:(_=N.minIndex,w=N.maxScore,O)},void 0),videoRanges:D,preferHDR:I,minFramerate:y,minBitrate:x,minIndex:_}}function Kr(s,e){Mi.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function SD(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const n=t.channels||"2";return i.channels[n]=(i.channels[n]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function g6(s,e,t,i){return s.slice(t,i+1).reduce((n,r,o)=>{if(!r.codecSet)return n;const u=r.audioGroups;let c=n[r.codecSet];c||(n[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!u,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const d=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,o),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,u&&u.forEach(f=>{if(!f)return;const p=e.groups[f];p&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?p.hasDefault:p.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(p.channels).forEach(g=>{c.channels[g]=(c.channels[g]||0)+p.channels[g]}))}),n},{})}function x2(s){if(!s)return s;const{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}=s;return{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}}function ra(s,e,t){if("attrs"in s){const i=e.indexOf(s);if(i!==-1)return i}for(let i=0;ii.indexOf(n)===-1)}function Nl(s,e){const{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function x6(s,e,t,i,n){const r=e[i],u=e.reduce((g,y,x)=>{const _=y.uri;return(g[_]||(g[_]=[])).push(x),g},{})[r.uri];u.length>1&&(i=Math.max.apply(Math,u));const c=r.videoRange,d=r.frameRate,f=r.codecSet.substring(0,4),p=b2(e,i,g=>{if(g.videoRange!==c||g.frameRate!==d||g.codecSet.substring(0,4)!==f)return!1;const y=g.audioGroups,x=t.filter(_=>!y||y.indexOf(_.groupId)!==-1);return ra(s,x,n)>-1});return p>-1?p:b2(e,i,g=>{const y=g.audioGroups,x=t.filter(_=>!y||y.indexOf(_.groupId)!==-1);return ra(s,x,n)>-1})}function b2(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i{var i;const{fragCurrent:n,partCurrent:r,hls:o}=this,{autoLevelEnabled:u,media:c}=o;if(!n||!c)return;const d=performance.now(),f=r?r.stats:n.stats,p=r?r.duration:n.duration,g=d-f.loading.start,y=o.minAutoLevel,x=n.level,_=this._nextAutoLevel;if(f.aborted||f.loaded&&f.loaded===f.total||x<=y){this.clearTimer(),this._nextAutoLevel=-1;return}if(!u)return;const w=_>-1&&_!==x,D=!!t||w;if(!D&&(c.paused||!c.playbackRate||!c.readyState))return;const I=o.mainForwardBufferInfo;if(!D&&I===null)return;const L=this.bwEstimator.getEstimateTTFB(),B=Math.abs(c.playbackRate);if(g<=Math.max(L,1e3*(p/(B*2))))return;const j=I?I.len/B:0,V=f.loading.first?f.loading.first-f.loading.start:-1,M=f.loaded&&V>-1,z=this.getBwEstimate(),O=o.levels,N=O[x],q=Math.max(f.loaded,Math.round(p*(n.bitrate||N.averageBitrate)/8));let Q=M?g-V:g;Q<1&&M&&(Q=Math.min(g,f.loaded*8/z));const Y=M?f.loaded*1e3/Q:0,re=L/1e3,Z=Y?(q-f.loaded)/Y:q*8/z+re;if(Z<=j)return;const H=Y?Y*8:z,K=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,ie=this.hls.config.abrBandWidthUpFactor;let te=Number.POSITIVE_INFINITY,ne;for(ne=x-1;ne>y;ne--){const be=O[ne].maxBitrate,fe=!O[ne].details||K;if(te=this.getTimeToLoadFrag(re,H,p*be,fe),te=Z||te>p*10)return;M?this.bwEstimator.sample(g-Math.min(L,V),f.loaded):this.bwEstimator.sampleTTFB(g);const $=O[ne].maxBitrate;this.getBwEstimate()*ie>$&&this.resetEstimator($);const ee=this.findBestLevel($,y,ne,0,j,1,1);ee>-1&&(ne=ee),this.warn(`Fragment ${n.sn}${r?" part "+r.index:""} of level ${x} is loading too slowly; + Fragment duration: ${n.duration.toFixed(3)} + Time to underbuffer: ${j.toFixed(3)} s + Estimated load time for current fragment: ${Z.toFixed(3)} s + Estimated load time for down switch fragment: ${te.toFixed(3)} s + TTFB estimate: ${V|0} ms + Current BW estimate: ${gt(z)?z|0:"Unknown"} bps + New BW estimate: ${this.getBwEstimate()|0} bps + Switching to level ${ne} @ ${$|0} bps`),o.nextLoadLevel=o.nextAutoLevel=ne,this.clearTimer();const le=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===ne&&ne>0){const be=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${ne>0?"and switching down":""} + Fragment duration: ${n.duration.toFixed(3)} s + Time to underbuffer: ${be.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,ne>y){let fe=this.findBestLevel(this.hls.levels[y].bitrate,y,ne,0,be,1,1);fe===-1&&(fe=y),this.hls.nextLoadLevel=this.hls.nextAutoLevel=fe,this.resetEstimator(this.hls.levels[fe].bitrate)}}};w||Z>te*2?le():this.timer=self.setInterval(le,te*1e3),o.trigger(U.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:r,stats:f})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new w8(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.FRAG_LOADING,this.onFragLoading,this),e.on(U.FRAG_LOADED,this.onFragLoaded,this),e.on(U.FRAG_BUFFERED,this.onFragBuffered,this),e.on(U.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(U.LEVEL_LOADED,this.onLevelLoaded,this),e.on(U.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(U.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(U.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.FRAG_LOADING,this.onFragLoading,this),e.off(U.FRAG_LOADED,this.onFragLoaded,this),e.off(U.FRAG_BUFFERED,this.onFragBuffered,this),e.off(U.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(U.LEVEL_LOADED,this.onLevelLoaded,this),e.off(U.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(U.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(U.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case we.BUFFER_ADD_CODEC_ERROR:case we.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case we.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const o=performance.now(),u=r?r.stats:i.stats,c=o-u.loading.start,d=u.loading.first?u.loading.first-u.loading.start:-1;if(u.loaded&&d>-1){const p=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(p,d),u.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,i,n){const r=e+i/t,o=n?e+this.lastLevelLoadSec:0;return r+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;gt(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===_t.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,o=this.hls.levels[t.level],u=(o.loaded?o.loaded.bytes:0)+n.loaded,c=(o.loaded?o.loaded.duration:0)+r;o.loaded={bytes:u,duration:c},o.realBitrate=Math.round(8*u/c)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(U.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,r=n!=null&&n.stats.loaded?n.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const o=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==_t.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,n,1,1);if(r>-1)return r;const o=this.hls.firstLevel,u=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${u}`),u}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,r)&&o[e].loadError<=o[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:r,minAutoLevel:o}=i,u=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let f=r.abrBandWidthFactor,p=r.abrBandWidthUpFactor;if(d){const w=this.findBestLevel(c,o,n,d,0,f,p);if(w>=0)return this.rebufferNotice=-1,w}let g=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!d){const w=this.bitrateTestDelay;w&&(g=(u?Math.min(u,r.maxLoadingDelay):r.maxLoadingDelay)-w,this.info(`bitrate test took ${Math.round(1e3*w)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),f=p=1)}const y=this.findBestLevel(c,o,n,d,g,f,p);if(this.rebufferNotice!==y&&(this.rebufferNotice=y,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${y}`)),y>-1)return y;const x=i.levels[o],_=i.loadLevelObj;return _&&x?.bitrate<_.bitrate?o:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,r,o,u){var c;const d=n+r,f=this.lastLoadedFragLevel,p=f===-1?this.hls.firstLevel:f,{fragCurrent:g,partCurrent:y}=this,{levels:x,allAudioTracks:_,loadLevel:w,config:D}=this.hls;if(x.length===1)return 0;const I=x[p],L=!!((c=this.hls.latestLevelDetails)!=null&&c.live),B=w===-1||f===-1;let j,V="SDR",M=I?.frameRate||0;const{audioPreference:z,videoPreference:O}=D,N=this.audioTracksByGroup||(this.audioTracksByGroup=SD(_));let q=-1;if(B){if(this.firstSelection!==-1)return this.firstSelection;const H=this.codecTiers||(this.codecTiers=g6(x,N,t,i)),K=p6(H,V,e,z,O),{codecSet:ie,videoRanges:te,minFramerate:ne,minBitrate:$,minIndex:ee,preferHDR:le}=K;q=ee,j=ie,V=le?te[te.length-1]:te[0],M=ne,e=Math.max(e,$),this.log(`picked start tier ${Yi(K)}`)}else j=I?.codecSet,V=I?.videoRange;const Q=y?y.duration:g?g.duration:0,Y=this.bwEstimator.getEstimateTTFB()/1e3,re=[];for(let H=i;H>=t;H--){var Z;const K=x[H],ie=H>p;if(!K)continue;if(D.useMediaCapabilities&&!K.supportedResult&&!K.supportedPromise){const fe=navigator.mediaCapabilities;typeof fe?.decodingInfo=="function"&&r6(K,N,V,M,e,z)?(K.supportedPromise=TD(K,N,fe,this.supportedCache),K.supportedPromise.then(_e=>{if(!this.hls)return;K.supportedResult=_e;const Me=this.hls.levels,et=Me.indexOf(K);_e.error?this.warn(`MediaCapabilities decodingInfo error: "${_e.error}" for level ${et} ${Yi(_e)}`):_e.supported?_e.decodingInfoResults.some(Ge=>Ge.smooth===!1||Ge.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${et} not smooth or powerEfficient: ${Yi(_e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${et} ${Yi(_e)}`),et>-1&&Me.length>1&&(this.log(`Removing unsupported level ${et}`),this.hls.removeLevel(et),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(_e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${_e}`)})):K.supportedResult=xD}if((j&&K.codecSet!==j||V&&K.videoRange!==V||ie&&M>K.frameRate||!ie&&M>0&&Mfe.smooth===!1))&&(!B||H!==q)){re.push(H);continue}const te=K.details,ne=(y?te?.partTarget:te?.averagetargetduration)||Q;let $;ie?$=u*e:$=o*e;const ee=Q&&n>=Q*2&&r===0?K.averageBitrate:K.maxBitrate,le=this.getTimeToLoadFrag(Y,$,ee*ne,te===void 0);if($>=ee&&(H===f||K.loadError===0&&K.fragmentError===0)&&(le<=Y||!gt(le)||L&&!this.bitrateTestDelay||le${H} adjustedbw(${Math.round($)})-bitrate=${Math.round($-ee)} ttfb:${Y.toFixed(1)} avgDuration:${ne.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${le.toFixed(1)} firstSelection:${B} codecSet:${K.codecSet} videoRange:${K.videoRange} hls.loadLevel:${w}`)),B&&(this.firstSelection=H),H}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const ED={search:function(s,e){let t=0,i=s.length-1,n=null,r=null;for(;t<=i;){n=(t+i)/2|0,r=s[n];const o=e(r);if(o>0)t=n+1;else if(o<0)i=n-1;else return r}return null}};function T6(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!gt(e))return null;const i=s[0].programDateTime;if(e<(i||0))return null;const n=s[s.length-1].endProgramDateTime;if(e>=(n||0))return null;for(let r=0;r0&&u<15e-7&&(t+=15e-7),r&&s.level!==r.level&&r.end<=s.end&&(r=e[2+s.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!s||s.level===r.level)&&T2(t,i,r)===0||_6(r,s,Math.min(n,i))))return r;const o=ED.search(e,T2.bind(null,t,i));return o&&(o!==s||!r)?o:r}function _6(s,e,t){if(e&&e.start===0&&e.level0){const i=e.tagList.reduce((n,r)=>(r[0]==="INF"&&(n+=parseFloat(r[1])),n),t);return s.start<=i}return!1}function T2(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function S6(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function wD(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments;const{fragmentHint:n}=s;n&&(i=i.concat(n));let r;return ED.search(i,o=>o.cce?-1:(r=o,o.end<=t?1:o.start>t?-1:0)),r||null}return null}function bp(s){switch(s.details){case we.FRAG_LOAD_TIMEOUT:case we.KEY_LOAD_TIMEOUT:case we.LEVEL_LOAD_TIMEOUT:case we.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function AD(s){return s.details.startsWith("key")}function CD(s){return AD(s)&&!!s.frag&&!s.frag.decryptdata}function _2(s,e){const t=bp(e);return s.default[`${t?"timeout":"error"}Retry`]}function Ib(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function S2(s){return Oi(Oi({},s),{errorRetry:null,timeoutRetry:null})}function Tp(s,e,t,i){if(!s)return!1;const n=i?.code,r=e499)}function gx(s){return s===0&&navigator.onLine===!1}var Ys={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Xn={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class w6 extends gr{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(U.ERROR,this.onError,this),e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(U.ERROR,this.onError,this),e.off(U.ERROR,this.onErrorOut,this),e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===_t.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(o=>n.indexOf(o.groupId)>=0).some(o=>{var u;return(u=o.details)==null?void 0:u.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const n=this.hls,r=t.context;switch(t.details){case we.FRAG_LOAD_ERROR:case we.FRAG_LOAD_TIMEOUT:case we.KEY_LOAD_ERROR:case we.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case we.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=uc();return}case we.FRAG_GAP:case we.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ys.SendAlternateToPenaltyBox;return}case we.LEVEL_EMPTY_ERROR:case we.LEVEL_PARSING_ERROR:{var o;const c=t.parent===_t.MAIN?t.level:n.loadLevel;t.details===we.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(o=o.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case we.LEVEL_LOAD_ERROR:case we.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case we.AUDIO_TRACK_LOAD_ERROR:case we.AUDIO_TRACK_LOAD_TIMEOUT:case we.SUBTITLE_LOAD_ERROR:case we.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=n.loadLevelObj;if(c&&(r.type===di.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===di.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Ys.SendAlternateToPenaltyBox,t.errorAction.flags=Xn.MoveAllAlternatesMatchingHost;return}}return;case we.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ys.SendAlternateToPenaltyBox,flags:Xn.MoveAllAlternatesMatchingHDCP};return;case we.KEY_SYSTEM_SESSION_UPDATE_FAILED:case we.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case we.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ys.SendAlternateToPenaltyBox,flags:Xn.MoveAllAlternatesMatchingKey};return;case we.BUFFER_ADD_CODEC_ERROR:case we.REMUX_ALLOC_ERROR:case we.BUFFER_APPEND_ERROR:if(!t.errorAction){var u;t.errorAction=this.getLevelSwitchAction(t,(u=t.level)!=null?u:n.loadLevel)}return;case we.INTERNAL_EXCEPTION:case we.BUFFER_APPENDING_ERROR:case we.BUFFER_FULL_ERROR:case we.LEVEL_SWITCH_ERROR:case we.BUFFER_STALLED_ERROR:case we.BUFFER_SEEK_OVER_HOLE:case we.BUFFER_NUDGE_ON_STALL:t.errorAction=uc();return}t.type===Lt.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=uc())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=_2(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(Tp(n,r,bp(e),e.response))return{action:Ys.RetryRequest,flags:Xn.None,retryConfig:n,retryCount:r};const u=this.getLevelSwitchAction(e,t);return n&&(u.retryConfig=n,u.retryCount=r),u}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:o}=t.config,u=_2(AD(e)?o:r,e),c=t.levels.reduce((f,p)=>f+p.fragmentError,0);if(n&&(e.details!==we.FRAG_GAP&&n.fragmentError++,!CD(e)&&Tp(u,c,bp(e),e.response)))return{action:Ys.RetryRequest,flags:Xn.None,retryConfig:u,retryCount:c};const d=this.getLevelSwitchAction(e,i);return u&&(d.retryConfig=u,d.retryCount=c),d}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var r,o;const d=e.details;n.loadError++,d===we.BUFFER_APPEND_ERROR&&n.fragmentError++;let f=-1;const{levels:p,loadLevel:g,minAutoLevel:y,maxAutoLevel:x}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const _=(r=e.frag)==null?void 0:r.type,D=(_===_t.AUDIO&&d===we.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===we.BUFFER_ADD_CODEC_ERROR||d===we.BUFFER_APPEND_ERROR))&&p.some(({audioCodec:V})=>n.audioCodec!==V),L=e.sourceBufferName==="video"&&(d===we.BUFFER_ADD_CODEC_ERROR||d===we.BUFFER_APPEND_ERROR)&&p.some(({codecSet:V,audioCodec:M})=>n.codecSet!==V&&n.audioCodec===M),{type:B,groupId:j}=(o=e.context)!=null?o:{};for(let V=p.length;V--;){const M=(V+g)%p.length;if(M!==g&&M>=y&&M<=x&&p[M].loadError===0){var u,c;const z=p[M];if(d===we.FRAG_GAP&&_===_t.MAIN&&e.frag){const O=p[M].details;if(O){const N=Yl(e.frag,O.fragments,e.frag.start);if(N!=null&&N.gap)continue}}else{if(B===di.AUDIO_TRACK&&z.hasAudioGroup(j)||B===di.SUBTITLE_TRACK&&z.hasSubtitleGroup(j))continue;if(_===_t.AUDIO&&(u=n.audioGroups)!=null&&u.some(O=>z.hasAudioGroup(O))||_===_t.SUBTITLE&&(c=n.subtitleGroups)!=null&&c.some(O=>z.hasSubtitleGroup(O))||D&&n.audioCodec===z.audioCodec||L&&n.codecSet===z.codecSet||!D&&n.codecSet!==z.codecSet)continue}f=M;break}}if(f>-1&&i.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:Ys.SendAlternateToPenaltyBox,flags:Xn.None,nextAutoLevel:f}}return{action:Ys.SendAlternateToPenaltyBox,flags:Xn.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case Ys.DoNothing:break;case Ys.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==we.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n}=i,r=i.nextAutoLevel;switch(n){case Xn.None:this.switchLevel(e,r);break;case Xn.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),d=t.levels[c],f=d?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=f,f==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(f){t.maxHdcpLevel=px[px.indexOf(f)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Xn.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const d=this.hls.levels,f=d.length;for(let g=f;g--;)if(this.variantHasKey(d[g],c)){var o,u;this.log(`Banned key found in level ${g} (${d[g].bitrate}bps) or audio group "${(o=d[g].audioGroups)==null?void 0:o.join(",")}" (${(u=e.frag)==null?void 0:u.type} fragment) ${Xs(c.keyId||[])}`),d[g].fragmentError++,d[g].loadError++,this.log(`Removing level ${g} with key error (${e.error})`),this.hls.removeLevel(g)}const p=e.frag;if(this.hls.levels.length{const c=this.fragments[u];if(!c||o>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===i&&this.removeFragment(c.body);return}const d=c.range[e];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(f=>{const p=!this.isTimeBuffered(f.startPTS,f.endPTS,t);return p&&this.removeFragment(c.body),p})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=ju(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(u=>{const c=i.elementaryStreams[u];if(!c)return;const d=t[u],f=o||c.partial===!0;r.range[u]=this.getBufferedTimes(i,e.part,f,d)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),pm(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=E2(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=ju(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,i,n){const r={time:[],partial:i},o=e.start,u=e.end,c=e.minEndPTS||u,d=e.maxStartPTS||o;for(let f=0;f=p&&c<=g){r.time.push({startPTS:Math.max(o,n.start(f)),endPTS:Math.min(u,n.end(f))});break}else if(op){const y=Math.max(o,n.start(f)),x=Math.min(u,n.end(f));x>y&&(r.partial=!0,r.time.push({startPTS:y,endPTS:x}))}else if(u<=p)break}return r}getPartialFragment(e){let t=null,i,n,r,o=0;const{bufferPadding:u,fragments:c}=this;return Object.keys(c).forEach(d=>{const f=c[d];f&&pm(f)&&(n=f.body.start-u,r=f.body.end+u,e>=n&&e<=r&&(i=Math.min(e-n,r-e),o<=i&&(t=f.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||pm(t))}getState(e){const t=ju(e),i=this.fragments[t];return i?i.buffered?pm(i)?Ps.PARTIAL:Ps.OK:Ps.APPENDING:Ps.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let o=0;o=n&&t<=r)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,r=ju(i);this.fragments[r]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:r,type:o}=t;if(i.sn==="initSegment")return;const u=i.type;if(n){let d=this.activePartLists[u];d||(this.activePartLists[u]=d=[]),d.push(n)}this.timeRanges=r;const c=r[o];this.detectEvictedFragments(o,c,u,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=ju(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const r=t[i[n]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const u=this.fragments[o];if(!u)return;const c=u.body;c.type!==i||n&&!c.gap||c.starte&&(u.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=ju(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=E2(i,r=>r.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}}function pm(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function ju(s){return`${s.type}_${s.level}_${s.sn}`}function E2(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Qo={cbc:0,ctr:1};class C6{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Qo.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Qo.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function k6(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class D6{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],r=i[1],o=i[2],u=i[3],c=this.invSubMix,d=c[0],f=c[1],p=c[2],g=c[3],y=new Uint32Array(256);let x=0,_=0,w=0;for(w=0;w<256;w++)w<128?y[w]=w<<1:y[w]=w<<1^283;for(w=0;w<256;w++){let D=_^_<<1^_<<2^_<<3^_<<4;D=D>>>8^D&255^99,e[x]=D,t[D]=x;const I=y[x],L=y[I],B=y[L];let j=y[D]*257^D*16843008;n[x]=j<<24|j>>>8,r[x]=j<<16|j>>>16,o[x]=j<<8|j>>>24,u[x]=j,j=B*16843009^L*65537^I*257^x*16843008,d[D]=j<<24|j>>>8,f[D]=j<<16|j>>>16,p[D]=j<<8|j>>>24,g[D]=j,x?(x=I^y[y[y[B^I]]],_^=y[y[_]]):x=_=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n{const u=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(u,t,i,n);const c=this.flush();c?r(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:o,remainderData:u}=this;if(n!==Qo.cbc||t.byteLength!==16)return Mi.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),u&&(e=fr(u,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(i=r);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new D6),d.expandKey(t);const f=o;return this.currentResult=d.decrypt(c.buffer,0,i),this.currentIV=c.slice(-16).buffer,f||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new L6(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new C6(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Mi.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%I6;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Mi.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const w2=Math.pow(2,17);class N6{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Ba({type:Lt.NETWORK_ERROR,details:we.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(x=>x[0]==="GAP")){c(C2(e));return}else e.gap=!1;const d=this.loader=r?new r(n):new o(n),f=A2(e);e.loader=d;const p=S2(n.fragLoadPolicy.default),g={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:w2};e.stats=d.stats;const y={onSuccess:(x,_,w,D)=>{this.resetLoader(e,d);let I=x.data;w.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(I.slice(0,16)),I=I.slice(16)),u({frag:e,part:null,payload:I,networkDetails:D})},onError:(x,_,w,D)=>{this.resetLoader(e,d),c(new Ba({type:Lt.NETWORK_ERROR,details:we.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Oi({url:i,data:void 0},x),error:new Error(`HTTP Error ${x.code} ${x.text}`),networkDetails:w,stats:D}))},onAbort:(x,_,w)=>{this.resetLoader(e,d),c(new Ba({type:Lt.NETWORK_ERROR,details:we.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:w,stats:x}))},onTimeout:(x,_,w)=>{this.resetLoader(e,d),c(new Ba({type:Lt.NETWORK_ERROR,details:we.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:w,stats:x}))}};t&&(y.onProgress=(x,_,w,D)=>t({frag:e,part:null,payload:w,networkDetails:D})),d.load(f,g,y)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(C2(e,t));return}const d=this.loader=r?new r(n):new o(n),f=A2(e,t);e.loader=d;const p=S2(n.fragLoadPolicy.default),g={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:w2};t.stats=d.stats,d.load(f,g,{onSuccess:(y,x,_,w)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const D={frag:e,part:t,payload:y.data,networkDetails:w};i(D),u(D)},onError:(y,x,_,w)=>{this.resetLoader(e,d),c(new Ba({type:Lt.NETWORK_ERROR,details:we.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Oi({url:f.url,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:_,stats:w}))},onAbort:(y,x,_)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),c(new Ba({type:Lt.NETWORK_ERROR,details:we.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:_,stats:y}))},onTimeout:(y,x,_)=>{this.resetLoader(e,d),c(new Ba({type:Lt.NETWORK_ERROR,details:we.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:_,stats:y}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,r=n.total;if(i.loaded+=n.loaded,r){const c=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/r),c),p=(c-d)*Math.round(i.loaded/d);i.total=i.loaded+p}else i.total=Math.max(i.loaded,i.total);const o=i.loading,u=n.loading;o.start?o.first+=u.first-u.start:(o.start=u.start,o.first=u.first),o.end=u.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function A2(s,e=null){const t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(gt(n)&>(r)){var o;let u=n,c=r;if(s.sn==="initSegment"&&O6((o=s.decryptdata)==null?void 0:o.method)){const d=r-n;d%16&&(c=r+(16-d%16)),n!==0&&(i.resetIV=!0,u=n-16)}i.rangeStart=u,i.rangeEnd=c}return i}function C2(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:Lt.MEDIA_ERROR,details:we.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new Ba(i)}function O6(s){return s==="AES-128"||s==="AES-256"}class Ba extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class kD extends gr{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ob{constructor(e,t,i,n=0,r=-1,o=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=gm(),this.buffering={audio:gm(),video:gm(),audiovideo:gm()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=o}}function gm(){return{start:0,executeStart:0,executeEnd:0,end:0}}const k2={length:0,start:()=>0,end:()=>0};class Yt{static isBuffered(e,t){if(e){const i=Yt.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=Yt.getBuffered(e);return Yt.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i1&&e.sort((f,p)=>f.start-p.start||p.end-f.end);let n=-1,r=[];if(i)for(let f=0;f=e[f].start&&t<=e[f].end&&(n=f);const p=r.length;if(p){const g=r[p-1].end;e[f].start-gg&&(r[p-1].end=e[f].end):r.push(e[f])}else r.push(e[f])}else r=e;let o=0,u,c=t,d=t;for(let f=0;f=p&&t<=g&&(n=f),t+i>=p&&t{const n=i.substring(2,i.length-1),r=t?.[n];return r===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):r})}return e}function L2(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))r=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,r=e.VALUE;n in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=r||""}function M6(s,e,t){const i=e.IMPORT;if(t&&i in t){let n=s.variableList;n||(s.variableList=n={}),n[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const P6=/^(\d+)x(\d+)$/,R2=/(.+?)=(".*?"|.*?)(?:,|$)/g;class cs{constructor(e,t){typeof e=="string"&&(e=cs.parseAttrList(e,t)),$i(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let n=0;nNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,r)=>(n[r.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=P6.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={};for(R2.lastIndex=0;(i=R2.exec(e))!==null;){const o=i[1].trim();let u=i[2];const c=u.indexOf('"')===0&&u.lastIndexOf('"')===u.length-1;let d=!1;if(c)u=u.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(c||d))u=yx(t,u);else if(!d&&!c)switch(o){case"CLOSED-CAPTIONS":if(u==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Mi.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=u}return n}}const B6="com.apple.hls.interstitial";function F6(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function U6(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class LD{constructor(e,t,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(n=t?.tagOrder)!=null?n:i,t){const r=t.attr;for(const o in r)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==r[o]){Mi.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=$i(new cs({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=t?.endDate||new Date(this.attr["END-DATE"]);gt(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Mi.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(gt(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===B6}get isValid(){return!!this.id&&!this._badValueForSameId&>(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const j6=10;class $6{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?gt(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||j6}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function _p(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function I2(s,e){return!s&&!e?!0:!s||!e?!1:_p(s,e)}function cc(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Mb(s){switch(s){case"AES-128":case"AES-256":return Qo.cbc;case"AES-256-CTR":return Qo.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Pb(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function vx(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function H6(s){const e=vx(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function RD(s){const e=function(i,n,r){const o=i[n];i[n]=i[r],i[r]=o};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function ID(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const r=n[0]==="base64",o=n[1];r?(i.splice(-1,1),t=Pb(o)):t=H6(o)}}return t}const Sp=typeof self<"u"?self:void 0;var ds={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Qs={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Bm(s){switch(s){case Qs.FAIRPLAY:return ds.FAIRPLAY;case Qs.PLAYREADY:return ds.PLAYREADY;case Qs.WIDEVINE:return ds.WIDEVINE;case Qs.CLEARKEY:return ds.CLEARKEY}}function tv(s){switch(s){case ds.FAIRPLAY:return Qs.FAIRPLAY;case ds.PLAYREADY:return Qs.PLAYREADY;case ds.WIDEVINE:return Qs.WIDEVINE;case ds.CLEARKEY:return Qs.CLEARKEY}}function Wd(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[ds.FAIRPLAY,ds.WIDEVINE,ds.PLAYREADY,ds.CLEARKEY].filter(n=>!!e[n]):[];return!i[ds.WIDEVINE]&&t&&i.push(ds.WIDEVINE),i}const ND=(function(s){return Sp!=null&&(s=Sp.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function V6(s,e,t,i){let n;switch(s){case ds.FAIRPLAY:n=["cenc","sinf"];break;case ds.WIDEVINE:case ds.PLAYREADY:n=["cenc"];break;case ds.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return G6(n,e,t,i)}function G6(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function z6(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function OD(s){const e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){const u=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(u){const c=Pb(u).subarray(0,16);return RD(c),c}}return null}let $u={};class qo{static clearKeyUriToKeyIdMap(){$u={}}static setKeyIdForUri(e,t){$u[e]=t}static addKeyIdForUri(e){const t=Object.keys($u).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),$u[e]=i,i}constructor(e,t,i,n=[1],r=null,o){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=n,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!cc(e),o!=null&&o.startsWith("0x")&&(this.keyId=new Uint8Array(lD(o)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&_p(e.keyFormatVersions,this.keyFormatVersions)&&I2(e.iv,this.iv)&&I2(e.keyId,this.keyId)}isSupported(){if(this.method){if(cc(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Qs.FAIRPLAY:case Qs.WIDEVINE:case Qs.PLAYREADY:case Qs.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(cc(this.method)){let r=this.iv;return r||(typeof e!="number"&&(Mi.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=K6(e)),new qo(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=$u[this.uri];if(r&&!_p(this.keyId,r)&&qo.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=ID(this.uri);if(i)switch(this.keyFormat){case Qs.WIDEVINE:if(this.pssh=i,!this.keyId){const r=X8(i.buffer);if(r.length){var n;const o=r[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=N2(t));break;case Qs.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=W8(r,null,i),this.keyId=OD(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const o=new Uint8Array(16);o.set(r,16-r.length),r=o}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=q6(t),r||(r=N2(t),r||(r=$u[this.uri])),r&&(this.keyId=r,qo.setKeyIdForUri(this.uri,r))}return this}}function q6(s){const e=s?.[Qs.WIDEVINE];return e?e.keyId:null}function N2(s){const e=s?.[Qs.PLAYREADY];if(e){const t=ID(e.uri);if(t)return OD(t)}return null}function K6(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const O2=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,M2=/#EXT-X-MEDIA:(.*)/g,Y6=/^#EXT(?:INF|-X-TARGETDURATION):/m,iv=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),W6=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class aa{static findGroup(e,t){for(let i=0;i0&&r.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:o.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(M2.lastIndex=0;(n=M2.exec(e))!==null;){const d=new cs(n[1],i),f=d.TYPE;if(f){const p=u[f],g=r[f]||[];r[f]=g;const y=d.LANGUAGE,x=d["ASSOC-LANGUAGE"],_=d.CHANNELS,w=d.CHARACTERISTICS,D=d["INSTREAM-ID"],I={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||y||"",type:f,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:y,url:d.URI?aa.resolve(d.URI,t):""};if(x&&(I.assocLang=x),_&&(I.channels=_),w&&(I.characteristics=w),D&&(I.instreamId=D),p!=null&&p.length){const L=aa.findGroup(p,I.groupId)||p[0];U2(I,L,"audioCodec"),U2(I,L,"textCodec")}g.push(I)}}return r}static parseLevelPlaylist(e,t,i,n,r,o){var u;const c={url:t},d=new $6(t),f=d.fragments,p=[];let g=null,y=0,x=0,_=0,w=0,D=0,I=null,L=new Zy(n,c),B,j,V,M=-1,z=!1,O=null,N;if(iv.lastIndex=0,d.m3u8=e,d.hasVariableRefs=D2(e),((u=iv.exec(e))==null?void 0:u[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(B=iv.exec(e))!==null;){z&&(z=!1,L=new Zy(n,c),L.playlistOffset=_,L.setStart(_),L.sn=y,L.cc=w,D&&(L.bitrate=D),L.level=i,g&&(L.initSegment=g,g.rawProgramDateTime&&(L.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),O&&(L.setByteRange(O),O=null)));const re=B[1];if(re){L.duration=parseFloat(re);const Z=(" "+B[2]).slice(1);L.title=Z||null,L.tagList.push(Z?["INF",re,Z]:["INF",re])}else if(B[3]){if(gt(L.duration)){L.playlistOffset=_,L.setStart(_),V&&$2(L,V,d),L.sn=y,L.level=i,L.cc=w,f.push(L);const Z=(" "+B[3]).slice(1);L.relurl=yx(d,Z),xx(L,I,p),I=L,_+=L.duration,y++,x=0,z=!0}}else{if(B=B[0].match(W6),!B){Mi.warn("No matches on slow regex match for level playlist!");continue}for(j=1;j0&&H2(d,Z,B),y=d.startSN=parseInt(H);break;case"SKIP":{d.skippedSegments&&Ma(d,Z,B);const ie=new cs(H,d),te=ie.decimalInteger("SKIPPED-SEGMENTS");if(gt(te)){d.skippedSegments+=te;for(let $=te;$--;)f.push(null);y+=te}const ne=ie.enumeratedString("RECENTLY-REMOVED-DATERANGES");ne&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(ne.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&Ma(d,Z,B),d.targetduration=Math.max(parseInt(H),1);break;case"VERSION":d.version!==null&&Ma(d,Z,B),d.version=parseInt(H);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||Ma(d,Z,B),d.live=!1;break;case"#":(H||K)&&L.tagList.push(K?[H,K]:[H]);break;case"DISCONTINUITY":w++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([Z]);break;case"BITRATE":L.tagList.push([Z,H]),D=parseInt(H)*1e3,gt(D)?L.bitrate=D:D=0;break;case"DATERANGE":{const ie=new cs(H,d),te=new LD(ie,d.dateRanges[ie.ID],d.dateRangeTagCount);d.dateRangeTagCount++,te.isValid||d.skippedSegments?d.dateRanges[te.id]=te:Mi.warn(`Ignoring invalid DATERANGE tag: "${H}"`),L.tagList.push(["EXT-X-DATERANGE",H]);break}case"DEFINE":{{const ie=new cs(H,d);"IMPORT"in ie?M6(d,ie,o):L2(d,ie,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?Ma(d,Z,B):f.length>0&&H2(d,Z,B),d.startCC=w=parseInt(H);break;case"KEY":{const ie=P2(H,t,d);if(ie.isSupported()){if(ie.method==="NONE"){V=void 0;break}V||(V={});const te=V[ie.keyFormat];te!=null&&te.matches(ie)||(te&&(V=$i({},V)),V[ie.keyFormat]=ie)}else Mi.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${H}"`);break}case"START":d.startTimeOffset=B2(H);break;case"MAP":{const ie=new cs(H,d);if(L.duration){const te=new Zy(n,c);j2(te,ie,i,V),g=te,L.initSegment=g,g.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=g.rawProgramDateTime)}else{const te=L.byteRangeEndOffset;if(te){const ne=L.byteRangeStartOffset;O=`${te-ne}@${ne}`}else O=null;j2(L,ie,i,V),g=L,z=!0}g.cc=w;break}case"SERVER-CONTROL":{N&&Ma(d,Z,B),N=new cs(H),d.canBlockReload=N.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=N.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&N.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=N.optionalFloat("PART-HOLD-BACK",0),d.holdBack=N.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&Ma(d,Z,B);const ie=new cs(H);d.partTarget=ie.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ie=d.partList;ie||(ie=d.partList=[]);const te=x>0?ie[ie.length-1]:void 0,ne=x++,$=new cs(H,d),ee=new M8($,L,c,ne,te);ie.push(ee),L.duration+=ee.duration;break}case"PRELOAD-HINT":{const ie=new cs(H,d);d.preloadHint=ie;break}case"RENDITION-REPORT":{const ie=new cs(H,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ie);break}default:Mi.warn(`line parsed but not handled: ${B}`);break}}}I&&!I.relurl?(f.pop(),_-=I.duration,d.partList&&(d.fragmentHint=I)):d.partList&&(xx(L,I,p),L.cc=w,d.fragmentHint=L,V&&$2(L,V,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const q=f.length,Q=f[0],Y=f[q-1];if(_+=d.skippedSegments*d.targetduration,_>0&&q&&Y){d.averagetargetduration=_/q;const re=Y.sn;d.endSN=re!=="initSegment"?re:0,d.live||(Y.endList=!0),M>0&&(Q6(f,M),Q&&p.unshift(Q))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,p.length&&d.dateRangeTagCount&&Q&&MD(p,d),d.endCC=w,d}}function MD(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){const u=e.fragments[e.fragments.length-1];s.push(u),t++}else return;const i=s[t-1],n=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let u=r.length;u--;){const c=e.dateRanges[r[u]],d=c.startDate.getTime();c.tagAnchor=i.ref;for(let f=t;f--;){var o;if(((o=s[f])==null?void 0:o.sn)=u||i===0){var o;const c=(((o=t[i+1])==null?void 0:o.start)||n)-r.start;if(e<=u+c*1e3){const d=t[i].sn-s.startSN;if(d<0)return-1;const f=s.fragments;if(f.length>t.length){const g=(t[i+1]||f[f.length-1]).sn-s.startSN;for(let y=g;y>d;y--){const x=f[y].programDateTime;if(e>=x&&ei);["video","audio","text"].forEach(i=>{const n=t.filter(r=>Lb(r,i));n.length&&(e[`${i}Codec`]=n.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>n.indexOf(r)===-1))}),e.unknownCodecs=t}function U2(s,e,t){const i=e[t];i&&(s[t]=i)}function Q6(s,e){let t=s[e];for(let i=e;i--;){const n=s[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function xx(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function j2(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function $2(s,e,t){s.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(s)}function Ma(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function H2(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function sv(s,e){const t=e.startPTS;if(gt(t)){let i=0,n;e.sn>s.sn?(i=t-s.start,n=s):(i=s.start-t,n=e),n.duration!==i&&n.setDuration(i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0))}function PD(s,e,t,i,n,r,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,r=n+e.duration);let c=t,d=i;const f=e.startPTS,p=e.endPTS;if(gt(f)){const D=Math.abs(f-t);s&&D>s.totalduration?o.warn(`media timestamps and playlist times differ by ${D}s for level ${e.level} ${s.url}`):gt(e.deltaPTS)?e.deltaPTS=Math.max(D,e.deltaPTS):e.deltaPTS=D,c=Math.max(t,f),t=Math.min(t,f),n=e.startDTS!==void 0?Math.min(n,e.startDTS):n,d=Math.min(i,p),i=Math.max(i,p),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const g=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=n,e.endPTS=i,e.minEndPTS=d,e.endDTS=r;const y=e.sn;if(!s||ys.endSN)return 0;let x;const _=y-s.startSN,w=s.fragments;for(w[_]=e,x=_;x>0;x--)sv(w[x],w[x-1]);for(x=_;x=0;f--){const p=n[f].initSegment;if(p){i=p;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;tU(s,e,(f,p,g,y)=>{if((!e.startCC||e.skippedSegments)&&p.cc!==f.cc){const x=f.cc-p.cc;for(let _=g;_{var p;f&&(!f.initSegment||f.initSegment.relurl===((p=i)==null?void 0:p.relurl))&&(f.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(f=>!f),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let f=e.skippedSegments;f--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=J6(s.dateRanges,e,t));const f=s.fragments.filter(p=>p.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let p=1;p{p.elementaryStreams=f.elementaryStreams,p.stats=f.stats}),r?PD(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):BD(s,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const f=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=f),e.driftEndTime=d,e.driftEnd=f}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function J6(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=$i({},s);n&&n.forEach(c=>{delete r[c]});const u=Object.keys(r).length;return u?(Object.keys(i).forEach(c=>{const d=r[c],f=new LD(i[c].attr,d);f.isValid?(r[c]=f,d||(f.tagOrder+=u)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Yi(i[c].attr)}"`)}),r):i}function eU(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const o=s[n],u=e[n+i];o&&u&&o.index===u.index&&o.fragment.sn===u.fragment.sn?t(o,u):i--}}}function tU(s,e,t){const i=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,r=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,o=e.startSN-s.startSN,u=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=n;d<=r;d++){const f=c[o+d];let p=u[d];if(i&&!p&&f&&(p=e.fragments[d]=f),f&&p){t(f,p,d,u);const g=f.relurl,y=p.relurl;if(g&&iU(g,y)){e.playlistParsingError=V2(`media sequence mismatch ${p.sn}:`,s,e,f,p);return}else if(f.cc!==p.cc){e.playlistParsingError=V2(`discontinuity sequence mismatch (${f.cc}!=${p.cc})`,s,e,f,p);return}}}}function V2(s,e,t,i,n){return new Error(`${s} ${n.url} +Playlist starting @${e.startSN} +${e.m3u8} + +Playlist starting @${t.startSN} +${t.m3u8}`)}function BD(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let o=0;if(r&&ie){const r=i[i.length-1].duration*1e3;r{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function iU(s,e){return s!==e&&e?z2(s)!==z2(e):!1}function z2(s){return s.replace(/\?[^?]*$/,"")}function ah(s,e){for(let i=0,n=s.length;is.startCC)}function q2(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function HD(s,e){const t=e.fragments;for(let i=0,n=t.length;i{const{config:o,fragCurrent:u,media:c,mediaBuffer:d,state:f}=this,p=c?c.currentTime:0,g=Yt.bufferInfo(d||c,p,o.maxBufferHole),y=!g.len;if(this.log(`Media seeking to ${gt(p)?p.toFixed(3):p}, state: ${f}, ${y?"out of":"in"} buffer`),this.state===ze.ENDED)this.resetLoadingState();else if(u){const x=o.maxFragLookUpTolerance,_=u.start-x,w=u.start+u.duration+x;if(y||wg.end){const D=p>w;(p<_||D)&&(D&&u.loader&&(this.log(`Cancelling fragment load for seek (sn: ${u.sn})`),u.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(p,1/0,this.playlistType,!0);const x=this.lastCurrentTime;if(p>x&&(this.lastCurrentTime=p),!this.loadingParts){const _=Math.max(g.end,p),w=this.shouldLoadParts(this.getLevelDetails(),_);w&&(this.log(`LL-Part loading ON after seeking to ${p.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=w)}}this.hls.hasEnoughToStart||(this.log(`Setting ${y?"startPosition":"nextLoadPosition"} to ${p} for seek without enough to start`),this.nextLoadPosition=p,y&&(this.startPosition=p)),y&&this.state===ze.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new N6(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Nb(e.config)}registerListeners(){const{hls:e}=this;e.on(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(U.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(U.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===ze.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ze.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=Yt.bufferedInfo(r,e.start,0));const o=e.nextStart;if(o&&o>n&&o{const o=r.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(o,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const o=this.state,u=r.frag;if(this.fragContextChanged(u)){(o===ze.FRAG_LOADING||!this.fragCurrent&&o===ze.PARSING)&&(this.fragmentTracker.removeFragment(u),this.state=ze.IDLE);return}"payload"in r&&(this.log(`Loaded ${u.type} sn: ${u.sn} of ${this.playlistLabel()} ${u.level}`),this.hls.trigger(U.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===ze.STOPPED||this.state===ze.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Ps.APPENDING){const r=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,r),u=Math.max(e.duration,o?o.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(u,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ps.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(U.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i?.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:r,payload:o}=i,u=r.decryptdata;if(o&&o.byteLength>0&&u!=null&&u.key&&u.iv&&cc(u.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),u.key.buffer,u.iv.buffer,Mb(u.method)).catch(d=>{throw n.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),d}).then(d=>{const f=self.performance.now();return n.trigger(U.FRAG_DECRYPTED,{frag:r,payload:d,stats:{tstart:c,tdecrypt:f}}),i.payload=d,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===ze.STOPPED||this.state===ze.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==ze.STOPPED&&(this.state=ze.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,n;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(n=r.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const o=this.media,u=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${o?"attached mediaKeys: "+o.mediaKeys:"detached"})`);return this.warn(u.message),!o||o.mediaKeys?!1:(this.hls.trigger(U.ERROR,{type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_NO_KEYS,fatal:!1,error:u,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?rU.toString(Yt.getBuffered(i)):"(detached)"})`),Ss(e)){var n;if(e.type!==_t.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(u=>!!o[u])){this.state=ze.IDLE;return}}const r=(n=this.levels)==null?void 0:n[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=ze.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,o=!r||r.length===0||r.some(c=>!c),u=new Ob(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(u)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;this.fragCurrent=e;const o=t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let u=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=ze.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(g=>{if(!this.fragContextChanged(g.frag))return this.hls.trigger(U.KEY_LOADED,g),this.state===ze.KEY_LOADING&&(this.state=ze.IDLE),g}),this.hls.trigger(U.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(u=this.keyLoader.loadClear(e,o.encryptedFragments,this.startFragRequested),u&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(Ss(e)&&(!c||e.sn!==c.sn)){const g=this.shouldLoadParts(t.details,e.end);g!==this.loadingParts&&(this.log(`LL-Part loading ${g?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=g)}if(i=Math.max(e.start,i||0),this.loadingParts&&Ss(e)){const g=o.partList;if(g&&n){i>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);const y=this.getNextPart(g,e,i);if(y>-1){const x=g[y];e=this.fragCurrent=x.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${x.index} (${y}/${g.length-1}) of ${this.fragInfo(e,!1,x)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=x.start+x.duration,this.state=ze.FRAG_LOADING;let _;return u?_=u.then(w=>!w||this.fragContextChanged(w.frag)?null:this.doFragPartsLoad(e,x,t,n)).catch(w=>this.handleFragLoadError(w)):_=this.doFragPartsLoad(e,x,t,n).catch(w=>this.handleFragLoadError(w)),this.hls.trigger(U.FRAG_LOADING,{frag:e,part:x,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):_}else if(!e.url||this.loadedEndOfParts(g,i))return Promise.resolve(null)}}if(Ss(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=o.partList)==null?void 0:d.filter(g=>g.loaded).map(g=>`[${g.start}-${g.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),gt(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=ze.FRAG_LOADING;const f=this.config.progressive&&e.type!==_t.SUBTITLE;let p;return f&&u?p=u.then(g=>!g||this.fragContextChanged(g.frag)?null:this.fragmentLoader.load(e,n)).catch(g=>this.handleFragLoadError(g)):p=Promise.all([this.fragmentLoader.load(e,f?n:void 0),u]).then(([g])=>(!f&&n&&n(g),g)).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(U.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):p}doFragPartsLoad(e,t,i,n){return new Promise((r,o)=>{var u;const c=[],d=(u=i.details)==null?void 0:u.partList,f=p=>{this.fragmentLoader.loadPart(e,p,n).then(g=>{c[p.index]=g;const y=g.part;this.hls.trigger(U.FRAG_LOADED,g);const x=G2(i.details,e.sn,p.index+1)||jD(d,e.sn,p.index+1);if(x)f(x);else return r({frag:e,part:y,partsLoaded:c})}).catch(o)};f(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===we.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Lt.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(U.ERROR,t)}else this.hls.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==ze.PARSING){!this.fragCurrent&&this.state!==ze.STOPPED&&this.state!==ze.ERROR&&(this.state=ze.IDLE);return}const{frag:i,part:n,level:r}=t,o=self.performance.now();i.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const u=this.getLevelDetails(),d=u&&i.sn>u.endSN||this.shouldLoadParts(u,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(i,n,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===_t.SUBTITLE)return!1;const o=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:r,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const u=t[n],c=u.details,d=o>-1?G2(c,r,o):null,f=d?d.fragment:UD(c,r,i);return f?(i&&i!==f&&(f.stats=i.stats),{frag:f,part:d,level:u}):null}bufferFragmentData(e,t,i,n,r){if(this.state!==ze.PARSING)return;const{data1:o,data2:u}=e;let c=o;if(u&&(c=fr(o,u)),!c.length)return;const d=this.initPTS[t.cc],f=d?-d.baseTime/d.timescale:void 0,p={type:e.type,frag:t,part:i,chunkMeta:n,offset:f,parent:t.type,data:c};if(this.hls.trigger(U.BUFFER_APPENDING,p),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Yt.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=Yt.bufferInfo(t,i,0),r=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),u=Math.max(Math.min(e.start-o,n.end-o),i+o);e.start-u>o&&this.flushMainBuffer(u,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!gt(n))return null;const o=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,i,n){const r=Yt.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&(r.nextStart<=o.end||o.gap)){const u=Math.max(Math.min(r.nextStart,o.end)-t,n);return Yt.bufferInfo(e,t,u)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return r>=n?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=_t.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:r}=this,o=i[0].start,u=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const p=r.initialLiveManifestSize;if(n=o?g:y)||c.start:e;this.log(`Setting startPosition to ${x} to match start frag at live edge. mainStart: ${g} liveSyncPosition: ${y} frag.start: ${(d=c)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=x}}else e<=o&&(c=i[0]);if(!c){const p=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,p,t)}let f=this.filterReplacedPrimary(c,t);if(!f&&c){const p=c.sn-t.startSN;f=this.filterReplacedPrimary(i[p+1]||null,t)}return this.mapToInitFragWhenRequired(f)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Ps.OK||i===Ps.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,r){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){const u=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(u!==null&&i.len+u.len>=r){const c=o.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(K2(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(K2(this.config)&&e.type!==_t.SUBTITLE){const i=this.hls.interstitialsManager,n=i?.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&t?.live===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const r=i?.playerQueue;if(r)for(let o=r.length;o--;){const u=r[o].interstitial;if(u.appendInPlace&&e.start>=u.startTime&&e.end<=u.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,r=!1,o=!0;for(let u=0,c=e.length;u-1&&ii.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=T6(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const o=t[r-e.startSN];i.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=wD(e,i.cc,i.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(n=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:o,endSN:u}=i;const{fragmentHint:c}=i,{maxFragLookUpTolerance:d}=n,f=i.partList,p=!!(this.loadingParts&&f!=null&&f.length&&c);p&&!this.bitrateTest&&f[f.length-1].fragment.sn===c.sn&&(o=o.concat(c),u=c.sn);let g;if(et-d||(y=this.media)!=null&&y.paused||!this.startFragRequested?0:d;g=Yl(r,o,e,_)}else g=o[o.length-1];if(g){const x=g.sn-i.startSN,_=this.fragmentTracker.getState(g);if((_===Ps.OK||_===Ps.PARTIAL&&g.gap)&&(r=g),r&&g.sn===r.sn&&(!p||f[0].fragment.sn>g.sn||!i.live)&&g.level===r.level){const D=o[x+1];g.sn${e.startSN} fragments: ${n}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ss(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==ze.FRAG_LOADING_WAITING_RETRY)&&(this.state=ze.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const D=this.getCurrentContext(t.chunkMeta);D&&(t.frag=D.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var r;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const o=t.details===we.FRAG_GAP;o&&this.fragmentTracker.fragBuffered(n,!0);const u=t.errorAction;if(!u){this.state=ze.ERROR;return}const{action:c,flags:d,retryCount:f=0,retryConfig:p}=u,g=!!p,y=g&&c===Ys.RetryRequest,x=g&&!u.resolved&&d===Xn.MoveAllAlternatesMatchingHost,_=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!y&&x&&Ss(n)&&!n.endList&&_&&!CD(t))this.resetFragmentErrors(e),this.treatAsGap(n),u.resolved=!0;else if((y||x)&&f=t||i&&!gx(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ze.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===ze.PARSING||this.state===ze.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len,t?.duration||10);const o=!r;return o&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===_t.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ze.STOPPED&&(this.state=ze.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=Yt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===ze.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ze.STOPPED&&(this.state=ze.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const r=i.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,d)=>{const f=e.elementaryStreams[d];if(f){const p=f.endPTS-f.startPTS;if(p<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${p})`),c||!1;const g=n?0:PD(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this);return this.hls.trigger(U.LEVEL_PTS_UPDATED,{details:r,level:i,drift:g,type:d,frag:e,start:f.startPTS,end:f.endPTS}),!0}return c},!1)){var u;const c=((u=this.transmuxer)==null?void 0:u.error)===null;if((i.fragmentError===0||c&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),c){const d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=ze.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(U.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===_t.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function K2(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class GD{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=aU(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function aU(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n0)return s.subarray(t,t+i)}function fU(s,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],o=r>>2&15;if(o>12){const y=new Error(`invalid ADTS sampling index:${o}`);s.emit(U.ERROR,U.ERROR,{type:Lt.MEDIA_ERROR,details:we.FRAG_PARSING_ERROR,fatal:!0,error:y,reason:y.message});return}const u=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,d="mp4a.40."+u,f=n[o];let p=o;(u===5||u===29)&&(p-=3);const g=[u<<3|(p&14)>>1,(p&1)<<7|c<<3];return Mi.log(`manifest codec:${i}, parsed codec:${d}, channels:${c}, rate:${f} (ADTS object type:${u} sampling index:${o})`),{config:g,samplerate:f,channelCount:c,codec:d,parsedCodec:d,manifestCodec:i}}function qD(s,e){return s[e]===255&&(s[e+1]&246)===240}function KD(s,e){return s[e+1]&1?7:9}function jb(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function mU(s,e){return e+5=s.length)return!1;const i=jb(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||wp(s,n)}return!1}function YD(s,e,t,i,n){if(!s.samplerate){const r=fU(e,t,i,n);if(!r)return;$i(s,r)}}function WD(s){return 1024*9e4/s}function yU(s,e){const t=KD(s,e);if(e+t<=s.length){const i=jb(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function XD(s,e,t,i,n){const r=WD(s.samplerate),o=i+n*r,u=yU(e,t);let c;if(u){const{frameLength:p,headerLength:g}=u,y=g+p,x=Math.max(0,t+y-e.length);x?(c=new Uint8Array(y-g),c.set(e.subarray(t+g,e.length),0)):c=e.subarray(t+g,t+y);const _={unit:c,pts:o};return x||s.samples.push(_),{sample:_,length:y,missing:x}}const d=e.length-t;return c=new Uint8Array(d),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:o},length:d,missing:-1}}function vU(s,e){return Ub(s,e)&&o0(s,e+6)+10<=s.length-e}function xU(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function rv(s,e=0,t=1/0){return bU(s,e,t,Uint8Array)}function bU(s,e,t,i){const n=TU(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const o=_U(s)?s.byteOffset:0,u=(o+s.byteLength)/r,c=(o+e)/r,d=Math.floor(Math.max(0,Math.min(c,u))),f=Math.floor(Math.min(d+Math.max(t,0),u));return new i(n,d,f-d)}function TU(s){return s instanceof ArrayBuffer?s:s.buffer}function _U(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function SU(s){const e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=s.data.subarray(1).indexOf(0);if(i===-1)return;const n=er(rv(s.data,1,i)),r=s.data[2+i],o=s.data.subarray(3+i).indexOf(0);if(o===-1)return;const u=er(rv(s.data,3+i,o));let c;return n==="-->"?c=er(rv(s.data,4+i+o)):c=xU(s.data.subarray(4+i+o)),e.mimeType=n,e.pictureType=r,e.description=u,e.data=c,e}function EU(s){if(s.size<2)return;const e=er(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function wU(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=er(s.data.subarray(t),!0);t+=i.length+1;const n=er(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=er(s.data.subarray(1));return{key:s.type,info:"",data:e}}function AU(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=er(s.data.subarray(t),!0);t+=i.length+1;const n=er(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=er(s.data);return{key:s.type,info:"",data:e}}function CU(s){return s.type==="PRIV"?EU(s):s.type[0]==="W"?AU(s):s.type==="APIC"?SU(s):wU(s)}function kU(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=o0(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const ym=10,DU=10;function QD(s){let e=0;const t=[];for(;Ub(s,e);){const i=o0(s,e+6);s[e+5]>>6&1&&(e+=ym),e+=ym;const n=e+i;for(;e+DU0&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY});n{if(gt(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let vm=null;const IU=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],NU=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],OU=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],MU=[0,1,1,4];function JD(s,e,t,i,n){if(t+24>e.length)return;const r=eL(e,t);if(r&&t+r.frameLength<=e.length){const o=r.samplesPerFrame*9e4/r.sampleRate,u=i+n*o,c={unit:e.subarray(t,t+r.frameLength),pts:u,dts:u};return s.config=[],s.channelCount=r.channelCount,s.samplerate=r.sampleRate,s.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function eL(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,n=s[e+2]>>4&15,r=s[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&r!==3){const o=s[e+2]>>1&1,u=s[e+3]>>6,c=t===3?3-i:i===3?3:4,d=IU[c*14+n-1]*1e3,p=NU[(t===3?0:t===2?1:2)*3+r],g=u===3?1:2,y=OU[t][i],x=MU[i],_=y*8*x,w=Math.floor(y*d/p+o)*x;if(vm===null){const L=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);vm=L?parseInt(L[1]):0}return vm&&vm<=87&&i===2&&d>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:p,channelCount:g,frameLength:w,samplesPerFrame:_}}}function Vb(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function tL(s,e){return e+1{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=s[e];const u=Math.min(i,8),c=8-u;r[0]=4278190080>>>24+c<>c,t=t?t<e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const u=[48e3,44100,32e3][r],c=e[t+4]&63,f=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+r]*2;if(t+f>e.length)return-1;const p=e[t+6]>>5;let g=0;p===2?g+=2:(p&1&&p!==1&&(g+=2),p&4&&(g+=2));const y=(e[t+6]<<8|e[t+7])>>12-g&1,_=[2,1,2,3,3,4,4,5][p]+y,w=e[t+5]>>3,D=e[t+5]&7,I=new Uint8Array([r<<6|w<<1|D>>2,(D&3)<<6|p<<3|y<<2|c>>4,c<<4&224]),L=1536/u*9e4,B=i+n*L,j=e.subarray(t,t+f);return s.config=I,s.channelCount=_,s.samplerate=u,s.samples.push({unit:j,pts:B}),f}class UU extends Hb{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=bh(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&$b(t)!==void 0&&sL(e,i)<=16)return!1;for(let n=e.length;i{const o=K8(r);if(jU.test(o.schemeIdUri)){const u=W2(o,t);let c=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=o.payload;i.samples.push({data:d,len:d.byteLength,dts:u,pts:u,type:Zn.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const u=W2(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:u,pts:u,type:Zn.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function W2(s,e){return gt(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class HU{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Nb(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Qo.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const r=n.subarray(16,n.length-n.length%16),o=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(o).then(u=>{const c=new Uint8Array(u);n.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let r=32;r{r.data=this.getAvcDecryptedUnit(o,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)}).catch(n)}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const r=e[t].units;for(;!(i>=r.length);i++){const o=r[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,n,o),!this.decrypter.isSync()))return}}}}class rL{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;n=r[r.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const r=i[n-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let r=e.naluState||0;const o=r,u=[];let c=0,d,f,p,g=-1,y=0;for(r===-1&&(g=0,y=this.getNALuType(t,0),r=0,c=1);c=0){const x={data:t.subarray(g,f),type:y};u.push(x)}else{const x=this.getLastNalUnit(e.samples);x&&(o&&c<=4-o&&x.state&&(x.data=x.data.subarray(0,x.data.byteLength-o)),f>0&&(x.data=fr(x.data,t.subarray(0,f)),x.state=0))}c=0&&r>=0){const x={data:t.subarray(g,n),type:y,state:r};u.push(x)}if(u.length===0){const x=this.getLastNalUnit(e.samples);x&&(x.data=fr(x.data,t))}return e.naluState=r,u}}class oh{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,n=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");n.set(e.subarray(i,i+r)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&Mi.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class VU extends rL{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let o=this.VideoSample,u,c=!1;i.data=null,o&&r.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(d=>{var f,p;switch(d.type){case 1:{let _=!1;u=!0;const w=d.data;if(c&&w.length>4){const D=this.readSliceType(w);(D===2||D===4||D===7||D===9)&&(_=!0)}if(_){var g;(g=o)!=null&&g.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=_;break}case 5:u=!0,(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:{u=!0,Db(d.data,1,i.pts,t.samples);break}case 7:{var y,x;u=!0,c=!0;const _=d.data,w=this.readSPS(_);if(!e.sps||e.width!==w.width||e.height!==w.height||((y=e.pixelRatio)==null?void 0:y[0])!==w.pixelRatio[0]||((x=e.pixelRatio)==null?void 0:x[1])!==w.pixelRatio[1]){e.width=w.width,e.height=w.height,e.pixelRatio=w.pixelRatio,e.sps=[_];const D=_.subarray(1,4);let I="avc1.";for(let L=0;L<3;L++){let B=D[L].toString(16);B.length<2&&(B="0"+B),I+=B}e.codec=I}break}case 8:u=!0,e.pps=[d.data];break;case 9:u=!0,e.audFound=!0,(p=o)!=null&&p.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}o&&u&&o.units.push(d)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new oh(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let o=0;o{var f,p;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,u=!0;break;case 16:case 17:case 18:case 21:if(u=!0,c){var g;(g=o)!=null&&g.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:u=!0,(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:u=!0,Db(d.data,2,i.pts,t.samples);break;case 32:u=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=$i(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(u=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const y=this.readSPS(d.data);e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.codec=y.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const x in y.params)e.params[x]=y.params[x]}this.pushParameterSet(e.sps,d.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(u=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const y=this.readPPS(d.data);for(const x in y)e.params[x]=y[x]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:u=!0,e.audFound=!0,(p=o)!=null&&p.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:u=!1;break}o&&u&&o.units.push(d)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new oh(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new oh(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),r=t.readBoolean(),o=t.readBits(5),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),g=t.readUByte(),y=t.readUByte(),x=t.readUByte(),_=t.readUByte(),w=t.readUByte(),D=t.readUByte(),I=[],L=[];for(let He=0;He0)for(let He=i;He<8;He++)t.readBits(2);for(let He=0;He1&&t.readEG();for(let pt=0;pt0&&yt<16?(ee=Gt[yt-1],le=Ut[yt-1]):yt===255&&(ee=t.readBits(16),le=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Me=t.readBoolean(),Me&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(fe=t.readBits(32),_e=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Ut=t.readBoolean(),ai=t.readBoolean();let Zt=!1;(Ut||ai)&&(Zt=t.readBoolean(),Zt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Zt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let $e=0;$e<=i;$e++){be=t.readBoolean();const ct=be||t.readBoolean();let it=!1;ct?t.readEG():it=t.readBoolean();const Tt=it?1:t.readUEG()+1;if(Ut)for(let Wt=0;Wt>He&1)<<31-He)>>>0;let Re=Vt.toString(16);return o===1&&Re==="2"&&(Re="6"),{codecString:`hvc1.${At}${o}.${Re}.${r?"H":"L"}${D}.B0`,params:{general_tier_flag:r,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[u,c,d,f],general_constraint_indicator_flags:[p,g,y,x,_,w],general_level_idc:D,bit_depth:Q+8,bit_depth_luma_minus8:Q,bit_depth_chroma_minus8:Y,min_spatial_segmentation_idc:$,chroma_format_idc:B,frame_rate:{fixed:be,fps:_e/fe}},width:Ge,height:lt,pixelRatio:[ee,le]}}readPPS(e){const t=new oh(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),r=t.readBoolean();let o=1;return r&&n?o=0:r?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const js=188;class $o{constructor(e,t,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=$o.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(js*5,t-js)+1,n=0;for(;n1&&(o===0&&u>2||c+js>i))return o}else{if(u)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:dD[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=$o.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=$o.createTrack("audio",n),this._id3Track=$o.createTrack("id3"),this._txtTrack=$o.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let r;const o=this._videoTrack,u=this._audioTrack,c=this._id3Track,d=this._txtTrack;let f=o.pid,p=o.pesData,g=u.pid,y=c.pid,x=u.pesData,_=c.pesData,w=null,D=this.pmtParsed,I=this._pmtId,L=e.length;if(this.remainderData&&(e=fr(this.remainderData,e),L=e.length,this.remainderData=null),L>4;let q;if(N>1){if(q=M+5+e[M+4],q===M+js)continue}else q=M+4;switch(O){case f:z&&(p&&(r=Hu(p,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,d,r,!1)),p={data:[],size:0}),p&&(p.data.push(e.subarray(q,M+js)),p.size+=M+js-q);break;case g:if(z){if(x&&(r=Hu(x,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,r);break;case"mp3":this.parseMPEGPES(u,r);break;case"ac3":this.parseAC3PES(u,r);break}x={data:[],size:0}}x&&(x.data.push(e.subarray(q,M+js)),x.size+=M+js-q);break;case y:z&&(_&&(r=Hu(_,this.logger))&&this.parseID3PES(c,r),_={data:[],size:0}),_&&(_.data.push(e.subarray(q,M+js)),_.size+=M+js-q);break;case 0:z&&(q+=e[q]+1),I=this._pmtId=zU(e,q);break;case I:{z&&(q+=e[q]+1);const Q=qU(e,q,this.typeSupported,i,this.observer,this.logger);f=Q.videoPid,f>0&&(o.pid=f,o.segmentCodec=Q.segmentVideoCodec),g=Q.audioPid,g>0&&(u.pid=g,u.segmentCodec=Q.segmentAudioCodec),y=Q.id3Pid,y>0&&(c.pid=y),w!==null&&!D&&(this.logger.warn(`MPEG-TS PMT found at ${M} after unknown PID '${w}'. Backtracking to sync byte @${B} to parse all TS packets.`),w=null,M=B-188),D=this.pmtParsed=!0;break}case 17:case 8191:break;default:w=O;break}}else j++;j>0&&_x(this.observer,new Error(`Found ${j} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=p,u.pesData=x,c.pesData=_;const V={audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};return n&&this.extractRemainingSamples(V),V}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:r}=e,o=i.pesData,u=t.pesData,c=n.pesData;let d;if(o&&(d=Hu(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,d,!0),i.pesData=null)):i.pesData=o,u&&(d=Hu(u,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else u!=null&&u.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=u;c&&(d=Hu(c,this.logger))?(this.parseID3PES(n,d),n.pesData=null):n.pesData=c}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new HU(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new VU:e==="hevc"&&(this.videoParser=new GU))}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:r}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let r=t.data;if(n){this.aacOverFlow=null;const p=n.missing,g=n.sample.unit.byteLength;if(p===-1)r=fr(n.sample.unit,r);else{const y=g-p;n.sample.unit.set(r.subarray(0,p),y),e.samples.push(n.sample),i=n.missing}}let o,u;for(o=i,u=r.length;o0;)u+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=$i({},t,{type:this._videoTrack?Zn.emsg:Zn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Tx(s,e){return((s[e+1]&31)<<8)+s[e+2]}function zU(s,e){return(s[e+10]&31)<<8|s[e+11]}function qU(s,e,t,i,n,r){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=(s[e+1]&15)<<8|s[e+2],c=e+3+u-4,d=(s[e+10]&15)<<8|s[e+11];for(e+=12+d;e0){let g=e+5,y=p;for(;y>2;){s[g]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=f,o.segmentAudioCodec="ac3"));const _=s[g+1]+2;g+=_,y-=_}}break;case 194:case 135:return _x(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),o;case 36:o.videoPid===-1&&(o.videoPid=f,o.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=p+5}return o}function _x(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(U.ERROR,U.ERROR,{type:Lt.MEDIA_ERROR,details:we.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function av(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Hu(s,e){let t=0,i,n,r,o,u;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=fr(c[0],c[1]),c.splice(1,1);if(i=c[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>s.size-6)return null;const f=i[7];f&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,f&64?(u=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-u>60*9e4&&(e.warn(`${Math.round((o-u)/9e4)}s delta between PTS and DTS, align them`),o=u)):u=o),r=i[8];let p=r+9;if(s.size<=p)return null;s.size-=p;const g=new Uint8Array(s.size);for(let y=0,x=c.length;y_){p-=_;continue}else i=i.subarray(p),_-=p,p=0;g.set(i,t),t+=_}return n&&(n-=r+3),{data:g,pts:o,dts:u,len:n}}return null}class KU{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Po=Math.pow(2,32)-1;class Se{static init(){Se.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in Se.types)Se.types.hasOwnProperty(e)&&(Se.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Se.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Se.STTS=Se.STSC=Se.STCO=r,Se.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Se.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Se.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Se.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),u=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);Se.FTYP=Se.box(Se.types.ftyp,o,c,o,u),Se.DINF=Se.box(Se.types.dinf,Se.box(Se.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=i&255,o.set(e,4),n=0,i=8;n>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return Se.box(Se.types.mdia,Se.mdhd(e.timescale||0,e.duration||0),Se.hdlr(e.type),Se.minf(e))}static mfhd(e){return Se.box(Se.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?Se.box(Se.types.minf,Se.box(Se.types.smhd,Se.SMHD),Se.DINF,Se.stbl(e)):Se.box(Se.types.minf,Se.box(Se.types.vmhd,Se.VMHD),Se.DINF,Se.stbl(e))}static moof(e,t,i){return Se.box(Se.types.moof,Se.mfhd(e),Se.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Se.trak(e[t]);return Se.box.apply(null,[Se.types.moov,Se.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(Se.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Se.trex(e[t]);return Se.box.apply(null,[Se.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Po+1)),n=Math.floor(t%(Po+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Se.box(Se.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,r;for(n=0;n>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(r));const u=Se.box(Se.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),c=e.width,d=e.height,f=e.pixelRatio[0],p=e.pixelRatio[1];return Se.box(Se.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u,Se.box(Se.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Se.box(Se.types.pasp,new Uint8Array([f>>24,f>>16&255,f>>8&255,f&255,p>>24,p>>16&255,p>>8&255,p&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return Se.box(Se.types.mp4a,Se.audioStsd(e),Se.box(Se.types.esds,Se.esds(e)))}static mp3(e){return Se.box(Se.types[".mp3"],Se.audioStsd(e))}static ac3(e){return Se.box(Se.types["ac-3"],Se.audioStsd(e),Se.box(Se.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return Se.box(Se.types.stsd,Se.STSD,Se.mp4a(e));if(t==="ac3"&&e.config)return Se.box(Se.types.stsd,Se.STSD,Se.ac3(e));if(t==="mp3"&&e.codec==="mp3")return Se.box(Se.types.stsd,Se.STSD,Se.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return Se.box(Se.types.stsd,Se.STSD,Se.avc1(e));if(t==="hevc"&&e.vps)return Se.box(Se.types.stsd,Se.STSD,Se.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,r=e.height||0,o=Math.floor(i/(Po+1)),u=Math.floor(i%(Po+1));return Se.box(Se.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,u>>24,u>>16&255,u>>8&255,u&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=Se.sdtp(e),n=e.id,r=Math.floor(t/(Po+1)),o=Math.floor(t%(Po+1));return Se.box(Se.types.traf,Se.box(Se.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),Se.box(Se.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,o>>24,o>>16&255,o>>8&255,o&255])),Se.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Se.box(Se.types.trak,Se.tkhd(e),Se.mdia(e))}static trex(e){const t=e.id;return Se.box(Se.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,r=12+16*n,o=new Uint8Array(r);let u,c,d,f,p,g;for(t+=8+r,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),u=0;u>>24&255,d>>>16&255,d>>>8&255,d&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255,p.isLeading<<2|p.dependsOn,p.isDependedOn<<6|p.hasRedundancy<<4|p.paddingValue<<1|p.isNonSync,p.degradPrio&61440,p.degradPrio&15,g>>>24&255,g>>>16&255,g>>>8&255,g&255],12+16*u);return Se.box(Se.types.trun,o)}static initSegment(e){Se.types||Se.init();const t=Se.moov(e);return fr(Se.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let o=r.length;for(let x=0;x>8,i[x][_].length&255]),o),o+=2,u.set(i[x][_],o),o+=i[x][_].length}const d=Se.box(Se.types.hvcC,u),f=e.width,p=e.height,g=e.pixelRatio[0],y=e.pixelRatio[1];return Se.box(Se.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,f&255,p>>8&255,p&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,Se.box(Se.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Se.box(Se.types.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,g&255,y>>24,y>>16&255,y>>8&255,y&255])))}}Se.types=void 0;Se.HDLR_TYPES=void 0;Se.STTS=void 0;Se.STSC=void 0;Se.STCO=void 0;Se.STSZ=void 0;Se.VMHD=void 0;Se.SMHD=void 0;Se.STSD=void 0;Se.FTYP=void 0;Se.DINF=void 0;const aL=9e4;function Gb(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function YU(s,e,t=1,i=!1){return Gb(s,e,1/t,i)}function jd(s,e=!1){return Gb(s,1e3,1/aL,e)}function WU(s,e=1){return Gb(s,aL,1/e)}function X2(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const XU=10*1e3,QU=1024,ZU=1152,JU=1536;let Vu=null,ov=null;function Q2(s,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class Fm extends gr{constructor(e,t,i,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Vu===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Vu=o?parseInt(o[1]):0}if(ov===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);ov=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&X2(t)} > ${e&&X2(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((r,o)=>{let u=o.pts,c=u-r;return c<-4294967296&&(t=!0,u=Qn(u,i),c=u-r),c>0?r:u},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,o,u,c){let d,f,p,g,y,x,_=r,w=r;const D=e.pid>-1,I=t.pid>-1,L=t.samples.length,B=e.samples.length>0,j=u&&L>0||L>1;if((!D||B)&&(!I||j)||this.ISGenerated||u){if(this.ISGenerated){var M,z,O,N;const re=this.videoTrackConfig;(re&&(t.width!==re.width||t.height!==re.height||((M=t.pixelRatio)==null?void 0:M[0])!==((z=re.pixelRatio)==null?void 0:z[0])||((O=t.pixelRatio)==null?void 0:O[1])!==((N=re.pixelRatio)==null?void 0:N[1]))||!re&&j||this.nextAudioTs===null&&B)&&this.resetInitSegment()}this.ISGenerated||(p=this.generateIS(e,t,r,o));const q=this.isVideoContiguous;let Q=-1,Y;if(j&&(Q=e7(t.samples),!q&&this.config.forceKeyFrameOnDiscontinuity))if(x=!0,Q>0){this.warn(`Dropped ${Q} out of ${L} video samples due to a missing keyframe`);const re=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(Q),t.dropped+=Q,w+=(t.samples[0].pts-re)/t.inputTimeScale,Y=w}else Q===-1&&(this.warn(`No keyframe found out of ${L} video samples`),x=!1);if(this.ISGenerated){if(B&&j){const re=this.getVideoStartPts(t.samples),H=(Qn(e.samples[0].pts,re)-re)/t.inputTimeScale;_+=Math.max(0,H),w+=Math.max(0,-H)}if(B){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),p=this.generateIS(e,t,r,o)),f=this.remuxAudio(e,_,this.isAudioContiguous,o,I||j||c===_t.AUDIO?w:void 0),j){const re=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),p=this.generateIS(e,t,r,o)),d=this.remuxVideo(t,w,q,re)}}else j&&(d=this.remuxVideo(t,w,q,0));d&&(d.firstKeyFrame=Q,d.independent=Q!==-1,d.firstKeyFramePTS=Y)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(y=oL(i,r,this._initPTS,this._initDTS)),n.samples.length&&(g=lL(n,r,this._initPTS))),{audio:f,video:d,initSegment:p,independent:x,text:g,id3:y}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let o=Qn(e,r);if(o0?$-1:$].dts&&(I=!0)}I&&o.sort(function($,ee){const le=$.dts-ee.dts,be=$.pts-ee.pts;return le||be}),x=o[0].dts,_=o[o.length-1].dts;const B=_-x,j=B?Math.round(B/(c-1)):y||e.inputTimeScale/30;if(i){const $=x-L,ee=$>j,le=$<-1;if((ee||le)&&(ee?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${jd($,!0)} ms (${$}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${jd(-$,!0)} ms (${$}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!le||L>=o[0].pts||Vu)){x=L;const be=o[0].pts-$;if(ee)o[0].dts=x,o[0].pts=be;else{let fe=!0;for(let _e=0;_ebe&&fe);_e++){const Me=o[_e].pts;if(o[_e].dts-=$,o[_e].pts-=$,_e0?ee.dts-o[$-1].dts:j;if(fe=$>0?ee.pts-o[$-1].pts:j,Me.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ge=Math.floor(Me.maxBufferHole*r),lt=(n?w+n*r:this.nextAudioTs+f)-ee.pts;lt>Ge?(y=lt-et,y<0?y=et:Q=!0,this.log(`It is approximately ${lt/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=et}else y=et}const _e=Math.round(ee.pts-ee.dts);Y=Math.min(Y,y),Z=Math.max(Z,y),re=Math.min(re,fe),H=Math.max(H,fe),u.push(Q2(ee.key,y,be,_e))}if(u.length){if(Vu){if(Vu<70){const $=u[0].flags;$.dependsOn=2,$.isNonSync=0}}else if(ov&&H-re0&&(n&&Math.abs(L-(D+I))<9e3||Math.abs(Qn(_[0].pts,L)-(D+I))<20*f),_.forEach(function(H){H.pts=Qn(H.pts,L)}),!i||D<0){const H=_.length;if(_=_.filter(K=>K.pts>=0),H!==_.length&&this.warn(`Removed ${_.length-H} of ${H} samples (initPTS ${I} / ${o})`),!_.length)return;r===0?D=0:n&&!x?D=Math.max(0,L-I):D=_[0].pts-I}if(e.segmentCodec==="aac"){const H=this.config.maxAudioFramesDrift;for(let K=0,ie=D+I;K<_.length;K++){const te=_[K],ne=te.pts,$=ne-ie,ee=Math.abs(1e3*$/o);if($<=-H*f&&x)K===0&&(this.warn(`Audio frame @ ${(ne/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*$/o)} ms.`),this.nextAudioTs=D=ne-I,ie=ne);else if($>=H*f&&ee0){M+=w;try{V=new Uint8Array(M)}catch(ee){this.observer.emit(U.ERROR,U.ERROR,{type:Lt.MUX_ERROR,details:we.REMUX_ALLOC_ERROR,fatal:!1,error:ee,bytes:M,reason:`fail allocating audio mdat ${M}`});return}g||(new DataView(V.buffer).setUint32(0,M),V.set(Se.types.mdat,4))}else return;V.set(te,w);const $=te.byteLength;w+=$,y.push(Q2(!0,d,$,0)),j=ne}const O=y.length;if(!O)return;const N=y[y.length-1];D=j-I,this.nextAudioTs=D+c*N.duration;const q=g?new Uint8Array(0):Se.moof(e.sequenceNumber++,B/c,$i({},e,{samples:y}));e.samples=[];const Q=(B-I)/o,Y=this.nextAudioTs/o,Z={data1:q,data2:V,startPTS:Q,endPTS:Y,startDTS:Q,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,Z}}function Qn(s,e){let t;if(e===null)return s;for(e4294967296;)s+=t;return s}function e7(s){for(let e=0;eo.pts-u.pts);const r=s.samples;return s.samples=[],{samples:r}}class t7 extends gr{constructor(e,t,i,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:o}=this.initData=mD(e);if(t)H8(e,t);else{const c=r||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(i=Z2(r,qi.AUDIO,this)),o&&(n=Z2(o,qi.VIDEO,this));const u={};r&&o?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:r?u.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}remux(e,t,i,n,r,o){var u,c;let{initPTS:d,lastEndTime:f}=this;const p={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};gt(f)||(f=this.lastEndTime=r||0);const g=t.samples;if(!g.length)return p;const y={initPTS:void 0,timescale:void 0,trackId:void 0};let x=this.initData;if((u=x)!=null&&u.length||(this.generateInitSegment(g),x=this.initData),!((c=x)!=null&&c.length))return this.warn("Failed to generate initSegment."),p;this.emitInitSegment&&(y.tracks=this.initTracks,this.emitInitSegment=!1);const _=G8(g,x,this),w=x.audio?_[x.audio.id]:null,D=x.video?_[x.video.id]:null,I=xm(D,1/0),L=xm(w,1/0),B=xm(D,0,!0),j=xm(w,0,!0);let V=r,M=0;const z=w&&(!D||!d&&L0?this.lastEndTime=q:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Q=!!x.audio,Y=!!x.video;let re="";Q&&(re+="audio"),Y&&(re+="video");const Z=(x.audio?x.audio.encrypted:!1)||(x.video?x.video.encrypted:!1),H={data1:g,startPTS:N,startDTS:N,endPTS:q,endDTS:q,type:re,hasAudio:Q,hasVideo:Y,nb:1,dropped:0,encrypted:Z};p.audio=Q&&!Y?H:void 0,p.video=Y?H:void 0;const K=D?.sampleCount;if(K){const ie=D.keyFrameIndex,te=ie!==-1;H.nb=K,H.dropped=ie===0||this.isVideoContiguous?0:te?ie:K,H.independent=te,H.firstKeyFrame=ie,te&&D.keyFrameStart&&(H.firstKeyFramePTS=(D.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(p.independent=te),this.isVideoContiguous||(this.isVideoContiguous=te),H.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ie}/${K} dropped: ${H.dropped} start: ${H.firstKeyFramePTS||"NA"}`)}return p.initSegment=y,p.id3=oL(i,r,d,d),n.samples.length&&(p.text=lL(n,r,d)),p}}function xm(s,e,t=!1){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function i7(s,e,t,i){if(s===null)return!0;const n=Math.max(i,1),r=e-s.baseTime/s.timescale;return Math.abs(r-t)>n}function Z2(s,e,t){const i=s.codec;return i&&i.length>4?i:e===qi.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?yp(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Fa;try{Fa=self.performance.now.bind(self.performance)}catch{Fa=Date.now}const Um=[{demux:$U,remux:t7},{demux:$o,remux:Fm},{demux:BU,remux:Fm},{demux:UU,remux:Fm}];Um.splice(2,0,{demux:FU,remux:Fm});class J2{constructor(e,t,i,n,r,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=Fa();let o=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:f,trackSwitch:p,accurateTimeOffset:g,timeOffset:y,initSegmentChange:x}=n||u,{audioCodec:_,videoCodec:w,defaultInitPts:D,duration:I,initSegmentData:L}=c,B=s7(o,t);if(B&&cc(B.method)){const z=this.getDecrypter(),O=Mb(B.method);if(z.isSync()){let N=z.softwareDecrypt(o,B.key.buffer,B.iv.buffer,O);if(i.part>-1){const Q=z.flush();N=Q&&Q.buffer}if(!N)return r.executeEnd=Fa(),lv(i);o=new Uint8Array(N)}else return this.asyncResult=!0,this.decryptionPromise=z.webCryptoDecrypt(o,B.key.buffer,B.iv.buffer,O).then(N=>{const q=this.push(N,null,i);return this.decryptionPromise=null,q}),this.decryptionPromise}const j=this.needsProbing(f,p);if(j){const z=this.configureTransmuxer(o);if(z)return this.logger.warn(`[transmuxer] ${z.message}`),this.observer.emit(U.ERROR,U.ERROR,{type:Lt.MEDIA_ERROR,details:we.FRAG_PARSING_ERROR,fatal:!1,error:z,reason:z.message}),r.executeEnd=Fa(),lv(i)}(f||p||x||j)&&this.resetInitSegment(L,_,w,I,t),(f||x||j)&&this.resetInitialTimestamp(D),d||this.resetContiguity();const V=this.transmux(o,B,y,g,i);this.asyncResult=Th(V);const M=this.currentTransmuxState;return M.contiguous=!0,M.discontinuity=!1,M.trackSwitch=!1,r.executeEnd=Fa(),V}flush(e){const t=e.transmuxing;t.executeStart=Fa();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const o=[],{timeOffset:u}=n;if(i){const p=i.flush();p&&o.push(this.push(p.buffer,null,e))}const{demuxer:c,remuxer:d}=this;if(!c||!d){t.executeEnd=Fa();const p=[lv(e)];return this.asyncResult?Promise.resolve(p):p}const f=c.flush(u);return Th(f)?(this.asyncResult=!0,f.then(p=>(this.flushRemux(o,p,e),o))):(this.flushRemux(o,f,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:o,textTrack:u}=t,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===_t.MAIN?"level":"track"} ${i.level}`);const f=this.remuxer.remux(n,r,o,u,d,c,!0,this.id);e.push({remuxResult:f,chunkMeta:i}),i.transmuxing.executeEnd=Fa()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,r){const{demuxer:o,remuxer:u}=this;!o||!u||(o.resetInitSegment(e,t,i,n),u.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,r){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,n,r):o=this.transmuxUnencrypted(e,i,n,r),o}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:o,id3Track:u,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,o,u,c,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let r;for(let p=0,g=Um.length;p0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const lv=s=>({remuxResult:{},chunkMeta:s});function Th(s){return"then"in s&&s.then instanceof Function}class n7{constructor(e,t,i,n,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=n,this.defaultInitPts=r||null}}class r7{constructor(e,t,i,n,r,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=r,this.initSegmentChange=o}}let ew=0;class uL{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=ew++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,f=this.hls;if(!(!f||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var p;const g=(p=this.workerContext)==null?void 0:p.objectURL;g&&self.URL.revokeObjectURL(g);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{f.logger[d.data.logType]&&f.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,f.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===U.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new Fb,this.observer.on(U.FRAG_DECRYPTED,o),this.observer.on(U.ERROR,o);const u=p2(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||uU()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=dU(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=cU());const{worker:f}=this.workerContext;f.addEventListener("message",this.onWorkerMessage),f.addEventListener("error",this.onWorkerError),f.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:t,config:Yi(r)})}catch(f){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,f),this.terminateWorker(),this.error=null,this.transmuxer=new J2(this.observer,u,r,"",t,e.logger)}return}}this.transmuxer=new J2(this.observer,u,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=ew++;const t=this.hls.config,i=p2(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Yi(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),hU(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,r,o,u,c,d,f){var p,g;d.transmuxing.start=self.performance.now();const{instanceNo:y,transmuxer:x}=this,_=o?o.start:r.start,w=r.decryptdata,D=this.frag,I=!(D&&r.cc===D.cc),L=!(D&&d.level===D.level),B=D?d.sn-D.sn:-1,j=this.part?d.part-this.part.index:-1,V=B===0&&d.id>1&&d.id===D?.stats.chunkCount,M=!L&&(B===1||B===0&&(j===1||V&&j<=0)),z=self.performance.now();(L||B||r.stats.parsing.start===0)&&(r.stats.parsing.start=z),o&&(j||!M)&&(o.stats.parsing.start=z);const O=!(D&&((p=r.initSegment)==null?void 0:p.url)===((g=D.initSegment)==null?void 0:g.url)),N=new r7(I,M,c,L,_,O);if(!M||I||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===_t.MAIN?"level":"track"}: ${d.level} id: ${d.id} + discontinuity: ${I} + trackSwitch: ${L} + contiguous: ${M} + accurateTimeOffset: ${c} + timeOffset: ${_} + initSegmentChange: ${O}`);const q=new n7(i,n,t,u,f);this.configureTransmuxer(q)}if(this.frag=r,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:y,cmd:"demux",data:e,decryptdata:w,chunkMeta:d,state:N},e instanceof ArrayBuffer?[e]:[]);else if(x){const q=x.push(e,w,d,N);Th(q)?q.then(Q=>{this.handleTransmuxComplete(Q)}).catch(Q=>{this.transmuxerError(Q,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(q)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);Th(n)?n.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const tw=100;class a7 extends Bb{constructor(e,t,i){super(e,t,i,"audio-stream-controller",_t.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(U.LEVEL_LOADED,this.onLevelLoaded,this),e.on(U.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(U.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(U.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(U.BUFFER_RESET,this.onBufferReset,this),e.on(U.BUFFER_CREATED,this.onBufferCreated,this),e.on(U.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(U.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(U.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(U.FRAG_LOADING,this.onFragLoading,this),e.on(U.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(U.LEVEL_LOADED,this.onLevelLoaded,this),e.off(U.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(U.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(U.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(U.BUFFER_RESET,this.onBufferReset,this),e.off(U.BUFFER_CREATED,this.onBufferCreated,this),e.off(U.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(U.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(U.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(U.FRAG_LOADING,this.onFragLoading,this),e.off(U.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:o}){if(i===_t.MAIN){const u=t.cc,c=this.fragCurrent;if(this.initPTS[u]={baseTime:n,timescale:r,trackId:o},this.log(`InitPTS for cc: ${u} found from main: ${n/r} (${n}/${r}) trackId: ${o}`),this.mainAnchor=t,this.state===ze.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==u)&&this.syncWithAnchor(t,d?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==u?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===ze.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const n=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&n?.cc===t.cc)return;const r=(n||e).cc,o=this.getLevelDetails(),u=this.getLoadPosition(),c=wD(o,r,u);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===ze.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=ze.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(tw),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=ze.IDLE):this.state=ze.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case ze.IDLE:this.doTickIdle();break;case ze.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e?.[t],n=i?.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=ze.WAITING_INIT_PTS}break}case ze.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case ze.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,o=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=ze.FRAG_LOADING;const u=n.flush().buffer,c={frag:t,part:i,payload:u,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,e.frag)}else this.state=ze.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:r}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[r]))return;const u=i[r],c=u.details;if(!c||this.waitForLive(u)||this.waitForCdnTuneIn(c)){this.state=ze.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,qi.AUDIO,_t.AUDIO));const f=this.getFwdBufferInfo(d,_t.AUDIO);if(f===null)return;if(!this.switchingTrack&&this._streamEnded(f,c)){t.trigger(U.BUFFER_EOS,{type:"audio"}),this.state=ze.ENDED;return}const p=f.len,g=t.maxBufferLength,y=c.fragments,x=y[0].start,_=this.getLoadPosition(),w=this.flushing?_:f.end;if(this.switchingTrack&&n){const L=_;c.PTSKnown&&Lx||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=x+.05)}if(p>=g&&!this.switchingTrack&&wI.end){const B=this.fragmentTracker.getFragAtPos(w,_t.MAIN);B&&B.end>I.end&&(I=B,this.mainFragLoading={frag:B,targetBufferTime:null})}if(D.start>I.end)return}this.loadFragment(D,u,w)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new vh(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==ze.STOPPED&&(this.setInterval(tw),this.state=ze.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(U.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:o,groupId:u,track:c}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${c.name}" of "${u}"`);return}const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==ze.STOPPED&&(this.state=ze.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${c.name}" of "${u}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const f=n[o];let p=0;if(r.live||(i=f.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(f.details){var g;p=this.alignPlaylists(r,f.details,(g=this.levelLastLoaded)==null?void 0:g.details)}r.alignedSliding||(VD(r,d),r.alignedSliding||Ep(r,d),p=r.fragmentStart)}f.details=r,this.levelLastLoaded=f,this.startFragRequested||this.setStartPosition(d,p),this.hls.trigger(U.AUDIO_TRACK_UPDATED,{details:r,id:o,groupId:t.groupId}),this.state===ze.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=ze.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:o,trackId:u,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const d=c[u];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const f=d.details;if(!f){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const p=o.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let g=this.transmuxer;g||(g=this.transmuxer=new uL(this.hls,_t.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const y=this.initPTS[i.cc],x=(t=i.initSegment)==null?void 0:t.data;if(y!==void 0){const w=n?n.index:-1,D=w!==-1,I=new Ob(i.level,i.sn,i.stats.chunkCount,r.byteLength,w,D);g.push(r,x,p,"",i,n,f.totalduration,!1,I,y)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${f.startSN} ,${f.endSN}],track ${u}`);const{cache:_}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new GD,complete:!1};_.push(new Uint8Array(r)),this.state!==ze.STOPPED&&(this.state=ze.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===_t.MAIN&&Ss(t.frag)&&(this.mainFragLoading=t,this.state===ze.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==_t.AUDIO){!this.audioOnly&&i.type===_t.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ss(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(U.AUDIO_TRACK_SWITCHED,Oi({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=ze.ERROR;return}switch(t.details){case we.FRAG_GAP:case we.FRAG_PARSING_ERROR:case we.FRAG_DECRYPT_ERROR:case we.FRAG_LOAD_ERROR:case we.FRAG_LOAD_TIMEOUT:case we.KEY_LOAD_ERROR:case we.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(_t.AUDIO,t);break;case we.AUDIO_TRACK_LOAD_ERROR:case we.AUDIO_TRACK_LOAD_TIMEOUT:case we.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===ze.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===di.AUDIO_TRACK&&(this.state=ze.IDLE);break;case we.BUFFER_ADD_CODEC_ERROR:case we.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case we.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case we.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==qi.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==qi.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===ze.ENDED&&(this.state=ze.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,_t.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:o}=e,u=this.getCurrentContext(o);if(!u){this.resetWhenMissingContext(o);return}const{frag:c,part:d,level:f}=u,{details:p}=f,{audio:g,text:y,id3:x,initSegment:_}=r;if(this.fragContextChanged(c)||!p){this.fragmentTracker.removeFragment(c);return}if(this.state=ze.PARSING,this.switchingTrack&&g&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const w=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(f,_.tracks,w,o),n.trigger(U.FRAG_PARSING_INIT_SEGMENT,{frag:w,id:i,tracks:_.tracks})}if(g){const{startPTS:w,endPTS:D,startDTS:I,endDTS:L}=g;d&&(d.elementaryStreams[qi.AUDIO]={startPTS:w,endPTS:D,startDTS:I,endDTS:L}),c.setElementaryStreamInfo(qi.AUDIO,w,D,I,L),this.bufferFragmentData(g,c,d,o)}if(x!=null&&(t=x.samples)!=null&&t.length){const w=$i({id:i,frag:c,details:p},x);n.trigger(U.FRAG_PARSING_METADATA,w)}if(y){const w=$i({id:i,frag:c,details:p},y);n.trigger(U.FRAG_PARSING_USERDATA,w)}}_bufferInitSegment(e,t,i,n){if(this.state!==ze.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=_t.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${o}/${r.codec}]`),o&&o.split(",").length===1&&(r.levelCodec=o),this.hls.trigger(U.BUFFER_CODECS,t);const u=r.initSegment;if(u!=null&&u.byteLength){const c={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:u};this.hls.trigger(U.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===Ps.NOT_LOADED||n===Ps.PARTIAL){var r;if(!Ss(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=ze.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&Ep(t.details,o)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u}=this.bufferedTrack;Gl({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u},e,Nl)||(xp(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(U.AUDIO_TRACK_SWITCHED,Oi({},e))}}class zb extends gr{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t?.renditionReports;if(n){let r=-1;for(let o=0;o=0&&f>t.partTarget&&(c+=1)}const d=i&&g2(i);return new y2(u,c>=0?c:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:r}=t,o=self.performance.now(),u=r.loading.first?Math.max(0,o-r.loading.first):0;n.advancedDateTime=Date.now()-u;const c=this.hls.config.timelineOffset;if(c!==n.appliedTimelineOffset){const f=Math.max(c||0,0);n.appliedTimelineOffset=f,n.fragments.forEach(p=>{p.setStart(p.playlistOffset+f)})}if(n.live||i!=null&&i.live){const f="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){Z6(i,n,this);const I=n.playlistParsingError;if(I){this.warn(I);const L=this.hls;if(!L.config.ignorePlaylistParsingErrors){var d;const{networkDetails:B}=t;L.trigger(U.ERROR,{type:Lt.NETWORK_ERROR,details:we.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:I,reason:I.message,level:t.level||void 0,parent:(d=n.fragments[0])==null?void 0:d.type,networkDetails:B,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const p=this.hls.mainForwardBufferInfo,g=p?p.end-p.len:0,y=(n.edge-g)*1e3,x=FD(n,y);if(n.requestScheduled+x0){if(O>n.targetduration*3)this.log(`Playlist last advanced ${z.toFixed(2)}s ago. Omitting segment and part directives.`),w=void 0,D=void 0;else if(i!=null&&i.tuneInGoal&&O-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${N} with playlist age: ${n.age}`),N=0;else{const q=Math.floor(N/n.targetduration);if(w+=q,D!==void 0){const Q=Math.round(N%n.targetduration/n.partTarget);D+=Q}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${z.toFixed(2)}s goal: ${N} skip sn ${q} to part ${D}`)}n.tuneInGoal=N}if(_=this.getDeliveryDirectives(n,t.deliveryDirectives,w,D),I||!M){n.requestScheduled=o,this.loadingPlaylist(f,_);return}}else(n.canBlockReload||n.canSkipUntil)&&(_=this.getDeliveryDirectives(n,t.deliveryDirectives,w,D));_&&w!==void 0&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(x-u*2,x/2)),this.scheduleLoading(f,_,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const r=self.performance.now(),o=n.requestScheduled;if(r>=o){this.loadingPlaylist(e,t);return}const u=o-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(u)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),u)}getDeliveryDirectives(e,t,i,n){let r=g2(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=Pm.No),new y2(i,n,r)}checkRetry(e){const t=e.details,i=bp(e),n=e.errorAction,{action:r,retryCount:o=0,retryConfig:u}=n||{},c=!!n&&!!u&&(r===Ys.RetryRequest||!n.resolved&&r===Ys.SendAlternateToPenaltyBox);if(c){var d;if(o>=u.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const f=Ib(u,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),f),this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" in ${f}ms`)}e.levelRetry=!0,n.resolved=!0}return c}}function cL(s,e){if(s.length!==e.length)return!1;for(let t=0;ts[n]!==e[n])}function Sx(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class o7 extends zb{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.MANIFEST_PARSED,this.onManifestParsed,this),e.on(U.LEVEL_LOADING,this.onLevelLoading,this),e.on(U.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(U.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(U.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.MANIFEST_PARSED,this.onManifestParsed,this),e.off(U.LEVEL_LOADING,this.onLevelLoading,this),e.off(U.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(U.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(U.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${o?.groupId}`);return}const u=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,u)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||n?.length!==i?.length||i!=null&&i.some(u=>n?.indexOf(u)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const u=this.tracks.filter(g=>!i||i.indexOf(g.groupId)!==-1);if(u.length)this.selectDefaultTrack&&!u.some(g=>g.default)&&(this.selectDefaultTrack=!1),u.forEach((g,y)=>{g.id=y});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const c=this.hls.config.audioPreference;if(!r&&c){const g=ra(c,u,Nl);if(g>-1)r=u[g];else{const y=ra(c,this.tracks);r=this.tracks[y]}}let d=this.findTrackId(r);d===-1&&r&&(d=this.findTrackId(null));const f={audioTracks:u};this.log(`Updating audio tracks, ${u.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(U.AUDIO_TRACKS_UPDATED,f);const p=this.trackId;if(d!==-1&&p===-1)this.setAudioTrack(d);else if(u.length&&p===-1){var o;const g=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${u.length}`);this.warn(g.message),this.hls.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:g})}}}onError(e,t){t.fatal||!t.context||t.context.type===di.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&Gl(e,n,Nl))return n;const r=ra(e,this.tracksInGroup,Nl);if(r>-1){const o=this.tracksInGroup[r];return this.setAudioTrack(r),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const u=x6(e,t.levels,i,o,Nl);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const o=ra(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],r=n.details&&!n.details.live;if(e===this.trackId&&n===i&&r||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(U.AUDIO_TRACK_SWITCHING,Oi({},n)),r))return;const o=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(r){var i;if(n.onError(r),this.queues===null||this.tracks===null)return;const o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"":` +${this.list("video")} +${this.list("audio")} +${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],n=i?.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const iw=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,dL="HlsJsTrackRemovedError";class u7 extends Error{constructor(e){super(e),this.name=dL}}class c7 extends gr{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:n,mediaSource:r}=this;i&&this.log("Media source opened"),!(!n||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(U.MEDIA_ATTACHED,{media:n,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:n}=this;i!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=I8(Xo(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.MANIFEST_PARSED,this.onManifestParsed,this),e.on(U.BUFFER_RESET,this.onBufferReset,this),e.on(U.BUFFER_APPENDING,this.onBufferAppending,this),e.on(U.BUFFER_CODECS,this.onBufferCodecs,this),e.on(U.BUFFER_EOS,this.onBufferEos,this),e.on(U.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(U.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(U.FRAG_PARSED,this.onFragParsed,this),e.on(U.FRAG_CHANGED,this.onFragChanged,this),e.on(U.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.MANIFEST_PARSED,this.onManifestParsed,this),e.off(U.BUFFER_RESET,this.onBufferReset,this),e.off(U.BUFFER_APPENDING,this.onBufferAppending,this),e.off(U.BUFFER_CODECS,this.onBufferCodecs,this),e.off(U.BUFFER_EOS,this.onBufferEos,this),e.off(U.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(U.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(U.FRAG_PARSED,this.onFragParsed,this),e.off(U.FRAG_CHANGED,this.onFragChanged,this),e.off(U.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const o=this.isQueued();(r||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?$i(i,n.tracks):this.sourceBuffers.forEach(r=>{const[o]=r;o&&(i[o]=$i({},this.tracks[o]),this.removeBuffer(o)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const n=Xo(this.appendSource);if(n){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(o),r)this._objectUrl=i.src,this.attachTransferred();else{const u=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");const c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&o instanceof c,sw(i),d7(i,u),i.load()}catch{i.src=u}else i.src=u}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,n=t.tracks,r=n?Object.keys(n):null,o=r?r.length:0,u=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) +required tracks: ${Yi(i,(c,d)=>c==="initSegment"?void 0:d)}; +transfer tracks: ${Yi(n,(c,d)=>c==="initSegment"?void 0:d)}}`),!oD(n,i)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,d=this.details,f=Math.max(c,d?.fragments[0].start||0);if(f-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${f}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${f} currentTime: ${c}`),this.onMediaDetaching(U.MEDIA_DETACHING,{}),this.onMediaAttaching(U.MEDIA_ATTACHING,t),e.currentTime=f;return}this.transferData=void 0,r.forEach(c=>{const d=c,f=n[d];if(f){const p=f.buffer;if(p){const g=this.fragmentTracker,y=f.id;if(g.hasFragments(y)||g.hasParts(y)){const w=Yt.getBuffered(p);g.detectEvictedFragments(d,w,y,null,!0)}const x=uv(d),_=[d,p];this.sourceBuffers[x]=_,p.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,f)}}}),u(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),u()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:r,_objectUrl:o}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([u])=>{u&&this.removeBuffer(u)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const u=r.readyState==="open";try{const c=r.sourceBuffers;for(let d=c.length;d--;)u&&c[d].abort(),r.removeSourceBuffer(c[d]);u&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&sw(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(U.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[uv(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new l7(this.tracks)}onBufferCodecs(e,t){var i;const n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const o="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),u=!o&&this.sourceBufferCount&&this.media&&r.some(c=>!n[c]);if(o||u){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var d,f;const p=t[c],{id:g,codec:y,levelCodec:x,container:_,metadata:w,supplemental:D}=p;let I=n[c];const L=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],B=L!=null&&L.buffer?L:I,j=B?.pendingCodec||B?.codec,V=B?.levelCodec;I||(I=n[c]={buffer:void 0,listeners:[],codec:y,supplemental:D,container:_,levelCodec:x,metadata:w,id:g});const M=Mm(j,V),z=M?.replace(iw,"$1");let O=Mm(y,x);const N=(f=O)==null?void 0:f.replace(iw,"$1");O&&M&&z!==N&&(c.slice(0,5)==="audio"&&(O=yp(O,this.appendSource)),this.log(`switching codec ${j} to ${O}`),O!==(I.pendingCodec||I.codec)&&(I.pendingCodec=O),I.container=_,this.appendChangeType(c,_,O))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,r={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const u=o.buffer;u!=null&&u.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),u.changeType(n),o.codec=i,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,_t.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var u;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&Yt.isBuffered(c.buffer,n)||((u=this.fragmentTracker.getAppendedFrag(n,_t.MAIN))==null?void 0:u.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:u=>{this.warn("Error executing block-audio operation",u)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:r,parent:o,frag:u,part:c,chunkMeta:d,offset:f}=t,p=d.buffering[r],{sn:g,cc:y}=u,x=self.performance.now();p.start=x;const _=u.stats.buffering,w=c?c.stats.buffering:null;_.start===0&&(_.start=x),w&&w.start===0&&(w.start=x);const D=i.audio;let I=!1;r==="audio"&&D?.container==="audio/mpeg"&&(I=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const L=i.video,B=L?.buffer;if(B&&g!=="initSegment"){const M=c||u,z=this.blockedAudioAppend;if(r==="audio"&&o!=="main"&&!this.blockedAudioAppend&&!(L.ending||L.ended)){const N=M.start+M.duration*.05,q=B.buffered,Q=this.currentOp("video");!q.length&&!Q?this.blockAudio(M):!Q&&!Yt.isBuffered(B,N)&&this.lastVideoAppendEndN||O{var M;p.executeStart=self.performance.now();const z=(M=this.tracks[r])==null?void 0:M.buffer;z&&(I?this.updateTimestampOffset(z,j,.1,r,g,y):f!==void 0&>(f)&&this.updateTimestampOffset(z,f,1e-6,r,g,y)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const M=self.performance.now();p.executeEnd=p.end=M,_.first===0&&(_.first=M),w&&w.first===0&&(w.first=M);const z={};this.sourceBuffers.forEach(([O,N])=>{O&&(z[O]=Yt.getBuffered(N))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(U.BUFFER_APPENDED,{type:r,frag:u,part:c,chunkMeta:d,parent:u.type,timeRanges:z})},onError:M=>{var z;const O={type:Lt.MEDIA_ERROR,parent:u.type,details:we.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:u,part:c,chunkMeta:d,error:M,err:M,fatal:!1},N=(z=this.media)==null?void 0:z.error;if(M.code===DOMException.QUOTA_EXCEEDED_ERR||M.name=="QuotaExceededError"||"quota"in M)O.details=we.BUFFER_FULL_ERROR;else if(M.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!N)O.errorAction=uc(!0);else if(M.name===dL&&this.sourceBufferCount===0)O.errorAction=uc(!0);else{const q=++this.appendErrors[r];this.warn(`Failed ${q}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${N||"no media error"})`),(q>=this.hls.config.appendErrorMaxRetry||N)&&(O.fatal=!0)}this.hls.trigger(U.ERROR,O)}};this.log(`queuing "${r}" append sn: ${g}${c?" p: "+c.index:""} of ${u.type===_t.MAIN?"level":"track"} ${u.level} cc: ${y}`),this.append(V,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(U.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:r}=t;i?this.append(this.getFlushOp(i,n,r),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,r),o)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],o=n?n.elementaryStreams:i.elementaryStreams;o[qi.AUDIOVIDEO]?r.push("audiovideo"):(o[qi.AUDIO]&&r.push("audio"),o[qi.VIDEO]&&r.push("video"));const u=()=>{const c=self.performance.now();i.stats.buffering.end=c,n&&(n.stats.buffering.end=c);const d=n?n.stats:i.stats;this.hls.trigger(U.FRAG_BUFFERED,{frag:i,part:n,stats:d,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(u,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){const u=this.tracks[o];(!t.type||t.type===o)&&(u.ending=!0,u.ended||(u.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var u;return o&&!((u=this.tracks[o])!=null&&u.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(U.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(U.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===we.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;gt(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,r=i.currentTime,o=t.levelTargetDuration,u=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(gt(u)&&u>=0){const d=Math.max(u,o),f=Math.floor(r/o)*o-d;this.flushBackBuffer(r,o,f)}const c=n.frontBufferFlushThreshold;if(gt(c)&&c>0){const d=Math.max(n.maxBufferLength,c),f=Math.max(d,o),p=Math.floor(r/o)*o+f;this.flushFrontBuffer(r,o,p)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const u=Yt.getBuffered(r);if(u.length>0&&i>u.start(0)){var o;this.hls.trigger(U.BACK_BUFFER_REACHED,{bufferEnd:i});const c=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(U.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(c!=null&&c.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(U.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const o=Yt.getBuffered(r),u=o.length;if(u<2)return;const c=o.start(u-1),d=o.end(u-1);if(i>c||e>=c&&e<=d)return;this.hls.trigger(U.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const d=Math.max(0,t.fragmentStart),f=Math.max(d,n);return{duration:1/0,start:d,end:f}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return gt(r)?{duration:r}:null;const o=this.media.duration,u=gt(i.duration)?i.duration:0;return n>u&&n>o||!gt(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(gt(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Yi(i)}`),this.tracksReady){var n;const r=(n=this.transferData)==null?void 0:n.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(U.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const o=r,u=e[o];if(this.isPending(u)){const c=this.getTrackCodec(u,o),d=`${u.container};codecs=${c}`;u.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(o)?" Queued":""} ${Yi(u)}`);try{const f=i.addSourceBuffer(d),p=uv(o),g=[o,f];t[p]=g,u.buffer=f}catch(f){var n;this.error(`error while trying to add sourceBuffer: ${f.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:f,sourceBufferName:o,mimeType:d,parent:u.id});return}this.trackSourceBuffer(o,u)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&gh(i,"video")&&(n=e6(n,i));const r=Mm(n,e.levelCodec);return r?t.slice(0,5)==="audio"?yp(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,o)=>{const u=o.removedRanges;u!=null&&u.length&&this.hls.trigger(U.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,o){const u=t-e.timestampOffset;Math.abs(u)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${o})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,o=this.tracks[e],u=o?.buffer;if(!n||!r||!u){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=gt(n.duration)?n.duration:1/0,d=gt(r.duration)?r.duration:1/0,f=Math.max(0,t),p=Math.min(i,c,d);p>f&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${f},${p}] from the ${e} SourceBuffer`),u.remove(f,p)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i?.buffer;if(!n)throw new u7(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const r=n.buffer;if(!r)return;const o=i.bind(this,e);n.listeners.push({event:t,listener:o}),r.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function sw(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function d7(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function uv(s){return s==="audio"?1:0}class qb{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(U.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(U.MANIFEST_PARSED,this.onManifestParsed,this),e.on(U.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(U.BUFFER_CODECS,this.onBufferCodecs,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(U.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(U.MANIFEST_PARSED,this.onManifestParsed,this),e.off(U.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(U.BUFFER_CODECS,this.onBufferCodecs,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&>(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,r)=>this.isLevelAllowed(n)&&r<=e);return this.clientRect=null,qb.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(u,c)=>c?u.width!==c.width||u.height!==c.height:!0;let r=e.length-1;const o=Math.max(t,i);for(let u=0;u=o||c.height>=o)&&n(c,e[u+1])){r=u;break}}return r}}const h7={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Rn=h7,f7={HLS:"h"},m7=f7;class ha{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof ha?i:new ha(i))),this.value=e,this.params=t}}const p7="Dict";function g7(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function y7(s,e,t,i){return new Error(`failed to ${s} "${g7(e)}" as ${t}`,{cause:i})}function fa(s,e,t){return y7("serialize",s,e,t)}class hL{constructor(e){this.description=e}}const nw="Bare Item",v7="Boolean";function x7(s){if(typeof s!="boolean")throw fa(s,v7);return s?"?1":"?0"}function b7(s){return btoa(String.fromCharCode(...s))}const T7="Byte Sequence";function _7(s){if(ArrayBuffer.isView(s)===!1)throw fa(s,T7);return`:${b7(s)}:`}const S7="Integer";function E7(s){return s<-999999999999999||99999999999999912)throw fa(s,A7);const t=e.toString();return t.includes(".")?t:`${t}.0`}const k7="String",D7=/[\x00-\x1f\x7f]+/;function L7(s){if(D7.test(s))throw fa(s,k7);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function R7(s){return s.description||s.toString().slice(7,-1)}const I7="Token";function rw(s){const e=R7(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw fa(e,I7);return e}function Ex(s){switch(typeof s){case"number":if(!gt(s))throw fa(s,nw);return Number.isInteger(s)?fL(s):C7(s);case"string":return L7(s);case"symbol":return rw(s);case"boolean":return x7(s);case"object":if(s instanceof Date)return w7(s);if(s instanceof Uint8Array)return _7(s);if(s instanceof hL)return rw(s);default:throw fa(s,nw)}}const N7="Key";function wx(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw fa(s,N7);return s}function Kb(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${wx(e)}`:`;${wx(e)}=${Ex(t)}`).join("")}function pL(s){return s instanceof ha?`${Ex(s.value)}${Kb(s.params)}`:Ex(s)}function O7(s){return`(${s.value.map(pL).join(" ")})${Kb(s.params)}`}function M7(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw fa(s,p7);const t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof ha||(r=new ha(r));let o=wx(n);return r.value===!0?o+=Kb(r.params):(o+="=",Array.isArray(r.value)?o+=O7(r):o+=pL(r)),o}).join(`,${i}`)}function gL(s,e){return M7(s,e)}const Yr="CMCD-Object",vs="CMCD-Request",Dl="CMCD-Session",Bo="CMCD-Status",P7={br:Yr,ab:Yr,d:Yr,ot:Yr,tb:Yr,tpb:Yr,lb:Yr,tab:Yr,lab:Yr,url:Yr,pb:vs,bl:vs,tbl:vs,dl:vs,ltc:vs,mtp:vs,nor:vs,nrr:vs,rc:vs,sn:vs,sta:vs,su:vs,ttfb:vs,ttfbb:vs,ttlb:vs,cmsdd:vs,cmsds:vs,smrt:vs,df:vs,cs:vs,ts:vs,cid:Dl,pr:Dl,sf:Dl,sid:Dl,st:Dl,v:Dl,msd:Dl,bs:Bo,bsd:Bo,cdn:Bo,rtp:Bo,bg:Bo,pt:Bo,ec:Bo,e:Bo},B7={REQUEST:vs};function F7(s){return Object.keys(s).reduce((e,t)=>{var i;return(i=s[t])===null||i===void 0||i.forEach(n=>e[n]=t),e},{})}function U7(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?F7(e):{};return i.reduce((r,o)=>{var u;const c=P7[o]||n[o]||B7.REQUEST,d=(u=r[c])!==null&&u!==void 0?u:r[c]={};return d[o]=s[o],r},t)}function j7(s){return["ot","sf","st","e","sta"].includes(s)}function $7(s){return typeof s=="number"?gt(s):s!=null&&s!==""&&s!==!1}const yL="event";function H7(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const n=t.pathname.split("/").slice(1),r=i.pathname.split("/").slice(1,-1);for(;n[0]===r[0];)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.join("/")+t.search+t.hash}const jm=s=>Math.round(s),Ax=(s,e)=>Array.isArray(s)?s.map(t=>Ax(t,e)):s instanceof ha&&typeof s.value=="string"?new ha(Ax(s.value,e),s.params):(e.baseUrl&&(s=H7(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),bm=s=>jm(s/100)*100,V7=(s,e)=>{let t=s;return e.version>=2&&(s instanceof ha&&typeof s.value=="string"?t=new ha([s]):typeof s=="string"&&(t=[s])),Ax(t,e)},G7={br:jm,d:jm,bl:bm,dl:bm,mtp:bm,nor:V7,rtp:bm,tb:jm},vL="request",xL="response",Yb=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],z7=["e"],q7=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function l0(s){return q7.test(s)}function K7(s){return Yb.includes(s)||z7.includes(s)||l0(s)}const bL=["d","dl","nor","ot","rtp","su"];function Y7(s){return Yb.includes(s)||bL.includes(s)||l0(s)}const W7=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function X7(s){return Yb.includes(s)||bL.includes(s)||W7.includes(s)||l0(s)}const Q7=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Z7(s){return Q7.includes(s)||l0(s)}const J7={[xL]:X7,[yL]:K7,[vL]:Y7};function TL(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||vL,r=i===1?Z7:J7[n];let o=Object.keys(s).filter(r);const u=e.filter;typeof u=="function"&&(o=o.filter(u));const c=n===xL||n===yL;c&&!o.includes("ts")&&o.push("ts"),i>1&&!o.includes("v")&&o.push("v");const d=$i({},G7,e.formatters),f={version:i,reportingMode:n,baseUrl:e.baseUrl};return o.sort().forEach(p=>{let g=s[p];const y=d[p];if(typeof y=="function"&&(g=y(g,f)),p==="v"){if(i===1)return;g=i}p=="pr"&&g===1||(c&&p==="ts"&&!gt(g)&&(g=Date.now()),$7(g)&&(j7(p)&&typeof g=="string"&&(g=new hL(g)),t[p]=g))}),t}function ej(s,e={}){const t={};if(!s)return t;const i=TL(s,e),n=U7(i,e?.customHeaderMap);return Object.entries(n).reduce((r,[o,u])=>{const c=gL(u,{whitespace:!1});return c&&(r[o]=c),r},t)}function tj(s,e,t){return $i(s,ej(e,t))}const ij="CMCD";function sj(s,e={}){return s?gL(TL(s,e),{whitespace:!1}):""}function nj(s,e={}){if(!s)return"";const t=sj(s,e);return encodeURIComponent(t)}function rj(s,e={}){if(!s)return"";const t=nj(s,e);return`${ij}=${t}`}const aw=/CMCD=[^&#]+/;function aj(s,e,t){const i=rj(e,t);if(!i)return s;if(aw.test(s))return s.replace(aw,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class oj{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=n=>{try{this.apply(n,{ot:Rn.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=n=>{try{const{frag:r,part:o}=n,u=this.hls.levels[r.level],c=this.getObjectType(r),d={d:(o||r).duration*1e3,ot:c};(c===Rn.VIDEO||c===Rn.AUDIO||c==Rn.MUXED)&&(d.br=u.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const f=o?this.getNextPart(o):this.getNextFrag(r);f!=null&&f.url&&f.url!==r.url&&(d.nor=f.url),this.apply(n,d)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(U.MEDIA_DETACHED,this.onMediaDetached,this),e.on(U.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(U.MEDIA_DETACHED,this.onMediaDetached,this),e.off(U.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:m7.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){$i(t,this.createData());const i=t.ot===Rn.INIT||t.ot===Rn.VIDEO||t.ot===Rn.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((o,u)=>(n.includes(u)&&(o[u]=t[u]),o),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),tj(e.headers,t,r)):e.url=aj(e.url,t,r)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t;const{index:i,fragment:n}=e,r=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:o}=n;for(let u=r.length-1;u>=0;u--){const c=r[u];if(c.index===i&&c.fragment.sn===o)return r[u+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Rn.TIMED_TEXT;if(e.sn==="initSegment")return Rn.INIT;if(t==="audio")return Rn.AUDIO;if(t==="main")return this.hls.audioTracks.length?Rn.VIDEO:Rn.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Rn.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,o=r>-1?r+1:n.levels.length;i=n.levels.slice(0,o)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Rn.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Yt.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,u){t(r),this.loader.load(r,o,u)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,u){t(r),this.loader.load(r,o,u)}}}}const lj=3e5;class uj extends gr{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(U.MANIFEST_PARSED,this.onManifestParsed,this),e.on(U.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(U.MANIFEST_PARSED,this.onManifestParsed,this),e.off(U.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if(i?.action===Ys.SendAlternateToPenaltyBox&&i.flags===Xn.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:u,pathwayId:c,type:d}=t.context;u&&n?o=this.getPathwayForGroupId(u,d,o):c&&(o=c)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==o),t.details===we.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${Yi(r)} penalized: ${Yi(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(r=>{n-i[r]>lj&&delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,$D(t),this.hls.trigger(U.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[u];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=u);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r{const{ID:o,"BASE-ID":u,"URI-REPLACEMENT":c}=r;if(t.some(f=>f.pathwayId===o))return;const d=this.getLevelsForPathway(u).map(f=>{const p=new cs(f.attrs);p["PATHWAY-ID"]=o;const g=p.AUDIO&&`${p.AUDIO}_clone_${o}`,y=p.SUBTITLES&&`${p.SUBTITLES}_clone_${o}`;g&&(i[p.AUDIO]=g,p.AUDIO=g),y&&(n[p.SUBTITLES]=y,p.SUBTITLES=y);const x=_L(f.uri,p["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new vh({attrs:p,audioCodec:f.audioCodec,bitrate:f.bitrate,height:f.height,name:f.name,url:x,videoCodec:f.videoCodec,width:f.width});if(f.audioGroups)for(let w=1;w{this.log(`Loaded steering manifest: "${n}"`);const x=f.data;if(x?.VERSION!==1){this.log(`Steering VERSION ${x.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=x.TTL;const{"RELOAD-URI":_,"PATHWAY-CLONES":w,"PATHWAY-PRIORITY":D}=x;if(_)try{this.uri=new self.URL(_,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${_}`);return}this.scheduleRefresh(this.uri||g.url),w&&this.clonePathways(w);const I={steeringManifest:x,url:n.toString()};this.hls.trigger(U.STEERING_MANIFEST_LOADED,I),D&&this.updatePathwayPriority(D)},onError:(f,p,g,y)=>{if(this.log(`Error loading steering manifest: ${f.code} ${f.text} (${p.url})`),this.stopLoad(),f.code===410){this.enabled=!1,this.log(`Steering manifest ${p.url} no longer available`);return}let x=this.timeToLoad*1e3;if(f.code===429){const _=this.loader;if(typeof _?.getResponseHeader=="function"){const w=_.getResponseHeader("Retry-After");w&&(x=parseFloat(w)*1e3)}this.log(`Steering manifest ${p.url} rate limited`);return}this.scheduleRefresh(this.uri||p.url,x)},onTimeout:(f,p,g)=>{this.log(`Timeout loading steering manifest (${p.url})`),this.scheduleRefresh(this.uri||p.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,c,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function ow(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(o=>o.groupId===n).map(o=>{const u=$i({},o);return u.details=void 0,u.attrs=new cs(u.attrs),u.url=u.attrs.URI=_L(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),u.groupId=u.attrs["GROUP-ID"]=e[n],u.attrs["PATHWAY-ID"]=i,u});s.push(...r)})}function _L(s,e,t,i){const{HOST:n,PARAMS:r,[t]:o}=i;let u;e&&(u=o?.[e],u&&(s=u));const c=new self.URL(s);return n&&!u&&(c.host=n),r&&Object.keys(r).sort().forEach(d=>{d&&c.searchParams.set(d,r[d])}),c.href}class dc extends gr{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=dc.CDMCleanupPromise?[dc.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,r=`"${t.type}" event: init data type: "${i}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=Wd(this.config));const u=o.map(tv).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(o=>{const u=Bm(o);if(i!=="sinf"||u!==ds.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}let c;try{const y=Ms(new Uint8Array(n)),x=Pb(JSON.parse(y).sinf),_=gD(x);if(!_)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(_.subarray(8,24))}catch(y){this.warn(`${r} Failed to parse sinf: ${y}`);return}const d=Xs(c),{keyIdToKeySessionPromise:f,mediaKeySessions:p}=this;let g=f[d];for(let y=0;ythis.generateRequestWithPreferredKeySession(x,i,n,"encrypted-event-key-match")),g.catch(D=>this.handleError(D));break}}g||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${p.length}.`))}).catch(o=>this.handleError(o))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(U.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(U.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(U.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(U.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(U.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(U.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(U.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(U.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(U.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(U.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t?.[e];if(n)return n.licenseUrl;if(e===ds.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t?.[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(o,u,c)=>!!o&&c.indexOf(o)===u,n=t.map(o=>o.audioCodec).filter(i),r=t.map(o=>o.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((o,u)=>{const c=d=>{const f=d.shift();this.getMediaKeysPromise(f,n,r).then(p=>o({keySystem:f,mediaKeys:p})).catch(p=>{d.length?c(d):p instanceof Wn?u(p):u(new Wn({type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_NO_ACCESS,error:p,fatal:!0},p.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return ND===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){var n;const r=V6(e,t,i,this.config.drmSystemOptions||{});let o=this.keySystemAccessPromises[e],u=(n=o)==null?void 0:n.keySystemAccess;if(!u){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Yi(r)}`),u=this.requestMediaKeySystemAccess(e,r);const c=o=this.keySystemAccessPromises[e]={keySystemAccess:u};return u.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),u.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const f=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const p=c.mediaKeys=d.createMediaKeys().then(g=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,f.then(y=>y?this.setMediaKeysServerCertificate(g,e,y):g)));return p.catch(g=>{this.error(`Failed to create media-keys for "${e}"}: ${g}`)}),p})}return u.then(()=>o.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Xs(e.keyId||[])} keyUri: ${e.uri}`);const n=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=Tm(t),r="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Xs(e.decryptdata.keyId||[])} + } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>tv(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:n})=>{const r=tv(n);r?t(r):i(new Error(`Unable to find format for key-system "${n}"`))}).catch(i)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Wd(this.config),i=e.map(Bm).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:t}))))).then(c=>{const d="cenc",f=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,f,"playlist-key")});return u.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[i]=u,u}return o.catch(u=>{if(u instanceof Wn){const c=Oi({},u.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const d=new Wn(c,u.message);this.handleError(d,e.frag)}}),o}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Wn){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${Xs(i.keyId||[])})`:""}`),this.hls.trigger(U.ERROR,e.data)}else this.error(e.message),this.hls.trigger(U.ERROR,{type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Tm(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=Bm(e.keyFormat),r=n?[n]:Wd(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Wd(this.config)),e.length===0)throw new Wn({type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Yi({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,o)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return o(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(o)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var r;const o=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(o)try{const x=o.call(this.hls,t,i,e);if(!x)throw new Error("Invalid response from configured generateRequest filter");t=x.initDataType,i=x.initData?x.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(x){if(this.warn(x.message),this.hls&&this.hls.config.debug)throw x}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const u=Tm(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${u} URI: ${c} (init data type: ${t} length: ${i.byteLength})`);const d=new Fb,f=e._onmessage=x=>{const _=e.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:w,message:D}=x;this.log(`"${w}" message event for session "${_.sessionId}" message size: ${D.byteLength}`),w==="license-request"||w==="license-renewal"?this.renewLicense(e,D).catch(I=>{d.eventNames().length?d.emit("error",I):this.handleError(I)}):w==="license-release"?e.keySystem===ds.FAIRPLAY&&this.updateKeySession(e,vx("acknowledged")).then(()=>this.removeSession(e)).catch(I=>this.handleError(I)):this.warn(`unhandled media key message type "${w}"`)},p=(x,_)=>{_.keyStatus=x;let w;x.startsWith("usable")?d.emit("resolved"):x==="internal-error"||x==="output-restricted"||x==="output-downscaled"?w=lw(x,_.decryptdata):x==="expired"?w=new Error(`key expired (keyId: ${u})`):x==="released"?w=new Error("key released"):x==="status-pending"||this.warn(`unhandled key status change "${x}" (keyId: ${u})`),w&&(d.eventNames().length?d.emit("error",w):this.handleError(w))},g=e._onkeystatuseschange=x=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const w=this.getKeyStatuses(e);if(!Object.keys(w).some(B=>w[B]!=="status-pending"))return;if(w[u]==="expired"){this.log(`Expired key ${Yi(w)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let I=w[u];if(I)p(I,e);else{var L;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(L=e.keyStatusTimeouts)[u]||(L[u]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const j=this.getKeyStatus(e.decryptdata);if(j&&j!=="status-pending")return this.log(`No status for keyId ${u} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${j} from other session.`),p(j,e);this.log(`key status for ${u} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),I="internal-error",p(I,e)},1e3)),this.log(`No status for keyId ${u} (${Yi(w)}).`)}};yn(e.mediaKeysSession,"message",f),yn(e.mediaKeysSession,"keystatuseschange",g);const y=new Promise((x,_)=>{d.on("error",_),d.on("resolved",x)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${u} URI: ${c}`)}).catch(x=>{throw new Wn({type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_NO_SESSION,error:x,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${x}`)}).then(()=>y).catch(x=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw x}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((i,n)=>{if(typeof n=="string"&&typeof i=="object"){const u=n;n=i,i=u}const r="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===ds.PLAYREADY&&r.length===16){const u=Xs(r);t[u]=i,RD(r)}const o=Xs(r);i==="internal-error"&&(this.bannedKeyIds[o]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${e.mediaKeysSession.sessionId}"`),t[o]=i}),t}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,u)=>{const c={responseType:"arraybuffer",url:r},d=t.certLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},p={onSuccess:(g,y,x,_)=>{o(g.data)},onError:(g,y,x,_)=>{u(new Wn({type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:x,response:Oi({url:c.url,data:void 0},g)},`"${e}" certificate request failed (${r}). Status: ${g.code} (${g.text})`))},onTimeout:(g,y,x)=>{u(new Wn({type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:x,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(g,y,x)=>{u(new Error("aborted"))}};n.load(c,f,p)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),n(e)}).catch(o=>{r(new Wn({type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new Wn({type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(i,"application/xml"),r=n.querySelectorAll("HttpHeader");if(r.length>0){let f;for(let p=0,g=r.length;p in key message");return vx(atob(d))}setupLicenseXHR(e,t,i,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,n)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((n,r)=>{const o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);const u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(u.readyState===4)if(u.status===200){this._requestLicenseFailureCount=0;let c=u.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,u,o,e)}catch(f){this.error(f)}n(c)}else{const c=i.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||u.status>=400&&u.status<500)r(new Wn({type:Lt.KEY_SYSTEM_ERROR,details:we.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:u,response:{url:o,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${o}). Status: ${u.status} (${u.statusText})`));else{const f=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${f} attempts left`),this.requestLicense(e,t).then(n,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=u,this.setupLicenseXHR(u,o,e,t).then(({xhr:c,licenseChallenge:d})=>{e.keySystem==ds.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,yn(i,"encrypted",this.onMediaEncrypted),yn(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(Mn(e,"encrypted",this.onMediaEncrypted),Mn(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,qo.clearKeyUriToKeyIdMap();const r=n.length;dc.CDMCleanupPromise=Promise.all(n.map(o=>this.removeSession(o)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(o=>{this.log(`Could not clear media keys: ${o}`),this.hls&&this.hls.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${o}`)})}))||Promise.resolve())).catch(o=>{this.log(`Could not close sessions and clear media keys: ${o}`),this.hls&&this.hls.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${o}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,r)=>(n.indexOf(r.keyFormat)===-1&&n.push(r.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Xs(n?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:o}=e;o&&Object.keys(o).forEach(d=>self.clearTimeout(o[d]));const{drmSystemOptions:u}=this.config;return(z6(u)?new Promise((d,f)=>{self.setTimeout(()=>f(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(f)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}dc.CDMCleanupPromise=void 0;function Tm(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Xs(s.keyId)}function cj(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}class Wn extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function lw(s,e){const t=s==="output-restricted",i=t?we.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:we.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Wn({type:Lt.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class dj{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(U.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(U.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(U.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(U.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const r=n-this.lastTime,o=i-this.lastDroppedFrames,u=t-this.lastDecodedFrames,c=1e3*o/r,d=this.hls;if(d.trigger(U.FPS_DROP,{currentDropped:o,currentDecoded:u,totalDroppedFrames:i}),c>0&&o>d.config.fpsDroppedMonitoringThreshold*u){let f=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+f),f>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=f)&&(f=f-1,d.trigger(U.FPS_DROP_LEVEL_CAPPING,{level:f,droppedLevel:d.currentLevel}),d.autoLevelCapping=f,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function SL(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function EL(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Mi.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,s.addCue(n)}catch(n){Mi.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function Zu(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t)}function Cx(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=fj(s.cues,e,t);for(let o=0;os[t].endTime)return-1;let i=0,n=t,r;for(;i<=n;)if(r=Math.floor((n+i)/2),es[r].startTime&&i-1)for(let r=n,o=s.length;r=e&&u.endTime<=t)i.push(u);else if(u.startTime>t)return i}return i}function $m(s){const e=[];for(let t=0;tthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=$m(this.media.textTracks);for(let r=0;r-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.MANIFEST_PARSED,this.onManifestParsed,this),e.on(U.LEVEL_LOADING,this.onLevelLoading,this),e.on(U.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(U.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(U.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.MANIFEST_PARSED,this.onManifestParsed,this),e.off(U.LEVEL_LOADING,this.onLevelLoading,this),e.off(U.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(U.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(U.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;$m(i.textTracks).forEach(o=>{Zu(o)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${o?.groupId}`);return}const u=o.details;o.details=t.details,this.log(`Subtitle track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,u)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||n?.length!==i?.length||i!=null&&i.some(o=>n?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(f=>!i||i.indexOf(f.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(f=>f.default)&&(this.selectDefaultTrack=!1),o.forEach((f,p)=>{f.id=p});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const f=ra(u,o);if(f>-1)r=o[f];else{const p=ra(u,this.tracks);r=this.tracks[p]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const d={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(U.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n-1){const r=this.tracksInGroup[n];return this.setSubtitleTrack(n),r}else{if(i)return null;{const r=ra(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,r=this.getUrlWithDirectives(e.url,t),o=e.details,u=o?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${u&&o.live?" age "+u.toFixed(1)+(o.type&&" "+o.type||""):""} ${r}`),this.hls.trigger(U.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=$m(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>Sx(i,r))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==n&&(r.mode="disabled")}),n){const r=this.subtitleDisplay?"showing":"hidden";n.mode!==r&&(n.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!gt(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(U.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!n.details&&!n.details.live;if(e===this.trackId&&n===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:u="",name:c,type:d,url:f}=n;this.hls.trigger(U.SUBTITLE_TRACK_SWITCH,{id:o,groupId:u,name:c,type:d,url:f});const p=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(p)}}function pj(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?r:r&3|8).toString(16)})}}}function lh(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const hc=.025;let Ap=(function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s})({});function gj(s,e,t){return`${s.identifier}-${t+1}-${lh(e)}`}class yj{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return cv(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=cv(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=gt(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return cv(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return vj(this)}}function cv(s,e){return s-e.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function Yu(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class xj{constructor(e,t,i,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(U.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const o=()=>{this.hasDetails=!0};r.once(U.LEVEL_LOADED,o),r.once(U.AUDIO_TRACK_LOADED,o),r.once(U.SUBTITLE_TRACK_LOADED,o),r.on(U.MEDIA_ATTACHING,(u,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(U.BUFFER_APPENDED,()=>{const f=this.bufferedEnd;this.reachedPlayout(f)&&(this._bufferedEosTime=f,r.trigger(U.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=wL(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,r=Yt.bufferInfo(e,n,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Yt.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,i){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,i){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Yu(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const uw=.033;class bj extends gr{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=n[i])!=null&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let n=0;nr.start&&e1)for(let r=0;ru&&(t!u.includes(d.identifier)):[];o.length&&o.sort((d,f)=>{const p=d.cue.pre,g=d.cue.post,y=f.cue.pre,x=f.cue.post;if(p&&!y)return-1;if(y&&!p||g&&!x)return 1;if(x&&!g)return-1;if(!p&&!y&&!g&&!x){const _=d.startTime,w=f.startTime;if(_!==w)return _-w}return d.dateRange.tagOrder-f.dateRange.tagOrder}),this.events=o,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],i=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const r=this.items,o=this.parseSchedule(n,e);(i||t.length||r?.length!==o.length||o.some((c,d)=>Math.abs(c.playout.start-r[d].playout.start)>.005||Math.abs(c.playout.end-r[d].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let o=0;o!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,d=0;if(e.forEach((f,p)=>{const g=f.cue.pre,y=f.cue.post,x=e[p-1]||null,_=f.appendInPlace,w=y?r:f.startOffset,D=f.duration,I=f.timelineOccupancy===Ap.Range?D:0,L=f.resumptionOffset,B=x?.startTime===w,j=w+f.cumulativeDuration;let V=_?j+D:w+L;if(g||!y&&w<=0){const z=d;d+=I,f.timelineStart=j;const O=o;o+=D,i.push({event:f,start:j,end:V,playout:{start:O,end:o},integrated:{start:z,end:d}})}else if(w<=r){if(!B){const N=w-c;if(N>uw){const q=c,Q=d;d+=N;const Y=o;o+=N;const re={previousEvent:e[p-1]||null,nextEvent:f,start:q,end:q+N,playout:{start:Y,end:o},integrated:{start:Q,end:d}};i.push(re)}else N>0&&x&&(x.cumulativeDuration+=N,i[i.length-1].end=w)}y&&(V=j),f.timelineStart=j;const z=d;d+=I;const O=o;o+=D,i.push({event:f,start:j,end:V,playout:{start:O,end:o},integrated:{start:z,end:d}})}else return;const M=f.resumeTime;y||M>r?c=r:c=M}),c{const d=u.cue.pre,f=u.cue.post,p=d?0:f?n:u.startTime;this.updateAssetDurations(u),o===p?u.cumulativeDuration=r:(r=0,o=p),!f&&u.snapOptions.in&&(u.resumeAnchor=Yl(null,i.fragments,u.startOffset+u.resumptionOffset,0,0)||void 0),u.appendInPlace&&!u.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(u,t)||(u.appendInPlace=!1)),!u.appendInPlace&&c+1hc?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(o=>{const u=t[o].details,c=u.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${o} playlist end ${c}`),!1;const d=Yl(null,u.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${o} playlist (${u.fragStart}-${u.fragmentEnd})`),!0;const f=o==="audio"?.175:0;return Math.abs(d.start-i){const w=g.data,D=w?.ASSETS;if(!Array.isArray(D)){const I=this.assignAssetListError(e,we.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),x.url,y,_);this.hls.trigger(U.ERROR,I);return}e.assetListResponse=w,this.hls.trigger(U.ASSET_LIST_LOADED,{event:e,assetListResponse:w,networkDetails:_})},onError:(g,y,x,_)=>{const w=this.assignAssetListError(e,we.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${g.code} ${g.text} (${y.url})`),y.url,_,x);this.hls.trigger(U.ERROR,w)},onTimeout:(g,y,x)=>{const _=this.assignAssetListError(e,we.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${y.url})`),y.url,g,x);this.hls.trigger(U.ERROR,_)}};return u.load(c,f,p),this.hls.trigger(U.ASSET_LIST_LOADING,{event:e}),u}assignAssetListError(e,t,i,n,r,o){return e.error=i,{type:Lt.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:o,stats:r}}}function cw(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function _m(s,e){return`[${s}] Advancing timeline position to ${e}`}class _j extends gr{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const n=i-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const u=this.playingItem;if(!u){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),o&&i=u.end){var c;const y=this.findItemIndex(u);let x=this.schedule.findItemIndexAtTime(i);if(x===-1&&(x=y+(o?-1:1),this.log(`seeked ${o?"back ":""}to position not covered by schedule ${i} (resolving from ${y} to ${x})`)),!this.isInterstitial(u)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!o&&x>y){const _=this.schedule.findJumpRestrictedIndex(y+1,x);if(_>y){this.setSchedulePosition(_);return}}this.setSchedulePosition(x);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(u)){const y=u.event.assetList[0];y&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,y))}return}const f=d.timelineStart,p=d.duration||0;if(o&&i=f+p){var g;(g=u.event)!=null&&g.appendInPlace&&(this.clearAssetPlayers(u.event,u),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(i>=n.end){this.timelinePos=n.end;const u=this.findItemIndex(n);this.setSchedulePosition(u+1)}const r=this.playingAsset;if(!r)return;const o=r.timelineStart+(r.duration||0);i>=o&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const o=this.playingItem,u=r.events||[],c=r.items||[],d=r.durations,f=i.map(_=>_.identifier),p=!!(u.length||f.length);(p||n)&&this.log(`INTERSTITIALS_UPDATED (${u.length}): ${u} +Schedule: ${c.map(_=>Er(_))} pos: ${this.timelinePos}`),f.length&&this.log(`Removed events ${f}`);let g=null,y=null;o&&(g=this.updateItem(o,this.timelinePos),this.itemsMatch(o,g)?this.playingItem=g:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const x=this.bufferingItem;if(x&&(y=this.updateItem(x,this.bufferedPos),this.itemsMatch(x,y)?this.bufferingItem=y:x.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(x.event,null))),i.forEach(_=>{_.assetList.forEach(w=>{this.clearAssetPlayer(w.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const w=_.assetItem.timelineStart,D=_.timelineOffset-w;if(D)try{_.timelineOffset=w}catch(I){Math.abs(D)>hc&&this.warn(`${I} ("${_.assetId}" ${_.timelineOffset}->${w})`)}}}),p||n){if(this.hls.trigger(U.INTERSTITIALS_UPDATED,{events:u.slice(0),schedule:c.slice(0),durations:d,removedIds:f}),this.isInterstitial(o)&&f.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}o&&this.trimInPlace(g,o),x&&y!==g&&this.trimInPlace(y,x),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Tj(e),this.schedule=new bj(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(U.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(U.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(U.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(U.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(U.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(U.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(U.BUFFER_APPENDED,this.onBufferAppended,this),e.on(U.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(U.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(U.MEDIA_ENDED,this.onMediaEnded,this),e.on(U.ERROR,this.onError,this),e.on(U.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(U.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(U.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(U.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(U.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(U.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(U.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(U.BUFFER_CODECS,this.onBufferCodecs,this),e.off(U.BUFFER_APPENDED,this.onBufferAppended,this),e.off(U.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(U.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(U.MEDIA_ENDED,this.onMediaEnded,this),e.off(U.ERROR,this.onError,this),e.off(U.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Mn(e,"play",this.onPlay),Mn(e,"pause",this.onPause),Mn(e,"seeking",this.onSeeking),Mn(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;yn(i,"seeking",this.onSeeking),yn(i,"timeupdate",this.onTimeupdate),yn(i,"play",this.onPlay),yn(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!n){this.clearScheduleState();const r=this.findItemIndex(i);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=p=>p&&e.getAssetPlayer(p.identifier),n=(p,g,y,x,_)=>{if(p){let w=p[g].start;const D=p.event;if(D){if(g==="playout"||D.timelineOccupancy!==Ap.Point){const I=i(y);I?.interstitial===D&&(w+=I.assetItem.startOffset+I[_])}}else{const I=x==="bufferedPos"?o():e[x];w+=I-p.start}return w}return 0},r=(p,g)=>{var y;if(p!==0&&g!=="primary"&&(y=e.schedule)!=null&&y.length){var x;const _=e.schedule.findItemIndexAtTime(p),w=(x=e.schedule.items)==null?void 0:x[_];if(w){const D=w[g].start-w.start;return p+D}}return p},o=()=>{const p=e.bufferedPos;return p===Number.MAX_VALUE?u("primary"):Math.max(p,0)},u=p=>{var g,y;return(g=e.primaryDetails)!=null&&g.live?e.primaryDetails.edge:((y=e.schedule)==null?void 0:y.durations[p])||0},c=(p,g)=>{var y,x;const _=e.effectivePlayingItem;if(_!=null&&(y=_.event)!=null&&y.restrictions.skip||!e.schedule)return;e.log(`seek to ${p} "${g}"`);const w=e.effectivePlayingItem,D=e.schedule.findItemIndexAtTime(p,g),I=(x=e.schedule.items)==null?void 0:x[D],L=e.getBufferingPlayer(),B=L?.interstitial,j=B?.appendInPlace,V=w&&e.itemsMatch(w,I);if(w&&(j||V)){const M=i(e.playingAsset),z=M?.media||e.primaryMedia;if(z){const O=g==="primary"?z.currentTime:n(w,g,e.playingAsset,"timelinePos","currentTime"),N=p-O,q=(j?O:z.currentTime)+N;if(q>=0&&(!M||j||q<=M.duration)){z.currentTime=q;return}}}if(I){let M=p;if(g!=="primary"){const O=I[g].start,N=p-O;M=I.start+N}const z=!e.isInterstitial(I);if((!e.isInterstitial(w)||w.event.appendInPlace)&&(z||I.event.appendInPlace)){const O=e.media||(j?L?.media:null);O&&(O.currentTime=M)}else if(w){const O=e.findItemIndex(w);if(D>O){const q=e.schedule.findJumpRestrictedIndex(O+1,D);if(q>O){e.setSchedulePosition(q);return}}let N=0;if(z)e.timelinePos=M,e.checkBuffer();else{const q=I.event.assetList,Q=p-(I[g]||I).start;for(let Y=q.length;Y--;){const re=q[Y];if(re.duration&&Q>=re.startOffset&&Q{const p=e.effectivePlayingItem;if(e.isInterstitial(p))return p;const g=t();return e.isInterstitial(g)?g:null},f={get bufferedEnd(){const p=t(),g=e.bufferingItem;if(g&&g===p){var y;return n(g,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-g.playout.start||((y=e.bufferingAsset)==null?void 0:y.startOffset)||0}return 0},get currentTime(){const p=d(),g=e.effectivePlayingItem;return g&&g===p?n(g,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-g.playout.start:0},set currentTime(p){const g=d(),y=e.effectivePlayingItem;y&&y===g&&c(p+y.playout.start,"playout")},get duration(){const p=d();return p?p.playout.end-p.playout.start:0},get assetPlayers(){var p;const g=(p=d())==null?void 0:p.event.assetList;return g?g.map(y=>e.getAssetPlayer(y.identifier)):[]},get playingIndex(){var p;const g=(p=d())==null?void 0:p.event;return g&&e.effectivePlayingAsset?g.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var p;return((p=e.schedule)==null||(p=p.events)==null?void 0:p.slice(0))||[]},get schedule(){var p;return((p=e.schedule)==null||(p=p.items)==null?void 0:p.slice(0))||[]},get interstitialPlayer(){return d()?f:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const p=t();return e.findItemIndex(p)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const p=e.effectivePlayingItem;return e.findItemIndex(p)},primary:{get bufferedEnd(){return o()},get currentTime(){const p=e.timelinePos;return p>0?p:0},set currentTime(p){c(p,"primary")},get duration(){return u("primary")},get seekableStart(){var p;return((p=e.primaryDetails)==null?void 0:p.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(p){c(p,"integrated")},get duration(){return u("integrated")},get seekableStart(){var p;return r(((p=e.primaryDetails)==null?void 0:p.fragmentStart)||0,"integrated")}},skip:()=>{const p=e.effectivePlayingItem,g=p?.event;if(g&&!g.restrictions.skip){const y=e.findItemIndex(p);if(g.appendInPlace){const x=p.playout.start+p.event.duration;c(x+.001,"playout")}else e.advanceAfterAssetEnded(g,y,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const r=(t=n)==null?void 0:t.currentTime;if(!(r===void 0||!gt(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,n=e.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Yi(r)}`),this.detachedData=r}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var i,n;if(e.media===t)return;let r=null;const o=this.hls,u=e!==o,c=u&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource;let f;if(o.media)c&&(r=o.transferMedia(),this.detachedData=r),f="Primary";else if(d){const x=this.getBufferingPlayer();x?(r=x.transferMedia(),f=`${x}`):f="detached MediaSource"}else f="detached media";if(!r){if(d)r=this.detachedData,this.log(`using detachedData: MediaSource ${Yi(r)}`);else if(!this.detachedData||o.media===t){const x=this.playerQueue;x.length>1&&x.forEach(_=>{if(u&&_.interstitial.appendInPlace!==c){const w=_.interstitial;this.clearInterstitial(_.interstitial,null),w.appendInPlace=!1,w.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${w}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const p=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",g=p&&r?r:t;this.log(`${p?"transfering MediaSource":"attaching media"} to ${u?e:"Primary"} from ${f} (media.currentTime: ${t.currentTime})`);const y=this.schedule;if(g===r&&y){const x=u&&e.assetId===y.assetIdAtEnd;g.overrides={duration:y.duration,endOfStream:!u||x,cueRemoval:!u}}e.attachMedia(g)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,n=this.effectivePlayingItem;if(i===-1){const r=this.hls.startPosition;if(this.log(_m("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(r>=0||!this.primaryLive){const o=this.timelinePos=r>0?r:0,u=e.findItemIndexAtTime(o);this.setSchedulePosition(u)}}else if(n&&!this.playingItem){const r=e.findItemIndex(n);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const i=e.event,n=i.findAssetIndex(t),r=dv(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var o;const u=(o=this.schedule.items)==null?void 0:o[this.findItemIndex(e)+1];u&&this.bufferedToItem(u)}}advanceAfterAssetEnded(e,t,i){const n=dv(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const o=t+1,u=r.length;if(o>=u){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Er(r)}) pos: ${this.timelinePos}`);const o=this.waitingItem||this.playingItem,u=this.playingLastItem;if(this.isInterstitial(o)){const f=o.event,p=this.playingAsset,g=p?.identifier,y=g?this.getAssetPlayer(g):null;if(y&&g&&(!this.eventItemsMatch(o,r)||t!==void 0&&g!==f.assetList[t].identifier)){var c;const x=f.findAssetIndex(p);if(this.log(`INTERSTITIAL_ASSET_ENDED ${x+1}/${f.assetList.length} ${Yu(p)}`),this.endedAsset=p,this.playingAsset=null,this.hls.trigger(U.INTERSTITIAL_ASSET_ENDED,{asset:p,assetListIndex:x,event:f,schedule:n.slice(0),scheduleIndex:e,player:y}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(f,this.findItemIndex(this.playingItem),x);return}this.retreiveMediaSource(g,r),y.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&y.detachMedia()}if(!this.eventItemsMatch(o,r)&&(this.endedItem=o,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${f} ${Er(o)}`),f.hasPlayed=!0,this.hls.trigger(U.INTERSTITIAL_ENDED,{event:f,schedule:n.slice(0),scheduleIndex:e}),f.cue.once)){var d;this.updateSchedule();const x=(d=this.schedule)==null?void 0:d.items;if(r&&x){const _=this.findItemIndex(r);this.advanceSchedule(_,x,t,o,u)}return}}this.advanceSchedule(e,n,t,o,u)}advanceSchedule(e,t,i,n,r){const o=this.schedule;if(!o)return;const u=t[e]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(f=>{const p=f.interstitial,g=o.findEventIndex(p.identifier);(ge+1)&&this.clearInterstitial(p,u)}),this.isInterstitial(u)){this.timelinePos=Math.min(Math.max(this.timelinePos,u.start),u.end);const f=u.event;if(i===void 0){i=o.findAssetIndex(f,this.timelinePos);const x=dv(f,i-1);if(f.isAssetPastPlayoutLimit(x)||f.appendInPlace&&this.timelinePos===u.end){this.advanceAfterAssetEnded(f,e,i);return}i=x}const p=this.waitingItem;this.assetsBuffered(u,c)||this.setBufferingItem(u);let g=this.preloadAssets(f,i);if(this.eventItemsMatch(u,p||n)||(this.waitingItem=u,this.log(`INTERSTITIAL_STARTED ${Er(u)} ${f.appendInPlace?"append in place":""}`),this.hls.trigger(U.INTERSTITIAL_STARTED,{event:f,schedule:t.slice(0),scheduleIndex:e})),!f.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${f}`);return}if(f.assetListLoader&&(f.assetListLoader.destroy(),f.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${f}`);return}this.waitingItem=this.endedItem=null,this.playingItem=u;const y=f.assetList[i];if(!y){this.advanceAfterAssetEnded(f,e,i||0);return}if(g||(g=this.getAssetPlayer(y.identifier)),g===null||g.destroyed){const x=f.assetList.length;this.warn(`asset ${i+1}/${x} player destroyed ${f}`),g=this.createAssetPlayer(f,y,i),g.loadSource()}if(!this.eventItemsMatch(u,this.bufferingItem)&&f.appendInPlace&&this.isAssetBuffered(y))return;this.startAssetPlayer(g,i,t,e,c),this.shouldPlay&&cw(g.media)}else u?(this.resumePrimary(u,e,n),this.shouldPlay&&cw(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(o.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var n,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Er(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let u=this.timelinePos;(u=e.end)&&(u=this.getPrimaryResumption(e,t),this.log(_m("resumePrimary",u)),this.timelinePos=u),this.attachPrimary(u,e)}if(!i)return;const o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Er(e)}`),this.hls.trigger(U.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(in.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Yt.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,n),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(_m("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((i=n.mainForwardBufferInfo)==null?void 0:i.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(U.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(U.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const n=Oi(Oi({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Oi(Oi({},this.altSelection),{},{audio:i});return}const r=Oi(Oi({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Oi(Oi({},this.altSelection),{},{subtitles:i});return}const r=Oi(Oi({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=x2(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=x2(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((r,o)=>{e.event.isAssetPastPlayoutLimit(o)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=Yt.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Er(e)} (was ${Er(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const n=Yt.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,i,e)}updateBufferedPos(e,t,i){const n=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const o=this.playingItem,u=this.findItemIndex(o);let c=n.findItemIndexAtTime(e);if(this.bufferedPos=r.end||(d=g.event)!=null&&d.appendInPlace&&e+.01>=g.start)&&(c=p),this.isInterstitial(r)){const y=r.event;if(p-u>1&&y.appendInPlace===!1||y.assetList.length===0&&y.assetListLoader)return}if(this.bufferedPos=e,c>f&&c>u)this.bufferedToItem(g);else{const y=this.primaryDetails;this.primaryLive&&y&&e>y.edge-y.targetduration&&g.start{const r=this.getAssetPlayer(n.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:n,events:r}=i;if(!n||!r)return t;const o=this.isInterstitial(e),u=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=u?u.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Er(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(o){const d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((f,p)=>{const g=this.getAssetPlayer(f.identifier);g&&(p===d&&g.loadSource(),g.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(U.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,n=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(n||!r){const o=this.preloadAssets(i,t);if(o!=null&&o.interstitial.appendInPlace){const u=this.primaryMedia;u&&this.bufferAssetPlayer(o,u)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,o=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var u;const g=this.playingItem;!this.isInterstitial(g)&&(g==null||(u=g.nextEvent)==null?void 0:u.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let d,f=0;if(!this.playingItem&&this.primaryLive&&(f=this.hls.startPosition,f===-1&&(f=this.hls.liveSyncPosition||0)),f&&!(e.cue.pre||e.cue.post)){const g=f-c;g>0&&(d=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:n} ${e}${d?` live-start: ${f} start-offset: ${d}`:""}`),i)return this.createAsset(e,0,0,c,e.duration,i);const p=this.assetListLoader.loadAssetList(e,d);p&&(e.assetListLoader=p)}else if(!o&&n){for(let d=t;d{this.hls.trigger(U.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i1){const j=t.duration;j&&B{if(B.live){var j;const z=new Error(`Interstitials MUST be VOD assets ${e}`),O={fatal:!0,type:Lt.OTHER_ERROR,details:we.INTERSTITIAL_ASSET_ITEM_ERROR,error:z},N=((j=this.schedule)==null?void 0:j.findEventIndex(e.identifier))||-1;this.handleAssetItemError(O,e,N,i,z.message);return}const V=B.edge-B.fragmentStart,M=t.duration;(_||M===null||V>M)&&(_=!1,this.log(`Interstitial asset "${p}" duration change ${M} > ${V}`),t.duration=V,this.updateSchedule())};x.on(U.LEVEL_UPDATED,(B,{details:j})=>w(j)),x.on(U.LEVEL_PTS_UPDATED,(B,{details:j})=>w(j)),x.on(U.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const D=(B,j)=>{const V=this.getAssetPlayer(p);if(V&&j.tracks){V.off(U.BUFFER_CODECS,D),V.tracks=j.tracks;const M=this.primaryMedia;this.bufferingAsset===V.assetItem&&M&&!V.media&&this.bufferAssetPlayer(V,M)}};x.on(U.BUFFER_CODECS,D);const I=()=>{var B;const j=this.getAssetPlayer(p);if(this.log(`buffered to end of asset ${j}`),!j||!this.schedule)return;const V=this.schedule.findEventIndex(e.identifier),M=(B=this.schedule.items)==null?void 0:B[V];this.isInterstitial(M)&&this.advanceAssetBuffering(M,t)};x.on(U.BUFFERED_TO_END,I);const L=B=>()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;this.shouldPlay=!0;const V=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,V,B)};return x.once(U.MEDIA_ENDED,L(i)),x.once(U.PLAYOUT_LIMIT_REACHED,L(1/0)),x.on(U.ERROR,(B,j)=>{if(!this.schedule)return;const V=this.getAssetPlayer(p);if(j.details===we.BUFFER_STALLED_ERROR){if(V!=null&&V.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(j,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${j.error} ${e}`)}),x.on(U.DESTROYING,()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;const j=new Error(`Asset player destroyed unexpectedly ${p}`),V={fatal:!0,type:Lt.OTHER_ERROR,details:we.INTERSTITIAL_ASSET_ITEM_ERROR,error:j};this.handleAssetItemError(V,e,this.schedule.findEventIndex(e.identifier),i,j.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Yu(t)}`),this.hls.trigger(U.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:x}),x}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const n=this.playerQueue[i];this.log(`clear ${n} toSegment: ${t&&Er(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(i,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,n,r){const{interstitial:o,assetItem:u,assetId:c}=e,d=o.assetList.length,f=this.playingAsset;this.endedAsset=null,this.playingAsset=u,(!f||f.identifier!==c)&&(f&&(this.clearAssetPlayer(f.identifier,i[n]),delete f.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${Yu(u)}`),this.hls.trigger(U.INTERSTITIAL_ASSET_STARTED,{asset:u,assetListIndex:t,event:o,schedule:i.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,n;if(!this.schedule)return;const{interstitial:r,assetItem:o}=e,u=this.schedule.findEventIndex(r.identifier),c=(i=this.schedule.items)==null?void 0:i[u];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=o;const d=this.getBufferingPlayer();if(d===e)return;const f=r.appendInPlace;if(f&&d?.interstitial.appendInPlace===!1)return;const p=d?.tracks||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(f&&o!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(p&&!oD(p,e.tracks)){const g=new Error(`Asset ${Yu(o)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(p)}')`),y={fatal:!0,type:Lt.OTHER_ERROR,details:we.INTERSTITIAL_ASSET_ITEM_ERROR,error:g},x=r.findAssetIndex(o);this.handleAssetItemError(y,r,u,x,g.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const n=i.currentTime,r=t.findAssetIndex(e,n),o=e.assetList[r];if(o){const u=this.getAssetPlayer(o.identifier);if(u){const c=u.currentTime||n-o.timelineStart,d=u.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${u} ${e} (media.currentTime: ${n})`),c&&(d/i.playbackRate<.5||u.bufferedInPlaceToEnd(i))&&u.hls){const f=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,f,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime!_.error))t.error=x;else for(let _=n;_{const D=parseFloat(_.DURATION);this.createAsset(r,w,f,c+f,D,_.URI),f+=D}),r.duration=f,this.log(`Loaded asset-list with duration: ${f} (was: ${d}) ${r}`);const p=this.waitingItem,g=p?.event.identifier===o;this.updateSchedule();const y=(n=this.bufferingItem)==null?void 0:n.event;if(g){var x;const _=this.schedule.findEventIndex(o),w=(x=this.schedule.items)==null?void 0:x[_];if(w){if(!this.playingItem&&this.timelinePos>w.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==_){r.error=new Error(`Interstitial ${u.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(w)}this.setSchedulePosition(_)}else if(y?.identifier===o){const _=r.assetList[0];if(_){const w=this.getAssetPlayer(_.identifier);if(y.appendInPlace){const D=this.primaryMedia;w&&D&&this.bufferAssetPlayer(w,D)}else w&&w.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case we.ASSET_LIST_PARSING_ERROR:case we.ASSET_LIST_LOAD_ERROR:case we.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case we.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const dw=500;class Sj extends Bb{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",_t.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(U.LEVEL_LOADED,this.onLevelLoaded,this),e.on(U.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(U.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(U.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(U.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(U.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(U.LEVEL_LOADED,this.onLevelLoaded,this),e.off(U.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(U.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(U.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(U.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(U.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=ze.IDLE,this.setInterval(dw),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(this.fragContextChanged(i)||(Ss(i)&&(this.fragPrevious=i),this.state=ze.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let o;const u=i.start;for(let d=0;d=r[d].start&&u<=r[d].end){o=r[d];break}const c=i.start+i.duration;o?o.end=c:(o={start:u,end:c},r.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const r=n-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(o=>{for(let u=0;unew vh(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new vh(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,_t.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==ze.STOPPED&&this.setInterval(dw)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:o,id:u}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${u}`);return}const c=r[u];if(u>=r.length||!c)return;this.log(`Subtitle track ${u} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(o.live||(i=c.details)!=null&&i.live){if(o.deltaUpdateFailed)return;const p=this.mainDetails;if(!p){this.startFragRequested=!1;return}const g=p.fragments[0];if(!c.details)o.hasProgramDateTime&&p.hasProgramDateTime?(Ep(o,p),d=o.fragmentStart):g&&(d=g.start,bx(o,d));else{var f;d=this.alignPlaylists(o,c.details,(f=this.levelLastLoaded)==null?void 0:f.details),d===0&&g&&(d=g.start,bx(o,d))}p&&!this.startFragRequested&&this.setStartPosition(p,d)}c.details=o,this.levelLastLoaded=c,u===n&&(this.hls.trigger(U.SUBTITLE_TRACK_UPDATED,{details:o,id:u,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===ze.IDLE&&(Yl(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,n=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&cc(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,Mb(n.method)).catch(u=>{throw r.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:t}),u}).then(u=>{const c=performance.now();r.trigger(U.FRAG_DECRYPTED,{frag:t,payload:u,stats:{tstart:o,tdecrypt:c}})}).catch(u=>{this.warn(`${u.name}: ${u.message}`),this.state=ze.IDLE})}}doTick(){if(!this.media){this.state=ze.IDLE;return}if(this.state===ze.IDLE){const{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:n}=this,r=this.getLoadPosition(),o=Yt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:c}=o,d=i.details,f=this.hls.maxBufferLength+d.levelTargetDuration;if(c>f)return;const p=d.fragments,g=p.length,y=d.edge;let x=null;const _=this.fragPrevious;if(uy-I?0:I;x=Yl(_,p,Math.max(p[0].start,u),L),!x&&_&&_.start{if(n=n>>>0,n>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const wj={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},AL=s=>String.fromCharCode(wj[s]||s),Ar=15,Pa=100,Aj={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Cj={17:2,18:4,21:6,22:8,23:10,19:13,20:15},kj={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Dj={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Lj=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Rj{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;Mi.log(`${this.time} [${e}] ${i}`)}}}const Ll=function(e){const t=[];for(let i=0;iPa&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Pa)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=AL(e);if(this.pos>=Pa){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t"pacData = "+Yi(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+Yi(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",n=-1;for(let r=0;r0&&(e?i="["+t.join(" | ")+"]":i=t.join(` +`)),i}getTextAndFormat(){return this.rows}}class hw{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new hv(i),this.nonDisplayedMemory=new hv(i),this.lastOutputScreen=new hv(i),this.currRollUpRow=this.displayedMemory.rows[Ar-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Ar-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;it+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[i]}this.logger.log(2,"MIDROW: "+Yi(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class fw{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Mj(),this.logger=void 0;const n=this.logger=new Rj;this.channels=[null,new hw(e,t,n),new hw(e+1,i,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i"["+Ll([t[i],t[i+1]])+"] -> ("+Ll([n,r])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(Oj(n,r,c)){Sm(null,null,c),this.logger.log(3,()=>"Repeated command ("+Ll([n,r])+") is dropped");continue}Sm(n,r,this.cmdHistory),o=this.parseCmd(n,r),o||(o=this.parseMidrow(n,r)),o||(o=this.parsePAC(n,r)),o||(o=this.parseBackgroundAttributes(n,r))}else Sm(null,null,c);if(!o&&(u=this.parseChars(n,r),u)){const f=this.currentChannel;f&&f>0?this.channels[f].insertChars(u):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!u&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Ll([n,r])+" orig: "+Ll([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(i||n))return!1;const r=e===20||e===21||e===23?1:2,o=this.channels[r];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[i];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Ll([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(n||r))return!1;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?Aj[e]:kj[e]:i=o===1?Cj[e]:Dj[e];const u=this.channels[o];return u?(u.setPAC(this.interpretPAC(i,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,n.underline=(i&1)===1,i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((i-16)/2)*4,n}parseChars(e,t){let i,n=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let o;r===17?o=t+80:r===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+AL(o)+"' in channel "+i),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+Ll(n).join(",")),n}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(i||n))return!1;let r;const o={};e===16||e===24?(r=Math.floor((t-32)/2),o.background=Lj[r],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const u=e<=23?1:2;return this.channels[u].setBkgData(o),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");V=N,this.hasBeenReset=!0}})),Object.defineProperty(f,"positionAlign",r({},p,{get:function(){return M},set:function(N){const q=n(N);if(!q)throw new SyntaxError("An invalid or illegal string was specified.");M=q,this.hasBeenReset=!0}})),Object.defineProperty(f,"size",r({},p,{get:function(){return z},set:function(N){if(N<0||N>100)throw new Error("Size must be between 0 and 100.");z=N,this.hasBeenReset=!0}})),Object.defineProperty(f,"align",r({},p,{get:function(){return O},set:function(N){const q=n(N);if(!q)throw new SyntaxError("An invalid or illegal string was specified.");O=q,this.hasBeenReset=!0}})),f.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})();class Pj{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function kL(s){function e(i,n,r,o){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(o||0)}const t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Bj{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let n=0;n=0&&i<=100)return this.set(e,i),!0}return!1}}function DL(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const o=n[r].split(t);if(o.length!==2)continue;const u=o[0],c=o[1];e(u,c)}}const kx=new Wb(0,0,""),Em=kx.align==="middle"?"middle":"center";function Fj(s,e,t){const i=s;function n(){const u=kL(s);if(u===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),u}function r(u,c){const d=new Bj;DL(u,function(g,y){let x;switch(g){case"region":for(let _=t.length-1;_>=0;_--)if(t[_].id===y){d.set(g,t[_].region);break}break;case"vertical":d.alt(g,y,["rl","lr"]);break;case"line":x=y.split(","),d.integer(g,x[0]),d.percent(g,x[0])&&d.set("snapToLines",!1),d.alt(g,x[0],["auto"]),x.length===2&&d.alt("lineAlign",x[1],["start",Em,"end"]);break;case"position":x=y.split(","),d.percent(g,x[0]),x.length===2&&d.alt("positionAlign",x[1],["start",Em,"end","line-left","line-right","auto"]);break;case"size":d.percent(g,y);break;case"align":d.alt(g,y,["start",Em,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let f=d.get("line","auto");f==="auto"&&kx.line===-1&&(f=-1),c.line=f,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",Em);let p=d.get("position","auto");p==="auto"&&kx.position===50&&(p=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=p}function o(){s=s.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),o(),e.endTime=n(),o(),r(s,e)}function LL(s){return s.replace(//gi,` +`)}class Uj{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Pj,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,o=0;for(r=LL(r);o")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Fj(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const u=r.indexOf("-->")!==-1;if(!r||u&&(o=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` +`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` + +`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const jj=/\r\n|\n\r|\n|\r/g,fv=function(e,t,i=0){return e.slice(i,i+t.length)===t},$j=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!gt(t)||!gt(i)||!gt(n)||!gt(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=3600*1e3*r,t};function Xb(s,e,t){return lh(s.toString())+lh(e.toString())+lh(t)}const Hj=function(e,t,i){let n=e[t],r=e[n.prevCC];if(!r||!r.new&&n.new){e.ccOffset=e.presentationOffset=n.start,n.new=!1;return}for(;(o=r)!=null&&o.new;){var o;e.ccOffset+=n.start-r.start,n.new=!1,n=r,r=e[n.prevCC]}e.presentationOffset=i};function Vj(s,e,t,i,n,r,o){const u=new Uj,c=er(new Uint8Array(s)).trim().replace(jj,` +`).split(` +`),d=[],f=e?WU(e.baseTime,e.timescale):0;let p="00:00.000",g=0,y=0,x,_=!0;u.oncue=function(w){const D=t[i];let I=t.ccOffset;const L=(g-f)/9e4;if(D!=null&&D.new&&(y!==void 0?I=t.ccOffset=D.start:Hj(t,i,L)),L){if(!e){x=new Error("Missing initPTS for VTT MPEGTS");return}I=L-t.presentationOffset}const B=w.endTime-w.startTime,j=Qn((w.startTime+I-y)*9e4,n*9e4)/9e4;w.startTime=Math.max(j,0),w.endTime=Math.max(j+B,0);const V=w.text.trim();w.text=decodeURIComponent(encodeURIComponent(V)),w.id||(w.id=Xb(w.startTime,w.endTime,V)),w.endTime>0&&d.push(w)},u.onparsingerror=function(w){x=w},u.onflush=function(){if(x){o(x);return}r(d)},c.forEach(w=>{if(_)if(fv(w,"X-TIMESTAMP-MAP=")){_=!1,w.slice(16).split(",").forEach(D=>{fv(D,"LOCAL:")?p=D.slice(6):fv(D,"MPEGTS:")&&(g=parseInt(D.slice(7)))});try{y=$j(p)/1e3}catch(D){x=D}return}else w===""&&(_=!1);u.parse(w+` +`)}),u.flush()}const mv="stpp.ttml.im1t",RL=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,IL=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Gj={left:"start",center:"center",right:"end",start:"start",end:"end"};function mw(s,e,t,i){const n=ci(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>er(u)),o=YU(e.baseTime,1,e.timescale);try{r.forEach(u=>t(zj(u,o)))}catch(u){i(u)}}function zj(s,e){const n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(r).reduce((p,g)=>(p[g]=n.getAttribute(`ttp:${g}`)||r[g],p),{}),u=n.getAttribute("xml:space")!=="preserve",c=pw(pv(n,"styling","style")),d=pw(pv(n,"layout","region")),f=pv(n,"body","[begin]");return[].map.call(f,p=>{const g=NL(p,u);if(!g||!p.hasAttribute("begin"))return null;const y=yv(p.getAttribute("begin"),o),x=yv(p.getAttribute("dur"),o);let _=yv(p.getAttribute("end"),o);if(y===null)throw gw(p);if(_===null){if(x===null)throw gw(p);_=y+x}const w=new Wb(y-e,_-e,g);w.id=Xb(w.startTime,w.endTime,w.text);const D=d[p.getAttribute("region")],I=c[p.getAttribute("style")],L=qj(D,I,c),{textAlign:B}=L;if(B){const j=Gj[B];j&&(w.lineAlign=j),w.align=B}return $i(w,L),w}).filter(p=>p!==null)}function pv(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function pw(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function NL(s,e){return[].slice.call(s.childNodes).reduce((t,i,n)=>{var r;return i.nodeName==="br"&&n?t+` +`:(r=i.childNodes)!=null&&r.length?NL(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function qj(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(n=t[o]),r.reduce((u,c)=>{const d=gv(e,i,c)||gv(s,i,c)||gv(n,i,c);return d&&(u[c]=d),u},{})}function gv(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function gw(s){return new Error(`Could not parse ttml timestamp ${s}`)}function yv(s,e){if(!s)return null;let t=kL(s);return t===null&&(RL.test(s)?t=Kj(s,e):IL.test(s)&&(t=Yj(s,e))),t}function Kj(s,e){const t=RL.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Yj(s,e){const t=IL.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class wm{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Wj{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=vw(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(U.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(U.FRAG_LOADING,this.onFragLoading,this),e.on(U.FRAG_LOADED,this.onFragLoaded,this),e.on(U.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(U.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(U.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(U.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(U.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(U.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(U.FRAG_LOADING,this.onFragLoading,this),e.off(U.FRAG_LOADED,this.onFragLoaded,this),e.off(U.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(U.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(U.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(U.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(U.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new wm(this,"textTrack1"),t=new wm(this,"textTrack2"),i=new wm(this,"textTrack3"),n=new wm(this,"textTrack4");this.cea608Parser1=new fw(1,e,t),this.cea608Parser2=new fw(3,i,n)}addCues(e,t,i,n,r){let o=!1;for(let u=r.length;u--;){const c=r[u],d=Xj(c[0],c[1],t,i);if(d>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),o=!0,d/(i-t)>.5))return}if(o||r.push([t,i]),this.config.renderTextTracksNatively){const u=this.captionsTracks[e];this.Cues.newCue(u,t,i,n)}else{const u=this.Cues.newCue(null,t,i,n);this.hls.trigger(U.CUES_PARSED,{type:"captions",cues:u,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:o}){const{unparsedVttFrags:u}=this;i===_t.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:o}),u.length&&(this.unparsedVttFrags=[],u.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(U.FRAG_LOADED,c):this.hls.trigger(U.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let n=0;n{Zu(n[r]),delete n[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=vw(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;ir.textCodec===mv);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(cL(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media,u=o?$m(o.textTracks):null;if(this.tracks.forEach((c,d)=>{let f;if(u){let p=null;for(let g=0;gd!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(u=>({label:u.name,kind:u.type.toLowerCase(),default:u.default,subtitleTrack:u}));this.hls.trigger(U.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const n=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!n)return;const r=`textTrack${n[1]}`,o=this.captionsProperties[r];o&&(o.label=i.name,i.lang&&(o.languageCode=i.lang),o.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===_t.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:o,lastSn:u}=this,{cc:c,sn:d}=t.frag,f=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&o&&(d!==u+1||d===u&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),o.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===_t.SUBTITLE)if(n.byteLength){const r=i.decryptdata,o="stats"in t;if(r==null||!r.encrypted||o){const u=this.tracks[i.level],c=this.vttCCs;c[i.cc]||(c[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),u&&u.textCodec===mv?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(U.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;mw(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(U.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger(U.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:o}=this,u=r.length-1;if(!r[i.cc]&&u===-1){o.push(e);return}const c=this.hls,d=(t=i.initSegment)!=null&&t.data?fr(i.initSegment.data,new Uint8Array(n)).buffer:n;Vj(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger(U.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const p=f.message==="Missing initPTS for VTT MPEGTS";p?o.push(e):this._fallbackToIMSC1(i,n),c.logger.log(`Failed to parse VTT cue: ${f}`),!(p&&u>i.cc)&&c.trigger(U.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||mw(t,this.initPTS[e.cc],()=>{i.textCodec=mv,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(r=>EL(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(U.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===_t.SUBTITLE&&this.onFragLoaded(U.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:n}=t;if(!(i.type===_t.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;rCx(u[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(c=>Cx(u[c],t,n))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let n=2;for(let r=0;r=16?c--:c++;const y=LL(d.trim()),x=Xb(e,t,y);s!=null&&(p=s.cues)!=null&&p.getCueById(x)||(o=new f(e,t,y),o.id=x,o.line=g+1,o.align="left",o.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(o))}return s&&n.length&&(n.sort((g,y)=>g.line==="auto"||y.line==="auto"?0:g.line>8&&y.line>8?y.line-g.line:g.line-y.line),n.forEach(g=>EL(s,g))),n}};function Jj(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const e9=/(\d+)-(\d+)\/(\d+)/;class xw{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||n9,this.controller=new self.AbortController,this.stats=new kb}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const r=t9(e,this.controller.signal),o=e.responseType==="arraybuffer",u=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&>(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Th(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(p=>{var g;this.response=this.loader=p;const y=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},d-(y-n.loading.start)),!p.ok){const{status:_,statusText:w}=p;throw new r9(w||"fetch, bad network response",_,p)}n.loading.first=y,n.total=s9(p.headers)||n.total;const x=(g=this.callbacks)==null?void 0:g.onProgress;return x&>(t.highWaterMark)?this.loadProgressively(p,n,e,t.highWaterMark,x):o?p.arrayBuffer():e.responseType==="json"?p.json():p.text()}).then(p=>{var g,y;const x=this.response;if(!x)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const _=p[u];_&&(n.loaded=n.total=_);const w={url:x.url,data:p,code:x.status},D=(g=this.callbacks)==null?void 0:g.onProgress;D&&!gt(t.highWaterMark)&&D(n,e,p,x),(y=this.callbacks)==null||y.onSuccess(w,n,e,x)}).catch(p=>{var g;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const y=p&&p.code||0,x=p?p.message:null;(g=this.callbacks)==null||g.onError({code:y,text:x},e,p?p.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,n=0,r){const o=new GD,u=e.body.getReader(),c=()=>u.read().then(d=>{if(d.done)return o.dataLength&&r(t,i,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=d.value,p=f.length;return t.loaded+=p,p=n&&r(t,i,o.flush().buffer,e)):r(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function t9(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers($i({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function i9(s){const e=e9.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function s9(s){const e=s.get("Content-Range");if(e){const i=i9(e);if(gt(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function n9(s,e){return new self.Request(s.url,e)}class r9 extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const a9=/^age:\s*[\d.]+\s*$/im;class ML{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new kb,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(o=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(o=>{var u;(u=this.callbacks)==null||u.onError({code:i.status,text:o.message},t,i,n)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:o}=i.loadPolicy;if(n)for(const u in n)e.setRequestHeader(u,n[u]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&>(r)?r:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const n=t.readyState,r=this.config;if(!i.aborted&&n>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const d=t.status,f=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const x=f??t.response;if(x!=null){var o,u;i.loading.end=Math.max(self.performance.now(),i.loading.first);const _=t.responseType==="arraybuffer"?x.byteLength:x.length;i.loaded=i.total=_,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const w=(o=this.callbacks)==null?void 0:o.onProgress;w&&w(i,e,x,t);const D={url:t.responseURL,data:x,code:d};(u=this.callbacks)==null||u.onSuccess(D,i,e,t);return}}const p=r.loadPolicy.errorRetry,g=i.retry,y={url:e.url,data:void 0,code:d};if(Tp(p,g,!1,y))this.retry(p);else{var c;Mi.error(`${d} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:d,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Tp(e,t,!0))this.retry(e);else{var i;Mi.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ib(e,i.retry),i.retry++,Mi.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&a9.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const o9={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},l9=Oi(Oi({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:ML,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:b6,bufferController:c7,capLevelController:qb,errorController:w6,fpsController:dj,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ND,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:o9},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},u9()),{},{subtitleStreamController:Sj,subtitleTrackController:mj,timelineController:Wj,audioStreamController:a7,audioTrackController:o7,emeController:dc,cmcdController:oj,contentSteeringController:uj,interstitialsController:_j});function u9(){return{cueHandler:Zj,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function c9(s,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Dx(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(o=>{const u=`${o==="level"?"playlist":o}LoadPolicy`,c=e[u]===void 0,d=[];r.forEach(f=>{const p=`${o}Loading${f}`,g=e[p];if(g!==void 0&&c){d.push(p);const y=i[u].default;switch(e[u]={default:y},f){case"TimeOut":y.maxLoadTimeMs=g,y.maxTimeToFirstByteMs=g;break;case"MaxRetry":y.errorRetry.maxNumRetry=g,y.timeoutRetry.maxNumRetry=g;break;case"RetryDelay":y.errorRetry.retryDelayMs=g,y.timeoutRetry.retryDelayMs=g;break;case"MaxRetryTimeout":y.errorRetry.maxRetryDelayMs=g,y.timeoutRetry.maxRetryDelayMs=g;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${u}": ${Yi(e[u])}`)}),Oi(Oi({},i),e)}function Dx(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Dx):Object.keys(s).reduce((e,t)=>(e[t]=Dx(s[t]),e),{}):s}function d9(s,e){const t=s.loader;t!==xw&&t!==ML?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):Jj()&&(s.loader=xw,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Hm=2,h9=.1,f9=.05,m9=100;class p9 extends kD{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(U.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(U.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(U.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(m9),this.mediaSource=t.mediaSource;const i=this.media=t.media;yn(i,"playing",this.onMediaPlaying),yn(i,"waiting",this.onMediaWaiting),yn(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(Mn(i,"playing",this.onMediaPlaying),Mn(i,"waiting",this.onMediaWaiting),Mn(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,n;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const o=this.media;if(!o)return;const{seeking:u}=o,c=this.seeking&&!u,d=!this.seeking&&u,f=o.paused&&!u||o.ended||o.playbackRate===0;if(this.seeking=u,e!==t){t&&(this.ended=0),this.moved=!0,u||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!f&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||c){c&&this.stallResolved(e);return}if(f){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(U.MEDIA_ENDED,{stalled:!1}));return}if(!Yt.getBuffered(o).length){this.nudgeRetry=0;return}const p=Yt.bufferInfo(o,e,0),g=p.nextStart||0,y=this.fragmentTracker;if(u&&y&&this.hls){const V=bw(this.hls.inFlightFragments,e),M=p.len>Hm,z=!g||V||g-e>Hm&&!y.getPartialFragment(e);if(M||z)return;this.moved=!1}const x=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&y){if(!(p.len>0)&&!g)return;const M=Math.max(g,p.start||0)-e,O=!!(x!=null&&x.live)?x.targetduration*2:Hm,N=Am(e,y);if(M>0&&(M<=O||N)){o.paused||this._trySkipBufferHole(N);return}}const _=r.detectStallWithCurrentTimeMs,w=self.performance.now(),D=this.waiting;let I=this.stalled;if(I===null)if(D>0&&w-D<_)I=this.stalled=D;else{this.stalled=w;return}const L=w-I;if(!u&&(L>=_||D)&&this.hls){var B;if(((B=this.mediaSource)==null?void 0:B.readyState)==="ended"&&!(x!=null&&x.live)&&Math.abs(e-(x?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(U.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(p),!this.media||!this.hls)return}const j=Yt.bufferInfo(o,e,r.maxBufferHole);this._tryFixBufferStall(j,L,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(U.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&n&&n.length>1&&e>n.end(0)){const r=Yt.bufferedInfo(Yt.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const o=Yt.timeRangesToArray(n),u=Yt.bufferedInfo(o,t,0).bufferedIndex;if(u>-1&&uu)&&f-d<1&&e-d<2){const p=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${f} buffered index: ${c}`);this.warn(p.message),this.media.currentTime+=1e-6;let g=Am(e,this.fragmentTracker);g&&"fragment"in g?g=g.fragment:g||(g=void 0);const y=Yt.bufferInfo(this.media,e,0);this.hls.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,frag:g,buffer:y.len,bufferInfo:y})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:o,media:u}=this,c=(n=this.hls)==null?void 0:n.config;if(!u||!o||!c)return;const d=(r=this.hls)==null?void 0:r.latestLevelDetails,f=Am(i,o);if((f||d!=null&&d.live&&i1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-ic.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,n=e.nextStart;if(i&&n){const r=i.getFragAtPos(t,_t.MAIN),o=i.getFragAtPos(n,_t.MAIN);if(r&&o)return o.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:n,stalled:r}=this;if(!n&&r!==null&&i&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Yi(e)})`);this.warn(o.message),t.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:n}=this,r=(t=this.hls)==null?void 0:t.config;if(!n||!i||!r)return 0;const o=n.currentTime,u=Yt.bufferInfo(n,o,0),c=o0&&u.len<1&&n.readyState<3,g=c-o;if(g>0&&(f||p)){if(g>r.maxBufferHole){let x=!1;if(o===0){const _=i.getAppendedFrag(0,_t.MAIN);_&&c<_.end&&(x=!0)}if(!x&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||bw(this.hls.inFlightFragments,c))return 0;let w=!1,D=e.end;for(;D"u"))return self.VTTCue||self.TextTrackCue}function vv(s,e,t,i,n){let r=new s(e,t,"");try{r.value=i,n&&(r.type=n)}catch{r=new s(e,t,Yi(n?Oi({type:n},i):i))}return r}const Cm=(()=>{const s=Lx();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class y9{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(U.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(U.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(U.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(U.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(U.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(U.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(U.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(U.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Zu(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tCm&&(p=Cm),p-f<=0&&(p=f+g9);for(let y=0;yf.type===Zn.audioId3&&c:n==="video"?d=f=>f.type===Zn.emsg&&u:d=f=>f.type===Zn.audioId3&&c||f.type===Zn.emsg&&u,Cx(r,t,i,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:n,enableDateRangeMetadataCues:r,interstitialsController:o}=this.hls.config;if(!r)return;const u=Lx();if(i&&n&&!o){const{fragmentStart:_,fragmentEnd:w}=e;let D=this.assetCue;D?(D.startTime=_,D.endTime=w):u&&(D=this.assetCue=vv(u,_,w,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),D&&(D.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(D),D.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=e,f=Object.keys(d);let p=this.dateRangeCuesAppended;if(c&&t){var g;if((g=c.cues)!=null&&g.length){const _=Object.keys(p).filter(w=>!f.includes(w));for(let w=_.length;w--;){var y;const D=_[w],I=(y=p[D])==null?void 0:y.cues;delete p[D],I&&Object.keys(I).forEach(L=>{const B=I[L];if(B){B.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(B)}catch{}}})}}else p=this.dateRangeCuesAppended={}}const x=e.fragments[e.fragments.length-1];if(!(f.length===0||!gt(x?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(Q!==D.id){const Y=d[Q];if(Y.class===D.class&&Y.startDate>D.startDate&&(!q||D.startDate.01&&(Q.startTime=I,Q.endTime=V);else if(u){let Y=D.attr[q];U6(q)&&(Y=lD(Y));const Z=vv(u,I,V,{key:q,data:Y},Zn.dateRange);Z&&(Z.id=w,this.id3Track.addCue(Z),B[q]=Z,o&&(q==="X-ASSET-LIST"||q==="X-ASSET-URL")&&Z.addEventListener("enter",this.onEventCueEnter))}}p[w]={cues:B,dateRange:D,durationKnown:j}}}}}class v9{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:o}=this.config;if(!r||o===1||!i.live)return;const u=this.targetLatency;if(u===null)return;const c=n-u,d=Math.min(this.maxLatency,u+i.targetduration);if(c.05&&this.forwardBufferLength>1){const p=Math.min(2,Math.max(1,o)),g=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,y=Math.min(p,Math.max(1,g));this.changeMediaPlaybackRate(t,y)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:n}=e,{liveSyncDuration:r,liveSyncDurationCount:o,lowLatencyMode:u}=this.config,c=this.hls.userConfig;let d=u&&i||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=r!==void 0?r:o*n);const f=n;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,f)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const n=i.edge,r=e-t-this.edgeStalled,o=n-i.totalduration,u=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(o,r),u)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(U.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(U.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(U.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(U.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===we.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,n;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class x9 extends zb{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(U.LEVEL_LOADED,this.onLevelLoaded,this),e.on(U.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(U.FRAG_BUFFERED,this.onFragBuffered,this),e.on(U.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(U.LEVEL_LOADED,this.onLevelLoaded,this),e.off(U.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(U.FRAG_BUFFERED,this.onFragBuffered,this),e.off(U.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,n=[],r={},o={};let u=!1,c=!1,d=!1;t.levels.forEach(f=>{const p=f.attrs;let{audioCodec:g,videoCodec:y}=f;g&&(f.audioCodec=g=yp(g,i)||void 0),y&&(y=f.videoCodec=t6(y));const{width:x,height:_,unknownCodecs:w}=f,D=w?.length||0;if(u||(u=!!(x&&_)),c||(c=!!y),d||(d=!!g),D||g&&!this.isAudioSupported(g)||y&&!this.isVideoSupported(y)){this.log(`Some or all CODECS not supported "${p.CODECS}"`);return}const{CODECS:I,"FRAME-RATE":L,"HDCP-LEVEL":B,"PATHWAY-ID":j,RESOLUTION:V,"VIDEO-RANGE":M}=p,O=`${`${j||"."}-`}${f.bitrate}-${V}-${L}-${I}-${M}-${B}`;if(r[O])if(r[O].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const N=o[O]+=1;f.attrs["PATHWAY-ID"]=new Array(N+1).join(".");const q=this.createLevel(f);r[O]=q,n.push(q)}else r[O].addGroupId("audio",p.AUDIO),r[O].addGroupId("text",p.SUBTITLES);else{const N=this.createLevel(f);r[O]=N,o[O]=1,n.push(N)}}),this.filterAndSortMediaOptions(n,t,u,c,d)}createLevel(e){const t=new vh(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(n.message),t.supportedResult=bD(n,[])}return t}isAudioSupported(e){return gh(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return gh(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var o;let u=[],c=[],d=e;const f=((o=t.stats)==null?void 0:o.parsing)||{};if((i||n)&&r&&(d=d.filter(({videoCodec:I,videoRange:L,width:B,height:j})=>(!!I||!!(B&&j))&&d6(L))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let I="no level with compatible codecs found in manifest",L=I;t.levels.length&&(L=`one or more CODECS in variant not supported: ${Yi(t.levels.map(j=>j.attrs.CODECS).filter((j,V,M)=>M.indexOf(j)===V))}`,this.warn(L),I+=` (${L})`);const B=new Error(I);this.hls.trigger(U.ERROR,{type:Lt.MEDIA_ERROR,details:we.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:B,reason:L})}}),f.end=performance.now();return}t.audioTracks&&(u=t.audioTracks.filter(I=>!I.audioCodec||this.isAudioSupported(I.audioCodec)),_w(u)),t.subtitles&&(c=t.subtitles,_w(c));const p=d.slice(0);d.sort((I,L)=>{if(I.attrs["HDCP-LEVEL"]!==L.attrs["HDCP-LEVEL"])return(I.attrs["HDCP-LEVEL"]||"")>(L.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&I.height!==L.height)return I.height-L.height;if(I.frameRate!==L.frameRate)return I.frameRate-L.frameRate;if(I.videoRange!==L.videoRange)return vp.indexOf(I.videoRange)-vp.indexOf(L.videoRange);if(I.videoCodec!==L.videoCodec){const B=f2(I.videoCodec),j=f2(L.videoCodec);if(B!==j)return j-B}if(I.uri===L.uri&&I.codecSet!==L.codecSet){const B=gp(I.codecSet),j=gp(L.codecSet);if(B!==j)return j-B}return I.averageBitrate!==L.averageBitrate?I.averageBitrate-L.averageBitrate:0});let g=p[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==p.length)){for(let I=0;IB&&B===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=j)}break}const x=r&&!n,_=this.hls.config,w=!!(_.audioStreamController&&_.audioTrackController),D={levels:d,audioTracks:u,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:n,altAudio:w&&!x&&u.some(I=>!!I.url)};f.end=performance.now(),this.hls.trigger(U.MANIFEST_PARSED,D)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const f=new Error("invalid level idx"),p=e<0;if(this.hls.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.LEVEL_SWITCH_ERROR,level:e,fatal:p,error:f,reason:f.message}),p)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],u=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,i===e&&n&&r===u)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${u?" with Pathway "+u:""} from level ${i}${r?" with Pathway "+r:""}`);const c={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(U.LEVEL_SWITCHING,c);const d=o.details;if(!d||d.live){const f=this.switchParams(o.uri,n?.details,d);this.loadPlaylist(f)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===di.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===_t.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var i;const{level:n,details:r}=t,o=t.levelInfo;if(!o){var u;this.warn(`Invalid level index ${n}`),(u=t.deliveryDirectives)!=null&&u.skip&&(r.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let c=o.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(n,t,c)}else(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],o=e.details,u=o?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${u&&o.live?" age "+u.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger(U.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const i=this._levels.filter((r,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(u=>u.level=-1)),!1));$D(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(U.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(U.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function _w(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function PL(){return self.SourceBuffer||self.WebKitSourceBuffer}function BL(){if(!Xo())return!1;const e=PL();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function b9(){if(!BL())return!1;const s=Xo();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(yh(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(yh(e,"audio"))))}function T9(){var s;const e=PL();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const _9=100;class S9 extends Bb{constructor(e,t,i){super(e,t,i,"stream-controller",_t.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,r=n?n.currentTime:null;if(r===null||!gt(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const o=this.getFwdBufferInfoAtPos(n,r,_t.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(U.MANIFEST_PARSED,this.onManifestParsed,this),e.on(U.LEVEL_LOADING,this.onLevelLoading,this),e.on(U.LEVEL_LOADED,this.onLevelLoaded,this),e.on(U.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(U.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(U.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(U.BUFFER_CREATED,this.onBufferCreated,this),e.on(U.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(U.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(U.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(U.MANIFEST_PARSED,this.onManifestParsed,this),e.off(U.LEVEL_LOADED,this.onLevelLoaded,this),e.off(U.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(U.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(U.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(U.BUFFER_CREATED,this.onBufferCreated,this),e.off(U.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(U.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(U.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:n}=this;if(this.stopLoad(),this.setInterval(_9),this.level=-1,!this.startFragRequested){let r=n.startLevel;r===-1&&(n.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=n.firstAutoLevel),n.nextLoadLevel=r,this.level=n.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=ze.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=ze.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ze.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e?.[t],n=i?.details;if(n&&(!n.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(n))break;this.state=ze.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=ze.IDLE;break}break}case ze.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===ze.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const o=i[r],u=this.getMainFwdBufferInfo();if(u===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(u,c)){const _={};this.altAudio===2&&(_.type="video"),this.hls.trigger(U.BUFFER_EOS,_),this.state=ze.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const d=o.details;if(!d||this.state===ze.WAITING_LEVEL||this.waitForLive(o)){this.level=r,this.state=ze.WAITING_LEVEL,this.startFragRequested=!1;return}const f=u.len,p=this.getMaxBufferLength(o.maxBitrate);if(f>=p)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const g=this.backtrackFragment?this.backtrackFragment.start:u.end;let y=this.getNextFragment(g,d);if(this.couldBacktrack&&!this.fragPrevious&&y&&Ss(y)&&this.fragmentTracker.getState(y)!==Ps.OK){var x;const w=((x=this.backtrackFragment)!=null?x:y).sn-d.startSN,D=d.fragments[w-1];D&&y.cc===D.cc&&(y=D,this.fragmentTracker.removeFragment(D))}else this.backtrackFragment&&u.len&&(this.backtrackFragment=null);if(y&&this.isLoopLoading(y,g)){if(!y.gap){const w=this.audioOnly&&!this.altAudio?qi.AUDIO:qi.VIDEO,D=(w===qi.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;D&&this.afterBufferFlushed(D,w,_t.MAIN)}y=this.getNextFragmentLoopLoading(y,d,u,_t.MAIN,p)}y&&(y.initSegment&&!y.initSegment.data&&!this.bitrateTest&&(y=y.initSegment),this.loadFragment(y,o,g))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===Ps.NOT_LOADED||n===Ps.PARTIAL?Ss(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,_t.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const u=this.getMainFwdBufferInfo();if(!u||u.len=o-t.maxFragLookUpTolerance&&r<=u;if(n!==null&&i.duration>n&&(r{this.hls&&this.hls.trigger(U.AUDIO_TRACK_SWITCHED,t)}),i.trigger(U.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(U.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=xp(t.url,this.hls);if(i){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let n,r,o=!1;for(const u in i){const c=i[u];if(c.id==="main"){if(r=u,n=c,u==="video"){const d=i[u];d&&(this.videoBuffer=d.buffer)}}else o=!0}o&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:n}=t,r=i.type===_t.MAIN;if(r){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===ze.PARSED&&(this.state=ze.IDLE);return}const u=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*u.total/(u.buffering.end-u.loading.first)),Ss(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const o=this.media;o&&(!this._hasEnoughToStart&&Yt.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=ze.ERROR;return}switch(t.details){case we.FRAG_GAP:case we.FRAG_PARSING_ERROR:case we.FRAG_DECRYPT_ERROR:case we.FRAG_LOAD_ERROR:case we.FRAG_LOAD_TIMEOUT:case we.KEY_LOAD_ERROR:case we.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(_t.MAIN,t);break;case we.LEVEL_LOAD_ERROR:case we.LEVEL_LOAD_TIMEOUT:case we.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===ze.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===di.LEVEL&&(this.state=ze.IDLE);break;case we.BUFFER_ADD_CODEC_ERROR:case we.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case we.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case we.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=ze.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==qi.AUDIO||!this.altAudio){const i=(t===qi.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,_t.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(c{const{hls:n}=this,r=i?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=ze.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=r.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),n.trigger(U.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===ze.STOPPED||this.state===ze.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,o=this.getCurrentContext(r);if(!o){this.resetWhenMissingContext(r);return}const{frag:u,part:c,level:d}=o,{video:f,text:p,id3:g,initSegment:y}=n,{details:x}=d,_=this.altAudio?void 0:n.audio;if(this.fragContextChanged(u)){this.fragmentTracker.removeFragment(u);return}if(this.state=ze.PARSING,y){const w=y.tracks;if(w){const B=u.initSegment||u;if(this.unhandledEncryptionError(y,u))return;this._bufferInitSegment(d,w,B,r),i.trigger(U.FRAG_PARSING_INIT_SEGMENT,{frag:B,id:t,tracks:w})}const D=y.initPTS,I=y.timescale,L=this.initPTS[u.cc];if(gt(D)&&(!L||L.baseTime!==D||L.timescale!==I)){const B=y.trackId;this.initPTS[u.cc]={baseTime:D,timescale:I,trackId:B},i.trigger(U.INIT_PTS_FOUND,{frag:u,id:t,initPTS:D,timescale:I,trackId:B})}}if(f&&x){_&&f.type==="audiovideo"&&this.logMuxedErr(u);const w=x.fragments[u.sn-1-x.startSN],D=u.sn===x.startSN,I=!w||u.cc>w.cc;if(n.independent!==!1){const{startPTS:L,endPTS:B,startDTS:j,endDTS:V}=f;if(c)c.elementaryStreams[f.type]={startPTS:L,endPTS:B,startDTS:j,endDTS:V};else if(f.firstKeyFrame&&f.independent&&r.id===1&&!I&&(this.couldBacktrack=!0),f.dropped&&f.independent){const M=this.getMainFwdBufferInfo(),z=(M?M.end:this.getLoadPosition())+this.config.maxBufferHole,O=f.firstKeyFramePTS?f.firstKeyFramePTS:L;if(!D&&zHm&&(u.gap=!0);u.setElementaryStreamInfo(f.type,L,B,j,V),this.backtrackFragment&&(this.backtrackFragment=u),this.bufferFragmentData(f,u,c,r,D||I)}else if(D||I)u.gap=!0;else{this.backtrack(u);return}}if(_){const{startPTS:w,endPTS:D,startDTS:I,endDTS:L}=_;c&&(c.elementaryStreams[qi.AUDIO]={startPTS:w,endPTS:D,startDTS:I,endDTS:L}),u.setElementaryStreamInfo(qi.AUDIO,w,D,I,L),this.bufferFragmentData(_,u,c,r)}if(x&&g!=null&&g.samples.length){const w={id:t,frag:u,details:x,samples:g.samples};i.trigger(U.FRAG_PARSING_METADATA,w)}if(x&&p){const w={id:t,frag:u,details:x,samples:p.samples};i.trigger(U.FRAG_PARSING_USERDATA,w)}}logMuxedErr(e){this.warn(`${Ss(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==ze.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:o,audiovideo:u}=t;if(r){const d=e.audioCodec;let f=Mm(r.codec,d);f==="mp4a"&&(f="mp4a.40.5");const p=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){f&&(f.indexOf("mp4a.40.5")!==-1?f="mp4a.40.2":f="mp4a.40.5");const g=r.metadata;g&&"channelCount"in g&&(g.channelCount||1)!==1&&p.indexOf("firefox")===-1&&(f="mp4a.40.5")}f&&f.indexOf("mp4a.40.5")!==-1&&p.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(f="mp4a.40.2",this.log(`Android: force audio codec to ${f}`)),d&&d!==f&&this.log(`Swapping manifest audio codec "${d}" for "${f}"`),r.levelCodec=f,r.id=_t.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${f||""}/${d||""}/${r.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=_t.MAIN;const d=o.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${o.codec!==d?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo}u&&(this.log(`Init audiovideo buffer, container:${u.container}, codecs[level/parsed]=[${e.codecs}/${u.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(U.BUFFER_CODECS,t),!this.hls)return;c.forEach(d=>{const p=t[d].initSegment;p!=null&&p.byteLength&&this.hls.trigger(U.BUFFER_APPENDING,{type:d,data:p,frag:i,part:null,chunkMeta:n,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,_t.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=ze.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(Yt.isBuffered(e,i)?t=this.getAppendedFrag(i):Yt.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,r=t.level;(!n||t.sn!==n.sn||n.level!==r)&&(this.fragPlaying=t,this.hls.trigger(U.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(U.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return gt(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(gt(t)){const i=this.getLevelDetails(),n=this.currentFrag||(i?Yl(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const o=r+(t-n.start)*1e3;return new Date(o)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class E9 extends gr{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[i].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=we.KEY_LOAD_ERROR,i,n,r){return new Ba({type:Lt.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:n})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,r=t.length;n{if(!this.emeController)return;o.setKeyFormat(u);const c=Bm(u);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const n=Wd(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,n;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,we.KEY_LOAD_ERROR,d))}const o=r.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,we.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));const u=xv(r);let c=this.keyIdToKeyInfo[u];if((i=c)!=null&&i.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(n=c)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(f=>{const{keyInfo:p}=f;return r.key=p.decryptdata.key,{frag:e,keyInfo:p}})}switch(this.log(`${this.keyIdToKeyInfo[u]?"Rel":"L"}oading${r.keyId?" keyId: "+Xs(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[u]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,we.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const o=V8(t.initSegment.data);if(o.length){let u=o[0];u.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Xs(u)}`),qo.setKeyIdForUri(e.decryptdata.uri,u)):(u=qo.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Xs(u)}`)),e.decryptdata.keyId=u}}if(!e.decryptdata.keyId&&!Ss(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(o=>(e.mediaKeySessionContext=o,i))).catch(o=>{throw e.keyLoadPromise=null,"data"in o&&(o.data.frag=t),o})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,n=i.loader,r=new n(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((o,u)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},p={onSuccess:(g,y,x,_)=>{const{frag:w,keyInfo:D}=x,I=xv(D.decryptdata);if(!w.decryptdata||D!==this.keyIdToKeyInfo[I])return u(this.createKeyLoadError(w,we.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));D.decryptdata.key=w.decryptdata.key=new Uint8Array(g.data),w.keyLoader=null,D.loader=null,o({frag:w,keyInfo:D})},onError:(g,y,x,_)=>{this.resetLoader(y),u(this.createKeyLoadError(t,we.KEY_LOAD_ERROR,new Error(`HTTP Error ${g.code} loading key ${g.text}`),x,Oi({url:c.url,data:void 0},g)))},onTimeout:(g,y,x)=>{this.resetLoader(y),u(this.createKeyLoadError(t,we.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),x))},onAbort:(g,y,x)=>{this.resetLoader(y),u(this.createKeyLoadError(t,we.INTERNAL_ABORTED,new Error("key loading aborted"),x))}};r.load(c,f,p)})}resetLoader(e){const{frag:t,keyInfo:i,url:n}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const o=xv(i.decryptdata)||n;delete this.keyIdToKeyInfo[o],r&&r.destroy()}}function xv(s){if(s.keyFormat!==Qs.FAIRPLAY){const e=s.keyId;if(e)return Xs(e)}return s.uri}function Sw(s){const{type:e}=s;switch(e){case di.AUDIO_TRACK:return _t.AUDIO;case di.SUBTITLE_TRACK:return _t.SUBTITLE;default:return _t.MAIN}}function bv(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class w9{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(U.MANIFEST_LOADING,this.onManifestLoading,this),e.on(U.LEVEL_LOADING,this.onLevelLoading,this),e.on(U.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(U.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(U.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(U.MANIFEST_LOADING,this.onManifestLoading,this),e.off(U.LEVEL_LOADING,this.onLevelLoading,this),e.off(U.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(U.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(U.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,o=new r(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:di.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:o,deliveryDirectives:u,levelInfo:c}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:di.LEVEL,url:o,deliveryDirectives:u,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:di.AUDIO_TRACK,url:r,deliveryDirectives:o,levelOrTrack:u})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:di.SUBTITLE_TRACK,url:r,deliveryDirectives:o,levelOrTrack:u})}onLevelsUpdated(e,t){const i=this.loaders[di.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[di.LEVEL])}}load(e){var t;const i=this.hls.config;let n=this.getInternalLoader(e);if(n){const d=this.hls.logger,f=n.context;if(f&&f.levelOrTrack===e.levelOrTrack&&(f.url===e.url||f.deliveryDirectives&&!e.deliveryDirectives)){f.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${f.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(e.type===di.MANIFEST?r=i.manifestLoadPolicy.default:r=$i({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),gt((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===di.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===di.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===di.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const f=d.partTarget,p=d.targetduration;if(f&&p){const g=Math.max(f*3,p*.8)*1e3;r=$i({},r,{maxTimeToFirstByteMs:Math.min(g,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(g,r.maxTimeToFirstByteMs)})}}}const o=r.errorRetry||r.timeoutRetry||{},u={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(d,f,p,g)=>{const y=this.getInternalLoader(p);this.resetInternalLoader(p.type);const x=d.data;f.parsing.start=performance.now(),aa.isMediaPlaylist(x)||p.type!==di.MANIFEST?this.handleTrackOrLevelPlaylist(d,f,p,g||null,y):this.handleMasterPlaylist(d,f,p,g)},onError:(d,f,p,g)=>{this.handleNetworkError(f,p,!1,d,g)},onTimeout:(d,f,p)=>{this.handleNetworkError(f,p,!0,void 0,d)}};n.load(e,u,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,n){const r=this.hls,o=e.data,u=bv(e,i),c=aa.parseMasterPlaylist(o,u);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,c.playlistParsingError,n,t);return}const{contentSteering:d,levels:f,sessionData:p,sessionKeys:g,startTimeOffset:y,variableList:x}=c;this.variableList=x,f.forEach(I=>{const{unknownCodecs:L}=I;if(L){const{preferManagedMediaSource:B}=this.hls.config;let{audioCodec:j,videoCodec:V}=I;for(let M=L.length;M--;){const z=L[M];gh(z,"audio",B)?(I.audioCodec=j=j?`${j},${z}`:z,Ec.audio[j.substring(0,4)]=2,L.splice(M,1)):gh(z,"video",B)&&(I.videoCodec=V=V?`${V},${z}`:z,Ec.video[V.substring(0,4)]=2,L.splice(M,1))}}});const{AUDIO:_=[],SUBTITLES:w,"CLOSED-CAPTIONS":D}=aa.parseMasterPlaylistMedia(o,u,c);_.length&&!_.some(L=>!L.url)&&f[0].audioCodec&&!f[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),_.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new cs({}),bitrate:0,url:""})),r.trigger(U.MANIFEST_LOADED,{levels:f,audioTracks:_,subtitles:w,captions:D,contentSteering:d,url:u,stats:t,networkDetails:n,sessionData:p,sessionKeys:g,startTimeOffset:y,variableList:x})}handleTrackOrLevelPlaylist(e,t,i,n,r){const o=this.hls,{id:u,level:c,type:d}=i,f=bv(e,i),p=gt(c)?c:gt(u)?u:0,g=Sw(i),y=aa.parseLevelPlaylist(e.data,f,p,g,0,this.variableList);if(d===di.MANIFEST){const x={attrs:new cs({}),bitrate:0,details:y,name:"",url:f};y.requestScheduled=t.loading.start+FD(y,0),o.trigger(U.MANIFEST_LOADED,{levels:[x],audioTracks:[],url:f,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=y,this.handlePlaylistLoaded(y,e,t,i,n,r)}handleManifestParsingError(e,t,i,n,r){this.hls.trigger(U.ERROR,{type:Lt.NETWORK_ERROR,details:we.MANIFEST_PARSING_ERROR,fatal:t.type===di.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:n,stats:r})}handleNetworkError(e,t,i=!1,n,r){let o=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===di.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===di.AUDIO_TRACK||e.type===di.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const u=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let c=we.UNKNOWN,d=!1;const f=this.getInternalLoader(e);switch(e.type){case di.MANIFEST:c=i?we.MANIFEST_LOAD_TIMEOUT:we.MANIFEST_LOAD_ERROR,d=!0;break;case di.LEVEL:c=i?we.LEVEL_LOAD_TIMEOUT:we.LEVEL_LOAD_ERROR,d=!1;break;case di.AUDIO_TRACK:c=i?we.AUDIO_TRACK_LOAD_TIMEOUT:we.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case di.SUBTITLE_TRACK:c=i?we.SUBTITLE_TRACK_LOAD_TIMEOUT:we.SUBTITLE_LOAD_ERROR,d=!1;break}f&&this.resetInternalLoader(e.type);const p={type:Lt.NETWORK_ERROR,details:c,fatal:d,url:e.url,loader:f,context:e,error:u,networkDetails:t,stats:r};if(n){const g=t?.url||e.url;p.response=Oi({url:g,data:void 0},n)}this.hls.trigger(U.ERROR,p)}handlePlaylistLoaded(e,t,i,n,r,o){const u=this.hls,{type:c,level:d,levelOrTrack:f,id:p,groupId:g,deliveryDirectives:y}=n,x=bv(t,n),_=Sw(n);let w=typeof n.level=="number"&&_===_t.MAIN?d:void 0;const D=e.playlistParsingError;if(D){if(this.hls.logger.warn(`${D} ${e.url}`),!u.config.ignorePlaylistParsingErrors){u.trigger(U.ERROR,{type:Lt.NETWORK_ERROR,details:we.LEVEL_PARSING_ERROR,fatal:!1,url:x,error:D,reason:D.message,response:t,context:n,level:w,parent:_,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const I=e.playlistParsingError=new Error("No Segments found in Playlist");u.trigger(U.ERROR,{type:Lt.NETWORK_ERROR,details:we.LEVEL_EMPTY_ERROR,fatal:!1,url:x,error:I,reason:I.message,response:t,context:n,level:w,parent:_,networkDetails:r,stats:i});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case di.MANIFEST:case di.LEVEL:if(w){if(!f)w=0;else if(f!==u.levels[w]){const I=u.levels.indexOf(f);I>-1&&(w=I)}}u.trigger(U.LEVEL_LOADED,{details:e,levelInfo:f||u.levels[0],level:w||0,id:p||0,stats:i,networkDetails:r,deliveryDirectives:y,withoutMultiVariant:c===di.MANIFEST});break;case di.AUDIO_TRACK:u.trigger(U.AUDIO_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:y});break;case di.SUBTITLE_TRACK:u.trigger(U.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:y});break}}}class Jn{static get version(){return xh}static isMSESupported(){return BL()}static isSupported(){return b9()}static getMediaSource(){return Xo()}static get Events(){return U}static get MetadataSchema(){return Zn}static get ErrorTypes(){return Lt}static get ErrorDetails(){return we}static get DefaultConfig(){return Jn.defaultConfig?Jn.defaultConfig:l9}static set DefaultConfig(e){Jn.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Fb,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=R8(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=c9(Jn.DefaultConfig,e,t);this.userConfig=e,i.progressive&&d9(i,t);const{abrController:n,bufferController:r,capLevelController:o,errorController:u,fpsController:c}=i,d=new u(this),f=this.abrController=new n(this),p=new A6(this),g=i.interstitialsController,y=g?this.interstitialsController=new g(this,Jn):null,x=this.bufferController=new r(this,p),_=this.capLevelController=new o(this),w=new c(this),D=new w9(this),I=i.contentSteeringController,L=I?new I(this):null,B=this.levelController=new x9(this,L),j=new y9(this),V=new E9(this.config,this.logger),M=this.streamController=new S9(this,p,V),z=this.gapController=new p9(this,p);_.setStreamController(M),w.setStreamController(M);const O=[D,B,M];y&&O.splice(1,0,y),L&&O.splice(1,0,L),this.networkControllers=O;const N=[f,x,z,_,w,j,p];this.audioTrackController=this.createController(i.audioTrackController,O);const q=i.audioStreamController;q&&O.push(this.audioStreamController=new q(this,p,V)),this.subtitleTrackController=this.createController(i.subtitleTrackController,O);const Q=i.subtitleStreamController;Q&&O.push(this.subtititleStreamController=new Q(this,p,V)),this.createController(i.timelineController,N),V.emeController=this.emeController=this.createController(i.emeController,N),this.cmcdController=this.createController(i.cmcdController,N),this.latencyController=this.createController(v9,N),this.coreComponents=N,O.push(d);const Y=d.onErrorOut;typeof Y=="function"&&this.on(U.ERROR,Y,d),this.on(U.MANIFEST_LOADED,D.onManifestLoaded,D)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,n){this._emitter.off(e,t,i,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const n=e===U.ERROR;this.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.INTERNAL_EXCEPTION,fatal:n,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(U.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(U.ERROR,{type:Lt.OTHER_ERROR,details:we.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,n=t?e:{media:i};this._media=i,this.trigger(U.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(U.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(U.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=Cb.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&i&&(i!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(U.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", ":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[_t.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[_t.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[_t.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=pj()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){c6(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let n=0;n=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,i)for(let r=n;r--;){const o=e[r].attrs["HDCP-LEVEL"];if(o&&o<=i)return r}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=SD(t);return TD(e,i,navigator.mediaCapabilities)}}Jn.defaultConfig=void 0;function Ew(s,e){const t=s.includes("?")?"&":"?";return`${s}${t}v=${e}`}function A9({src:s,muted:e=Ym,className:t}){const i=k.useRef(null),[n,r]=k.useState(!1),[o,u]=k.useState(null),c=k.useMemo(()=>Ew(s,Date.now()),[s]);return k.useEffect(()=>{let d=!1,f=null,p=null,g=null;const y=i.current;if(!y)return;const x=y;r(!1),u(null),gA(x,{muted:e});const _=()=>{p&&window.clearTimeout(p),g&&window.clearInterval(g),p=null,g=null},w=()=>{if(d)return;_();try{x.pause()}catch{}x.removeAttribute("src"),x.load();const B=Ew(s,Date.now());x.src=B,x.load(),x.play().catch(()=>{})};async function D(){const B=Date.now();for(;!d&&Date.now()-B<2e4;){try{const j=await fetch(c,{cache:"no-store"});if(j.status===403)return{ok:!1,reason:"private"};if(j.status===404)return{ok:!1,reason:"offline"};if(j.status!==204){if(j.ok&&(await j.text()).includes("#EXTINF"))return{ok:!0}}}catch{}await new Promise(j=>setTimeout(j,400))}return{ok:!1}}async function I(){const B=await D();if(!B.ok||d){d||(u(B.reason??null),r(!0));return}if(x.canPlayType("application/vnd.apple.mpegurl")){x.src=c,x.load(),x.play().catch(()=>{});let j=Date.now(),V=-1;const M=()=>{x.currentTime>V+.01&&(V=x.currentTime,j=Date.now())},z=()=>{p||(p=window.setTimeout(()=>{p=null,!d&&Date.now()-j>3500&&w()},800))};return x.addEventListener("timeupdate",M),x.addEventListener("waiting",z),x.addEventListener("stalled",z),x.addEventListener("error",z),g=window.setInterval(()=>{d||!x.paused&&Date.now()-j>6e3&&w()},2e3),()=>{x.removeEventListener("timeupdate",M),x.removeEventListener("waiting",z),x.removeEventListener("stalled",z),x.removeEventListener("error",z)}}if(!Jn.isSupported()){r(!0);return}f=new Jn({lowLatencyMode:!0,liveSyncDurationCount:2,maxBufferLength:8}),f.on(Jn.Events.ERROR,(j,V)=>{if(f&&V.fatal){if(V.type===Jn.ErrorTypes.NETWORK_ERROR){f.startLoad();return}if(V.type===Jn.ErrorTypes.MEDIA_ERROR){f.recoverMediaError();return}r(!0)}}),f.loadSource(c),f.attachMedia(x),f.on(Jn.Events.MANIFEST_PARSED,()=>{x.play().catch(()=>{})})}let L;return(async()=>{const B=await I();typeof B=="function"&&(L=B)})(),()=>{d=!0,_();try{L?.()}catch{}f?.destroy()}},[s,c,e]),n?v.jsx("div",{className:"text-xs text-gray-400 italic",children:o==="private"?"Private":o==="offline"?"Offline":"–"}):v.jsx("video",{ref:i,className:t,playsInline:!0,autoPlay:!0,muted:e,onClick:()=>{const d=i.current;d&&(d.muted=!1,d.play().catch(()=>{}))}})}function FL({jobId:s,thumbTick:e,autoTickMs:t=1e4,blur:i=!1,alignStartAt:n,alignEndAt:r=null,alignEveryMs:o,fastRetryMs:u,fastRetryMax:c,fastRetryWindowMs:d,className:f}){const[p,g]=k.useState(()=>typeof document>"u"?!0:!document.hidden),y=i?"blur-md":"",[x,_]=k.useState(0),[w,D]=k.useState(!1),I=k.useRef(null),[L,B]=k.useState(!1),j=k.useRef(null),V=k.useRef(0),M=k.useRef(!1),z=k.useRef(!1),O=Y=>{if(typeof Y=="number"&&Number.isFinite(Y))return Y;if(Y instanceof Date)return Y.getTime();const re=Date.parse(String(Y??""));return Number.isFinite(re)?re:NaN};k.useEffect(()=>{const Y=()=>g(!document.hidden);return document.addEventListener("visibilitychange",Y),()=>document.removeEventListener("visibilitychange",Y)},[]),k.useEffect(()=>()=>{j.current&&window.clearTimeout(j.current)},[]),k.useEffect(()=>{typeof e!="number"&&(!L||!p||z.current||(z.current=!0,_(Y=>Y+1)))},[L,e,p]),k.useEffect(()=>{if(typeof e=="number"||!L||!p)return;const Y=Number(o??t??1e4);if(!Number.isFinite(Y)||Y<=0)return;const re=n?O(n):NaN,Z=r?O(r):NaN;if(Number.isFinite(re)){let K;const ie=()=>{const te=Date.now();if(Number.isFinite(Z)&&te>=Z)return;const $=Math.max(0,te-re)%Y,ee=$===0?Y:Y-$;K=window.setTimeout(()=>{_(le=>le+1),ie()},ee)};return ie(),()=>{K&&window.clearTimeout(K)}}const H=window.setInterval(()=>{_(K=>K+1)},Y);return()=>window.clearInterval(H)},[e,t,L,p,n,r,o]),k.useEffect(()=>{const Y=I.current;if(!Y)return;const re=new IntersectionObserver(Z=>{const H=Z[0];B(!!(H&&(H.isIntersecting||H.intersectionRatio>0)))},{root:null,threshold:0,rootMargin:"300px 0px"});return re.observe(Y),()=>re.disconnect()},[]);const N=typeof e=="number"?e:x;k.useEffect(()=>{D(!1)},[N]),k.useEffect(()=>{M.current=!1,V.current=0,z.current=!1,D(!1),_(Y=>Y+1)},[s]);const q=k.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&v=${N}`,[s,N]),Q=k.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&file=index_hq.m3u8`,[s]);return v.jsx(pA,{content:(Y,{close:re})=>Y&&v.jsx("div",{className:"w-[420px] max-w-[calc(100vw-1.5rem)]",children:v.jsxs("div",{className:"relative aspect-video overflow-hidden rounded-lg bg-black",children:[v.jsx(A9,{src:Q,muted:!1,className:["w-full h-full relative z-0"].filter(Boolean).join(" ")}),v.jsxs("div",{className:"absolute left-2 top-2 inline-flex items-center gap-1.5 rounded-full bg-red-600/90 px-2 py-1 text-[11px] font-semibold text-white shadow-sm",children:[v.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]}),v.jsx("button",{type:"button",className:"absolute right-2 top-2 z-20 inline-flex items-center justify-center rounded-md p-1.5 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white/70 bg-white/75 text-gray-900 ring-1 ring-black/10 hover:bg-white/90 dark:bg-black/40 dark:text-white dark:ring-white/10 dark:hover:bg-black/55","aria-label":"Live-Vorschau schließen",title:"Vorschau schließen",onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),re()},children:v.jsx($x,{className:"h-4 w-4"})})]})}),children:v.jsx("div",{ref:I,className:["block relative rounded bg-gray-100 dark:bg-white/5 overflow-hidden",f||"w-full h-full"].join(" "),children:w?v.jsx("div",{className:"absolute inset-0 grid place-items-center px-1 text-center text-[10px] text-gray-500 dark:text-gray-400",children:"keine Vorschau"}):v.jsx("img",{src:q,loading:L?"eager":"lazy",fetchPriority:L?"high":"auto",alt:"",className:["block w-full h-full object-cover object-center",y].filter(Boolean).join(" "),onLoad:()=>{M.current=!0,V.current=0,j.current&&window.clearTimeout(j.current),D(!1)},onError:()=>{if(D(!0),!u||!L||!p||M.current)return;const Y=n?O(n):NaN,re=Number(d??6e4);if(!(!Number.isFinite(Y)||Date.now()-Y=H||(j.current&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{V.current+=1,_(K=>K+1)},u))}})})})}const Ac=new Map;let ww=!1;function C9(){ww||(ww=!0,document.addEventListener("visibilitychange",()=>{if(document.hidden)for(const s of Ac.values())s.es&&(s.es.close(),s.es=null,s.dispatchers.clear());else for(const s of Ac.values())s.refs>0&&!s.es&&UL(s)}))}function UL(s){if(!s.es&&!document.hidden){s.es=new EventSource(s.url);for(const[e,t]of s.listeners.entries()){const i=n=>{let r=null;try{r=JSON.parse(String(n.data??"null"))}catch{return}for(const o of t)o(r)};s.dispatchers.set(e,i),s.es.addEventListener(e,i)}s.es.onerror=()=>{}}}function k9(s){s.es&&(s.es.close(),s.es=null,s.dispatchers.clear())}function D9(s){let e=Ac.get(s);return e||(e={url:s,es:null,refs:0,listeners:new Map,dispatchers:new Map},Ac.set(s,e)),e}function jL(s,e,t){C9();const i=D9(s);let n=i.listeners.get(e);if(n||(n=new Set,i.listeners.set(e,n)),n.add(t),i.refs+=1,i.es){if(!i.dispatchers.has(e)){const r=o=>{let u=null;try{u=JSON.parse(String(o.data??"null"))}catch{return}for(const c of i.listeners.get(e)??[])c(u)};i.dispatchers.set(e,r),i.es.addEventListener(e,r)}}else UL(i);return()=>{const r=Ac.get(s);if(!r)return;const o=r.listeners.get(e);o&&(o.delete(t),o.size===0&&r.listeners.delete(e)),r.refs=Math.max(0,r.refs-1),r.refs===0&&(k9(r),Ac.delete(s))}}const Cp=s=>{const e=s;return e.modelName??e.model??e.modelKey??e.username??e.name??"—"},$L=s=>{const e=s;return e.sourceUrl??e.url??e.roomUrl??""},HL=s=>{const e=s;return String(e.imageUrl??e.image_url??"").trim()},Aw=s=>{const e=s;return String(e.key??e.id??Cp(s))},wr=s=>{if(typeof s=="number"&&Number.isFinite(s))return s<1e12?s*1e3:s;if(typeof s=="string"){const e=Date.parse(s);return Number.isFinite(e)?e:0}return s instanceof Date?s.getTime():0},Cw=s=>{if(s.kind==="job"){const t=s.job;return wr(t.addedAt)||wr(t.createdAt)||wr(t.enqueuedAt)||wr(t.queuedAt)||wr(t.requestedAt)||wr(t.startedAt)||0}const e=s.pending;return wr(e.addedAt)||wr(e.createdAt)||wr(e.enqueuedAt)||wr(e.queuedAt)||wr(e.requestedAt)||0},VL=s=>{switch(s){case"stopping":return"Stop wird angefordert…";case"remuxing":return"Remux zu MP4…";case"moving":return"Verschiebe nach Done…";case"assets":return"Erstelle Vorschau…";default:return""}};async function L9(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}function R9({job:s}){const e=String(s?.phase??"").trim(),t=Number(s?.progress??0),n=(e?VL(e)||e:"")||String(s?.status??"").trim().toLowerCase(),r=Number.isFinite(t)&&t>0&&t<100,o=!r&&!!e&&(!Number.isFinite(t)||t<=0||t>=100);return v.jsx("div",{className:"min-w-0",children:r?v.jsx(fc,{label:n,value:Math.max(0,Math.min(100,t)),showPercent:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):o?v.jsx(fc,{label:n,indeterminate:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):v.jsx("div",{className:"truncate",children:v.jsx("span",{className:"font-medium",children:n})})})}function I9({r:s,nowMs:e,blurPreviews:t,modelsByKey:i,stopRequestedIds:n,markStopRequested:r,onOpenPlayer:o,onStopJob:u,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f}){if(s.kind==="pending"){const Y=s.pending,re=Cp(Y),Z=$L(Y),H=(Y.currentShow||"unknown").toLowerCase();return v.jsxs("div",{className:` + relative overflow-hidden rounded-2xl border border-white/40 bg-white/35 shadow-sm + backdrop-blur-xl supports-[backdrop-filter]:bg-white/25 + ring-1 ring-black/5 + transition-all hover:-translate-y-0.5 hover:shadow-md active:translate-y-0 + dark:border-white/10 dark:bg-gray-950/35 dark:supports-[backdrop-filter]:bg-gray-950/25 + `,children:[v.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-br from-white/70 via-white/20 to-white/60 dark:from-white/10 dark:via-transparent dark:to-white/5"}),v.jsxs("div",{className:"relative p-3",children:[v.jsxs("div",{className:"flex items-start justify-between gap-2",children:[v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",title:re,children:re}),v.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[v.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-900/5 px-2 py-0.5 font-medium dark:bg-white/10",children:"Wartend"}),v.jsx("span",{className:"inline-flex items-center rounded-full bg-gray-900/5 px-2 py-0.5 text-[11px] font-medium uppercase tracking-wide text-gray-700 dark:bg-white/10 dark:text-gray-200",children:H})]})]}),v.jsx("span",{className:"shrink-0 rounded-full bg-gray-900/5 px-2.5 py-1 text-xs font-medium text-gray-800 dark:bg-white/10 dark:text-gray-200",children:"⏳"})]}),v.jsx("div",{className:"mt-3",children:(()=>{const K=HL(Y);return v.jsx("div",{className:"relative aspect-[16/9] w-full overflow-hidden rounded-xl bg-gray-100 ring-1 ring-black/5 dark:bg-white/10 dark:ring-white/10",children:K?v.jsx("img",{src:K,alt:re,className:["h-full w-full object-cover",t?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:ie=>{ie.currentTarget.style.display="none"}}):v.jsx("div",{className:"grid h-full w-full place-items-center",children:v.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-300",children:"Waiting…"})})})})()}),Z?v.jsx("a",{href:Z,target:"_blank",rel:"noreferrer",className:"mt-3 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:K=>K.stopPropagation(),title:Z,children:Z}):null]})]})}const p=s.job,g=Rx(p.output),y=Qb(p.output||""),x=String(p.phase??"").trim(),_=x?VL(x)||x:"",w=!!n[p.id],D=String(p.status??"").toLowerCase(),I=!!x||D!=="running"||w,L=D||"unknown",B=_||L,j=Number(p.progress??0),V=Number.isFinite(j)&&j>0&&j<100,M=!V&&!!x&&(!Number.isFinite(j)||j<=0||j>=100),z=g&&g!=="—"?g.toLowerCase():"",O=z?i[z]:void 0,N=!!O?.favorite,q=O?.liked===!0,Q=!!O?.watching;return v.jsxs("div",{className:` + group relative overflow-hidden rounded-2xl border border-white/40 bg-white/35 shadow-sm + backdrop-blur-xl supports-[backdrop-filter]:bg-white/25 + ring-1 ring-black/5 + transition-all hover:-translate-y-0.5 hover:shadow-md active:translate-y-0 + dark:border-white/10 dark:bg-gray-950/35 dark:supports-[backdrop-filter]:bg-gray-950/25 + `,onClick:()=>o(p),role:"button",tabIndex:0,onKeyDown:Y=>{(Y.key==="Enter"||Y.key===" ")&&o(p)},children:[v.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-br from-white/70 via-white/20 to-white/60 dark:from-white/10 dark:via-transparent dark:to-white/5"}),v.jsx("div",{className:"pointer-events-none absolute -inset-10 opacity-0 blur-2xl transition-opacity duration-300 group-hover:opacity-100 bg-white/40 dark:bg-white/10"}),v.jsxs("div",{className:"relative p-3",children:[v.jsxs("div",{className:"flex items-start gap-3",children:[v.jsx("div",{className:` + relative + shrink-0 overflow-hidden rounded-lg + w-[112px] h-[64px] + bg-gray-100 ring-1 ring-black/5 + dark:bg-white/10 dark:ring-white/10 + `,children:v.jsx(FL,{jobId:p.id,blur:t,alignStartAt:p.startedAt,alignEndAt:p.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsxs("div",{className:"flex items-start justify-between gap-2",children:[v.jsxs("div",{className:"min-w-0",children:[v.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[v.jsx("div",{className:"truncate text-base font-semibold text-gray-900 dark:text-white",title:g,children:g}),v.jsx("span",{className:["shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold","bg-gray-900/5 text-gray-800 dark:bg-white/10 dark:text-gray-200",I?"ring-1 ring-amber-500/30":"ring-1 ring-emerald-500/25"].join(" "),title:L,children:L})]}),v.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-600 dark:text-gray-300",title:p.output,children:y||"—"})]}),v.jsxs("div",{className:"shrink-0 flex flex-col items-end gap-1",children:[v.jsx("span",{className:"rounded-full bg-gray-900/5 px-2 py-0.5 text-[11px] font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:GL(p,e)}),v.jsx("span",{className:"rounded-full bg-gray-900/5 px-2 py-0.5 text-[11px] font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:qL(zL(p))})]})]}),p.sourceUrl?v.jsx("a",{href:p.sourceUrl,target:"_blank",rel:"noreferrer",className:"mt-1 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:Y=>Y.stopPropagation(),title:p.sourceUrl,children:p.sourceUrl}):null]})]}),V||M?v.jsx("div",{className:"mt-3",children:V?v.jsx(fc,{label:B,value:Math.max(0,Math.min(100,j)),showPercent:!0,size:"sm",className:"w-full"}):v.jsx(fc,{label:B,indeterminate:!0,size:"sm",className:"w-full"})}):null,v.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2 border-t border-white/30 pt-3 dark:border-white/10",children:[v.jsx("div",{className:"flex items-center gap-1",onClick:Y=>Y.stopPropagation(),onMouseDown:Y=>Y.stopPropagation(),children:v.jsx(Ko,{job:p,variant:"table",busy:I,isFavorite:N,isLiked:q,isWatching:Q,showHot:!1,showKeep:!1,showDelete:!1,showFavorite:!0,showLike:!0,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,order:["watch","favorite","like","details"],className:"flex items-center gap-1"})}),v.jsx(_i,{size:"sm",variant:"primary",disabled:I,className:"shrink-0",onClick:Y=>{Y.stopPropagation(),!I&&(r(p.id),u(p.id))},children:I?"Stoppe…":"Stop"})]})]})]})}const Qb=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",Rx=s=>{const e=Qb(s||"");if(!e)return"—";const t=e.replace(/\.[^.]+$/,""),i=t.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(i?.[1])return i[1];const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t},N9=s=>{if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`},GL=(s,e)=>{const t=Date.parse(String(s.startedAt||""));if(!Number.isFinite(t))return"—";const i=s.endedAt?Date.parse(String(s.endedAt)):e;return Number.isFinite(i)?N9(i-t):"—"},zL=s=>{const e=s,t=e.sizeBytes??e.fileSizeBytes??e.bytes??e.size??null;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null},qL=s=>{if(!s||!Number.isFinite(s)||s<=0)return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(n).replace(/\.0+$/,"")} ${e[i]}`};function O9({jobs:s,pending:e=[],onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:o,modelsByKey:u={},blurPreviews:c}){const[d,f]=k.useState(!1),[p,g]=k.useState(!1),[y,x]=k.useState(!1),_=k.useCallback(async()=>{try{const H=await L9("/api/autostart/state",{cache:"no-store"});g(!!H?.paused)}catch{}},[]);k.useEffect(()=>{_();const H=jL("/api/autostart/state/stream","autostart",K=>g(!!K?.paused));return()=>{H()}},[_]);const w=k.useCallback(async()=>{if(!(y||p)){x(!0);try{await fetch("/api/autostart/pause",{method:"POST"}),g(!0)}catch{}finally{x(!1)}}},[y,p]),D=k.useCallback(async()=>{if(!(y||!p)){x(!0);try{await fetch("/api/autostart/resume",{method:"POST"}),g(!1)}catch{}finally{x(!1)}}},[y,p]),[I,L]=k.useState({}),[B,j]=k.useState({}),V=k.useCallback(H=>{const K=Array.isArray(H)?H:[H];L(ie=>{const te={...ie};for(const ne of K)ne&&(te[ne]=!0);return te}),j(ie=>{const te={...ie};for(const ne of K)ne&&(te[ne]=!0);return te})},[]);k.useEffect(()=>{L(H=>{const K=Object.keys(H);if(K.length===0)return H;const ie={};for(const te of K){const ne=s.find(le=>le.id===te);if(!ne)continue;String(ne.phase??"").trim()||ne.status!=="running"||(ie[te]=!0)}return ie})},[s]);const[M,z]=k.useState(()=>Date.now()),O=k.useMemo(()=>s.some(H=>!H.endedAt&&H.status==="running"),[s]);k.useEffect(()=>{if(!O)return;const H=window.setInterval(()=>z(Date.now()),1e3);return()=>window.clearInterval(H)},[O]);const N=k.useMemo(()=>s.filter(H=>{const K=String(H.phase??"").trim(),ie=!!I[H.id];return!(!!K||H.status!=="running"||ie)}).map(H=>H.id),[s,I]),q=k.useMemo(()=>[{key:"preview",header:"Vorschau",widthClassName:"w-[96px]",cell:H=>{if(H.kind==="job"){const ne=H.job;return v.jsx("div",{className:"grid w-[96px] h-[60px] overflow-hidden rounded-md",children:v.jsx(FL,{jobId:ne.id,blur:c,alignStartAt:ne.startedAt,alignEndAt:ne.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})})}const K=H.pending,ie=Cp(K),te=HL(K);return te?v.jsx("div",{className:"grid w-[96px] h-[60px] overflow-hidden rounded-md bg-gray-100 ring-1 ring-black/5 dark:bg-white/10 dark:ring-white/10",children:v.jsx("img",{src:te,alt:ie,className:["h-full w-full object-cover",c?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:ne=>{ne.currentTarget.style.display="none"}})}):v.jsx("div",{className:"h-[60px] w-[96px] rounded-md bg-gray-100 dark:bg-white/10 grid place-items-center text-sm text-gray-500",children:"⏳"})}},{key:"model",header:"Modelname",widthClassName:"w-[170px]",cell:H=>{if(H.kind==="job"){const ne=H.job,$=Qb(ne.output||""),ee=Rx(ne.output),le=String(ne.phase??"").trim(),be=!!I[ne.id],fe=!!B[ne.id],_e=String(ne.status??"").toLowerCase(),Me=_e==="stopped"||fe&&!!ne.endedAt,et=!!le||_e!=="running"||be,Ge=_e||"unknown";return v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[v.jsx("span",{className:"min-w-0 block max-w-[170px] truncate font-medium",title:ee,children:ee}),v.jsx("span",{className:["shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold ring-1",et?"bg-amber-500/15 text-amber-900 ring-amber-500/30 dark:bg-amber-400/10 dark:text-amber-200 dark:ring-amber-400/25":ne.status==="finished"?"bg-emerald-500/15 text-emerald-900 ring-emerald-500/30 dark:bg-emerald-400/10 dark:text-emerald-200 dark:ring-emerald-400/25":ne.status==="failed"?"bg-red-500/15 text-red-900 ring-red-500/30 dark:bg-red-400/10 dark:text-red-200 dark:ring-red-400/25":Me?"bg-amber-500/15 text-amber-900 ring-amber-500/30 dark:bg-amber-400/10 dark:text-amber-200 dark:ring-amber-400/25":"bg-gray-900/5 text-gray-800 ring-gray-900/10 dark:bg-white/10 dark:text-gray-200 dark:ring-white/10"].join(" "),title:Ge,children:Ge})]}),v.jsx("span",{className:"block max-w-[220px] truncate",title:ne.output,children:$}),ne.sourceUrl?v.jsx("a",{href:ne.sourceUrl,target:"_blank",rel:"noreferrer",title:ne.sourceUrl,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:lt=>lt.stopPropagation(),children:ne.sourceUrl}):v.jsx("span",{className:"block max-w-[260px] truncate text-gray-500 dark:text-gray-400",children:"—"})]})}const K=H.pending,ie=Cp(K),te=$L(K);return v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"block max-w-[170px] truncate font-medium",title:ie,children:ie}),te?v.jsx("a",{href:te,target:"_blank",rel:"noreferrer",title:te,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:ne=>ne.stopPropagation(),children:te}):v.jsx("span",{className:"block max-w-[260px] truncate text-gray-500 dark:text-gray-400",children:"—"})]})}},{key:"status",header:"Status",widthClassName:"w-[260px] min-w-[240px]",cell:H=>{if(H.kind==="job"){const te=H.job;return v.jsx(R9,{job:te})}const ie=(H.pending.currentShow||"unknown").toLowerCase();return v.jsx("div",{className:"min-w-0",children:v.jsx("div",{className:"truncate",children:v.jsx("span",{className:"font-medium",children:ie})})})}},{key:"runtime",header:"Dauer",widthClassName:"w-[90px]",cell:H=>H.kind==="job"?GL(H.job,M):"—"},{key:"size",header:"Größe",align:"right",widthClassName:"w-[110px]",cell:H=>H.kind==="job"?v.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white",children:qL(zL(H.job))}):v.jsx("span",{className:"tabular-nums text-sm text-gray-500 dark:text-gray-400",children:"—"})},{key:"actions",header:"Aktion",srOnlyHeader:!0,align:"right",widthClassName:"w-[320px] min-w-[300px]",cell:H=>{if(H.kind!=="job")return v.jsx("div",{className:"pr-2 text-right text-sm text-gray-500 dark:text-gray-400",children:"—"});const K=H.job,ie=String(K.phase??"").trim(),te=!!I[K.id],ne=!!ie||K.status!=="running"||te,$=Rx(K.output||""),ee=$&&$!=="—"?u[$.toLowerCase()]:void 0,le=!!ee?.favorite,be=ee?.liked===!0,fe=!!ee?.watching;return v.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pr-2",children:[v.jsx(Ko,{job:K,variant:"table",busy:ne,isFavorite:le,isLiked:be,isWatching:fe,showHot:!1,showKeep:!1,showDelete:!1,showFavorite:!0,showLike:!0,onToggleFavorite:n,onToggleLike:r,onToggleWatch:o,order:["watch","favorite","like","details"],className:"flex items-center gap-1"}),(()=>{const _e=String(K.phase??"").trim(),Me=!!I[K.id],et=!!_e||K.status!=="running"||Me;return v.jsx(_i,{size:"sm",variant:"primary",disabled:et,className:"shrink-0",onClick:Ge=>{Ge.stopPropagation(),!et&&(V(K.id),i(K.id))},children:et?"Stoppe…":"Stop"})})()]})}}],[c,V,u,M,i,n,r,o,I,B]),Q=e.length>0,Y=s.length>0,re=k.useMemo(()=>{const H=[...s.map(K=>({kind:"job",job:K})),...e.map(K=>({kind:"pending",pending:K}))];return H.sort((K,ie)=>Cw(ie)-Cw(K)),H},[s,e]),Z=k.useCallback(async()=>{if(!d&&N.length!==0){f(!0);try{V(N),await Promise.allSettled(N.map(H=>Promise.resolve(i(H))))}finally{f(!1)}}},[d,N,V,i]);return v.jsxs("div",{className:"grid gap-3",children:[Q||Y?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"sticky top-[56px] z-20",children:v.jsx("div",{className:` + rounded-xl border border-gray-200/70 bg-white/80 shadow-sm + backdrop-blur supports-[backdrop-filter]:bg-white/60 + dark:border-white/10 dark:bg-gray-950/60 dark:supports-[backdrop-filter]:bg-gray-950/40 + `,children:v.jsxs("div",{className:"flex items-center justify-between gap-2 p-3",children:[v.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[v.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Downloads"}),v.jsx("span",{className:"shrink-0 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-gray-200",children:re.length})]}),v.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[v.jsx(_i,{size:"sm",variant:p?"secondary":"primary",disabled:y,onClick:H=>{H.preventDefault(),H.stopPropagation(),p?D():w()},className:"hidden sm:inline-flex",title:p?"Autostart fortsetzen":"Autostart pausieren",leadingIcon:p?v.jsx(HO,{className:"size-4 shrink-0"}):v.jsx(GO,{className:"size-4 shrink-0"}),children:"Autostart"}),v.jsx(_i,{size:"sm",variant:"primary",disabled:d||N.length===0,onClick:H=>{H.preventDefault(),H.stopPropagation(),Z()},className:"hidden sm:inline-flex",title:N.length===0?"Nichts zu stoppen":"Alle laufenden stoppen",children:d?"Stoppe alle…":`Alle stoppen (${N.length})`})]})]})})}),v.jsx("div",{className:"mt-3 grid gap-4 sm:hidden",children:re.map(H=>v.jsx(I9,{r:H,nowMs:M,blurPreviews:c,modelsByKey:u,stopRequestedIds:I,markStopRequested:V,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:o},H.kind==="job"?`job:${H.job.id}`:`pending:${Aw(H.pending)}`))}),v.jsx("div",{className:"mt-3 hidden sm:block overflow-x-auto",children:v.jsx(Ux,{rows:re,columns:q,getRowKey:H=>H.kind==="job"?`job:${H.job.id}`:`pending:${Aw(H.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,onRowClick:H=>{H.kind==="job"&&t(H.job)}})})]}):null,!Q&&!Y?v.jsx(za,{grayBody:!0,children:v.jsxs("div",{className:"flex items-center gap-3",children:[v.jsx("div",{className:"grid h-10 w-10 place-items-center rounded-xl bg-white/70 ring-1 ring-gray-200 dark:bg-white/5 dark:ring-white/10",children:v.jsx("span",{className:"text-lg",children:"⏸️"})}),v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine laufenden Downloads"}),v.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Starte oben eine URL – hier siehst du Live-Status und kannst Jobs stoppen."})]})]})}):null]})}function Ix({open:s,onClose:e,title:t,children:i,footer:n,icon:r,width:o="max-w-lg"}){return v.jsx(Jd,{show:s,as:k.Fragment,children:v.jsxs(Ju,{as:"div",className:"relative z-50",onClose:e,children:[v.jsx(Jd.Child,{as:k.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-200",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:v.jsx("div",{className:"fixed inset-0 bg-gray-500/75 dark:bg-gray-900/50"})}),v.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto px-4 py-6 sm:px-6",children:v.jsx("div",{className:"min-h-full flex items-start justify-center sm:items-center",children:v.jsx(Jd.Child,{as:k.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",enterTo:"opacity-100 translate-y-0 sm:scale-100",leave:"ease-in duration-200",leaveFrom:"opacity-100 translate-y-0 sm:scale-100",leaveTo:"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",children:v.jsxs(Ju.Panel,{className:["relative w-full transform rounded-lg bg-white text-left shadow-xl transition-all","max-h-[calc(100vh-3rem)] sm:max-h-[calc(100vh-4rem)]","flex flex-col","dark:bg-gray-800 dark:outline dark:-outline-offset-1 dark:outline-white/10",o].join(" "),children:[r&&v.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-500/10",children:r}),v.jsxs("div",{className:"px-6 pt-6 flex items-start justify-between gap-3",children:[v.jsx("div",{className:"min-w-0",children:t?v.jsx(Ju.Title,{className:"text-base font-semibold text-gray-900 dark:text-white truncate",children:t}):null}),v.jsx("button",{type:"button",onClick:e,className:`\r + inline-flex shrink-0 items-center justify-center rounded-lg p-1.5\r + text-gray-500 hover:text-gray-900 hover:bg-black/5\r + focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600\r + dark:text-gray-400 dark:hover:text-white dark:hover:bg-white/10 dark:focus-visible:outline-indigo-500\r + `,"aria-label":"Schließen",title:"Schließen",children:v.jsx($x,{className:"size-5"})})]}),v.jsx("div",{className:"px-6 pb-6 pt-4 text-sm text-gray-700 dark:text-gray-300 overflow-y-auto",children:i}),n?v.jsx("div",{className:"px-6 py-4 border-t border-gray-200/70 dark:border-white/10 flex justify-end gap-3",children:n}):null]})})})})]})})}async function Tv(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}const kw=(s,e)=>v.jsx("span",{className:Ti("inline-flex items-center rounded-md px-2 py-0.5 text-xs","bg-indigo-50 text-indigo-700 dark:bg-indigo-500/10 dark:text-indigo-200"),children:e});function M9(s){let e=(s??"").trim();if(!e)return null;/^https?:\/\//i.test(e)||(e=`https://${e}`);try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function Dw(s){if(!s)return[];const e=s.split(/[\n,;|]+/g).map(i=>i.trim()).filter(Boolean),t=Array.from(new Set(e));return t.sort((i,n)=>i.localeCompare(n,void 0,{sensitivity:"base"})),t}function P9(s){return String(s??"").trim().toLowerCase().replace(/^www\./,"")}function Lw(s){if(s.isUrl&&/^https?:\/\//i.test(String(s.input??"")))return String(s.input);const e=P9(s.host),t=String(s.modelKey??"").trim();return!e||!t?null:e.includes("chaturbate.com")||e.includes("chaturbate")?`https://chaturbate.com/${encodeURIComponent(t)}/`:e.includes("myfreecams.com")||e.includes("myfreecams")?`https://www.myfreecams.com/#${encodeURIComponent(t)}`:null}function Rw({title:s,active:e,hiddenUntilHover:t,onClick:i,icon:n}){return v.jsx("span",{className:Ti(t&&!e?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:v.jsx(_i,{variant:e?"soft":"secondary",size:"xs",className:Ti("px-2 py-1 leading-none",e?"":"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:s,onClick:i,children:v.jsx("span",{className:"text-base leading-none",children:n})})})}function B9(){const[s,e]=k.useState([]),t=k.useRef({}),[i,n]=k.useState(!1),[r,o]=k.useState(null),[u,c]=k.useState(""),[d,f]=k.useState(1),p=10,[g,y]=k.useState([]),x=k.useMemo(()=>new Set(g.map(Re=>Re.toLowerCase())),[g]),_=k.useCallback(Re=>{const dt=Re.toLowerCase();y(He=>He.some(nt=>nt.toLowerCase()===dt)?He.filter(nt=>nt.toLowerCase()!==dt):[...He,Re])},[]),w=k.useCallback(()=>y([]),[]),[D,I]=k.useState(""),[L,B]=k.useState(null),[j,V]=k.useState(null),[M,z]=k.useState(!1),[O,N]=k.useState(!1),[q,Q]=k.useState(null),[Y,re]=k.useState(null),[Z,H]=k.useState("favorite"),[K,ie]=k.useState(!1),[te,ne]=k.useState(null);async function $(){if(q){ie(!0),re(null),o(null);try{const Re=new FormData;Re.append("file",q),Re.append("kind",Z);const dt=await fetch("/api/models/import",{method:"POST",body:Re});if(!dt.ok)throw new Error(await dt.text());const He=await dt.json();re(`✅ Import: ${He.inserted} neu, ${He.updated} aktualisiert, ${He.skipped} übersprungen`),N(!1),Q(null),await be(),window.dispatchEvent(new Event("models-changed"))}catch(Re){ne(Re?.message??String(Re))}finally{ie(!1)}}}function ee(Re){return{output:`${Re}_01_01_2000__00-00-00.mp4`}}const le=()=>{ne(null),re(null),Q(null),H("favorite"),N(!0)},be=k.useCallback(async()=>{n(!0),o(null);try{const Re=await Tv("/api/models/list",{cache:"no-store"});e(Array.isArray(Re)?Re:[])}catch(Re){o(Re?.message??String(Re))}finally{n(!1)}},[]);k.useEffect(()=>{be()},[be]),k.useEffect(()=>{const Re=dt=>{const tt=dt?.detail??{};if(tt?.model){const nt=tt.model;e(ot=>{const Ke=ot.findIndex(yt=>yt.id===nt.id);if(Ke===-1)return ot;const pt=ot.slice();return pt[Ke]=nt,pt});return}if(tt?.removed&&tt?.id){const nt=String(tt.id);e(ot=>ot.filter(Ke=>Ke.id!==nt));return}be()};return window.addEventListener("models-changed",Re),()=>window.removeEventListener("models-changed",Re)},[be]),k.useEffect(()=>{const Re=D.trim();if(!Re){B(null),V(null);return}const dt=M9(Re);if(!dt){B(null),V("Bitte nur gültige http(s) URLs einfügen (keine Modelnamen).");return}const He=window.setTimeout(async()=>{try{const tt=await Tv("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:dt})});if(!tt?.isUrl){B(null),V("Bitte nur URLs einfügen (keine Modelnamen).");return}B(tt),V(null)}catch(tt){B(null),V(tt?.message??String(tt))}},300);return()=>window.clearTimeout(He)},[D]);const fe=k.useMemo(()=>s.map(Re=>({m:Re,hay:`${Re.modelKey} ${Re.host??""} ${Re.input??""} ${Re.tags??""}`.toLowerCase()})),[s]),_e=k.useDeferredValue(u),Me=k.useMemo(()=>{const Re=_e.trim().toLowerCase(),dt=Re?fe.filter(He=>He.hay.includes(Re)).map(He=>He.m):s;return x.size===0?dt:dt.filter(He=>{const tt=Dw(He.tags);if(tt.length===0)return!1;const nt=new Set(tt.map(ot=>ot.toLowerCase()));for(const ot of x)if(!nt.has(ot))return!1;return!0})},[s,fe,_e,x]);k.useEffect(()=>{f(1)},[u,g]);const et=Me.length,Ge=k.useMemo(()=>Math.max(1,Math.ceil(et/p)),[et,p]);k.useEffect(()=>{d>Ge&&f(Ge)},[d,Ge]);const lt=k.useMemo(()=>{const Re=(d-1)*p;return Me.slice(Re,Re+p)},[Me,d,p]),At=async()=>{if(L){if(!L.isUrl){V("Bitte nur URLs einfügen (keine Modelnamen).");return}z(!0),o(null);try{const Re=await Tv("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});e(dt=>{const He=dt.filter(tt=>tt.id!==Re.id);return[Re,...He]}),I(""),B(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Re}}))}catch(Re){o(Re?.message??String(Re))}finally{z(!1)}}},mt=async(Re,dt)=>{if(o(null),t.current[Re])return;t.current[Re]=!0;const He=s.find(tt=>tt.id===Re)??null;if(He){const tt={...He,...dt};typeof dt?.watched=="boolean"&&(tt.watching=dt.watched),dt?.favorite===!0&&(tt.liked=!1),dt?.liked===!0&&(tt.favorite=!1),e(nt=>nt.map(ot=>ot.id===Re?tt:ot)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:tt}}))}try{const tt=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:Re,...dt})});if(tt.status===204){e(ot=>ot.filter(Ke=>Ke.id!==Re)),He?window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:He.id,modelKey:He.modelKey}})):window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Re}}));return}if(!tt.ok){const ot=await tt.text().catch(()=>"");throw new Error(ot||`HTTP ${tt.status}`)}const nt=await tt.json();e(ot=>{const Ke=ot.findIndex(yt=>yt.id===nt.id);if(Ke===-1)return ot;const pt=ot.slice();return pt[Ke]=nt,pt}),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:nt}}))}catch(tt){He&&(e(nt=>nt.map(ot=>ot.id===Re?He:ot)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:He}}))),o(tt?.message??String(tt))}finally{delete t.current[Re]}},Vt=k.useMemo(()=>[{key:"statusAll",header:"Status",align:"center",cell:Re=>{const dt=Re.liked===!0,He=Re.favorite===!0,tt=Re.watching===!0,nt=!tt&&!He&&!dt;return v.jsxs("div",{className:"group flex items-center justify-center gap-1",children:[v.jsx("span",{className:Ti(nt&&!tt?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:v.jsx(_i,{variant:tt?"soft":"secondary",size:"xs",className:Ti("px-2 py-1 leading-none",!tt&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:tt?"Nicht mehr beobachten":"Beobachten",onClick:ot=>{ot.stopPropagation(),mt(Re.id,{watched:!tt})},children:v.jsx("span",{className:Ti("text-base leading-none",tt?"text-indigo-600 dark:text-indigo-400":"text-gray-400 dark:text-gray-500"),children:"👁"})})}),v.jsx(Rw,{title:He?"Favorit entfernen":"Als Favorit markieren",active:He,hiddenUntilHover:nt,onClick:ot=>{ot.stopPropagation(),He?mt(Re.id,{favorite:!1}):mt(Re.id,{favorite:!0,liked:!1})},icon:v.jsx("span",{className:He?"text-amber-500":"text-gray-400 dark:text-gray-500",children:"★"})}),v.jsx(Rw,{title:dt?"Gefällt mir entfernen":"Gefällt mir",active:dt,hiddenUntilHover:nt,onClick:ot=>{ot.stopPropagation(),dt?mt(Re.id,{liked:!1}):mt(Re.id,{liked:!0,favorite:!1})},icon:v.jsx("span",{className:dt?"text-rose-500":"text-gray-400 dark:text-gray-500",children:"♥"})})]})}},{key:"model",header:"Model",cell:Re=>v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"font-medium truncate",children:Re.modelKey}),v.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:Re.host??"—"})]})},{key:"url",header:"URL",cell:Re=>{const dt=Lw(Re),He=dt??(Re.isUrl&&Re.input||"—");return dt?v.jsx("a",{href:dt,target:"_blank",rel:"noreferrer",className:"text-indigo-600 dark:text-indigo-400 hover:underline truncate block max-w-[520px]",onClick:tt=>tt.stopPropagation(),title:dt,children:He}):v.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"—"})}},{key:"tags",header:"Tags",cell:Re=>{const dt=Dw(Re.tags),He=dt.slice(0,6),tt=dt.length-He.length,nt=dt.join(", ");return v.jsxs("div",{className:"flex flex-wrap gap-2",title:nt||void 0,children:[Re.hot?kw(!0,"🔥 HOT"):null,Re.keep?kw(!0,"📌 Behalten"):null,He.map(ot=>v.jsx(la,{tag:ot,title:ot,active:x.has(ot.toLowerCase()),onClick:_},ot)),tt>0?v.jsxs(la,{title:nt,children:["+",tt]}):null,!Re.hot&&!Re.keep&&dt.length===0?v.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"}):null]})}},{key:"actions",header:"",align:"right",cell:Re=>v.jsx("div",{className:"flex justify-end",children:v.jsx(Ko,{job:ee(Re.modelKey),variant:"table",order:["details"],className:"flex items-center"})})}],[x,_,mt]);return v.jsxs("div",{className:"space-y-4",children:[v.jsx(za,{header:v.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Model hinzufügen"}),grayBody:!0,children:v.jsxs("div",{className:"grid gap-2",children:[v.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[v.jsx("input",{value:D,onChange:Re=>I(Re.target.value),placeholder:"https://…",className:"flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),v.jsx(_i,{className:"px-3 py-2 text-sm",onClick:At,disabled:!L||M,title:L?"In Models speichern":"Bitte gültige URL einfügen",children:"Hinzufügen"}),v.jsx(_i,{className:"px-3 py-2 text-sm",onClick:be,disabled:i,children:"Aktualisieren"})]}),j?v.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:j}):L?v.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Gefunden: ",v.jsx("span",{className:"font-medium",children:L.modelKey}),L.host?v.jsxs("span",{className:"opacity-70",children:[" • ",L.host]}):null]}):null,r?v.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:r}):null]})}),v.jsxs(za,{header:v.jsxs("div",{className:"space-y-2",children:[v.jsxs("div",{className:"grid gap-2 sm:flex sm:items-center sm:justify-between",children:[v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Models ",v.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",Me.length,")"]})]}),v.jsx("div",{className:"sm:hidden",children:v.jsx(_i,{variant:"secondary",size:"md",onClick:le,children:"Import"})})]}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("div",{className:"hidden sm:block",children:v.jsx(_i,{variant:"secondary",size:"md",onClick:le,children:"Importieren"})}),v.jsx("input",{value:u,onChange:Re=>c(Re.target.value),placeholder:"Suchen…",className:`\r + w-full sm:w-[260px]\r + rounded-md px-3 py-2 text-sm\r + bg-white text-gray-900 shadow-sm ring-1 ring-gray-200\r + focus:outline-none focus:ring-2 focus:ring-indigo-500\r + dark:bg-white/10 dark:text-white dark:ring-white/10\r + `})]})]}),g.length>0?v.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[v.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Tag-Filter:"}),v.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.map(Re=>v.jsx(la,{tag:Re,active:!0,onClick:_,title:Re},Re)),v.jsx(_i,{size:"sm",variant:"soft",className:"text-xs font-medium text-gray-600 hover:underline dark:text-gray-300",onClick:w,children:"Zurücksetzen"})]})]}):null]}),noBodyPadding:!0,children:[v.jsx(Ux,{rows:lt,columns:Vt,getRowKey:Re=>Re.id,striped:!0,compact:!0,fullWidth:!0,stickyHeader:!0,onRowClick:Re=>{const dt=Lw(Re);dt&&window.open(dt,"_blank","noreferrer")}}),v.jsx(yA,{page:d,pageSize:p,totalItems:et,onPageChange:f})]}),v.jsx(Ix,{open:O,onClose:()=>!K&&N(!1),title:"Models importieren",footer:v.jsxs(v.Fragment,{children:[v.jsx(_i,{variant:"secondary",onClick:()=>N(!1),disabled:K,children:"Abbrechen"}),v.jsx(_i,{variant:"primary",onClick:$,isLoading:K,disabled:!q||K,children:"Import starten"})]}),children:v.jsxs("div",{className:"space-y-3",children:[v.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Wähle eine CSV-Datei zum Import aus."}),v.jsxs("div",{className:"space-y-2",children:[v.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Import-Typ"}),v.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[v.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[v.jsx("input",{type:"radio",name:"import-kind",value:"favorite",checked:Z==="favorite",onChange:()=>H("favorite"),disabled:K}),"Favoriten (★)"]}),v.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[v.jsx("input",{type:"radio",name:"import-kind",value:"liked",checked:Z==="liked",onChange:()=>H("liked"),disabled:K}),"Gefällt mir (♥)"]})]})]}),v.jsx("input",{type:"file",accept:".csv,text/csv",onChange:Re=>{const dt=Re.target.files?.[0]??null;ne(null),Q(dt)},className:"block w-full text-sm text-gray-700 file:mr-4 file:rounded-md file:border-0 file:bg-gray-100 file:px-3 file:py-2 file:text-sm file:font-semibold file:text-gray-900 hover:file:bg-gray-200 dark:text-gray-200 dark:file:bg-white/10 dark:file:text-white dark:hover:file:bg-white/20"}),q?v.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Ausgewählt: ",v.jsx("span",{className:"font-medium",children:q.name})]}):null,te?v.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:te}):null,Y?v.jsx("div",{className:"rounded-md bg-green-50 px-3 py-2 text-xs text-green-700 dark:bg-green-500/10 dark:text-green-200",children:Y}):null]})})]})}function mn(...s){return s.filter(Boolean).join(" ")}const F9=new Intl.NumberFormat("de-DE");function _v(s){return s==null||!Number.isFinite(s)?"—":F9.format(s)}function U9(s){if(s==null||!Number.isFinite(s))return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i0?`${t}:${String(i).padStart(2,"0")}:${String(n).padStart(2,"0")}`:`${i}:${String(n).padStart(2,"0")}`}function $d(s){if(!s)return"—";const e=typeof s=="string"?new Date(s):s;return Number.isNaN(e.getTime())?String(s):e.toLocaleString("de-DE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}function j9(s){return s?s.split(",").map(e=>e.trim()).filter(Boolean):[]}function $9(s){const e=s.toLowerCase();return e.includes("/keep/")||e.includes("\\keep\\")}function km(s){return(s||"").split(/[\\/]/).pop()||""}function Nw(s){const e=s.replace(/\.[^.]+$/,""),t=e.startsWith("HOT ")?e.slice(4):e,i=t.match(/^(.+?)_\d{2}_\d{2}_\d{4}(?:__|_)\d{2}[-_]\d{2}[-_]\d{2}/);if(i?.[1])return i[1].trim().toLowerCase();const n=t.match(/^(.+?)_\d{2}_\d{2}_\d{4}/);if(n?.[1])return n[1].trim().toLowerCase();const r=t.indexOf("_");return r>0?t.slice(0,r).trim().toLowerCase():t.trim().toLowerCase()}function Sv(s){return s?String(s).replace(/[\s\S]*?<\/script>/gi,"").replace(/[\s\S]*?<\/style>/gi,"").replace(/<\/?[^>]+>/g," ").replace(/\s+/g," ").trim():""}function H9(s){if(!s)return"";const e=String(s).trim();return e?e.startsWith("http://")||e.startsWith("https://")?e:e.startsWith("/")?`https://chaturbate.com${e}`:`https://chaturbate.com/${e}`:""}function Wr(s){return mn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset",s)}const Ev=s=>s?"blur-md scale-[1.03] brightness-90":"";function V9(s){let e=String(s??"").trim();if(!e)return"";if(e=e.replace(/^https?:\/\//i,""),e.includes("/")){const t=e.split("/").filter(Boolean);e=t[t.length-1]||e}return e.includes(":")&&(e=e.split(":").pop()||e),e.trim().toLowerCase()}function G9(s){const e=s??{},t=e.cf_clearance||e["cf-clearance"]||e.cfclearance||"",i=e.sessionId||e.sessionid||e.session_id||e["session-id"]||"",n=[];return t&&n.push(`cf_clearance=${t}`),i&&n.push(`sessionid=${i}`),n.join("; ")}function z9({open:s,modelKey:e,onClose:t,onOpenPlayer:i,cookies:n,runningJobs:r,blurPreviews:o}){const[u,c]=k.useState([]),[d,f]=k.useState(!1),[p,g]=k.useState(null),[y,x]=k.useState(null),[_,w]=k.useState(!1),[D,I]=k.useState(null),[L,B]=k.useState(null),[j,V]=k.useState(!1),[M,z]=k.useState([]),[O,N]=k.useState(!1),[q,Q]=k.useState([]),[Y,re]=k.useState(!1),[Z,H]=k.useState(0),[K,ie]=k.useState(null),te=k.useCallback(($e,ct)=>{const it=String($e??"").trim();it&&ie({src:it,alt:ct})},[]);k.useEffect(()=>{s||H(0)},[s]);const[ne,$]=k.useState(1),ee=25,le=V9(e),be=k.useMemo(()=>Array.isArray(r)?r:q,[r,q]);k.useEffect(()=>{s&&$(1)},[s,e]),k.useEffect(()=>{if(!s)return;let $e=!0;return f(!0),fetch("/api/models/list",{cache:"no-store"}).then(ct=>ct.json()).then(ct=>{$e&&c(Array.isArray(ct)?ct:[])}).catch(()=>{$e&&c([])}).finally(()=>{$e&&f(!1)}),()=>{$e=!1}},[s]),k.useEffect(()=>{if(!s||!le)return;let $e=!0;return w(!0),g(null),x(null),fetch("/api/chaturbate/online",{cache:"no-store"}).then(ct=>ct.json()).then(ct=>{if(!$e)return;x({enabled:ct?.enabled,fetchedAt:ct?.fetchedAt,lastError:ct?.lastError});const Tt=(Array.isArray(ct?.rooms)?ct.rooms:[]).find(Wt=>String(Wt?.username??"").trim().toLowerCase()===le)??null;g(Tt)}).catch(()=>{$e&&(x({enabled:void 0,fetchedAt:void 0,lastError:"Fetch fehlgeschlagen"}),g(null))}).finally(()=>{$e&&w(!1)}),()=>{$e=!1}},[s,le]),k.useEffect(()=>{if(!s||!le)return;let $e=!0;V(!0),I(null),B(null);const ct=G9(n),it=`/api/chaturbate/biocontext?model=${encodeURIComponent(le)}${Z>0?"&refresh=1":""}`;return fetch(it,{cache:"no-store",headers:ct?{"X-Chaturbate-Cookie":ct}:void 0}).then(async Tt=>{if(!Tt.ok){const Wt=await Tt.text().catch(()=>"");throw new Error(Wt||`HTTP ${Tt.status}`)}return Tt.json()}).then(Tt=>{$e&&(B({enabled:Tt?.enabled,fetchedAt:Tt?.fetchedAt,lastError:Tt?.lastError}),I(Tt?.bio??null))}).catch(Tt=>{$e&&(B({enabled:void 0,fetchedAt:void 0,lastError:Tt?.message||"Fetch fehlgeschlagen"}),I(null))}).finally(()=>{$e&&V(!1)}),()=>{$e=!1}},[s,le,Z,n]),k.useEffect(()=>{if(!s)return;let $e=!0;N(!0);const ct=`/api/record/done?page=${ne}&pageSize=${ee}&sort=completed_desc&includeKeep=1`;return fetch(ct,{cache:"no-store"}).then(it=>it.json()).then(it=>{$e&&z(Array.isArray(it)?it:[])}).catch(()=>{$e&&z([])}).finally(()=>{$e&&N(!1)}),()=>{$e=!1}},[s,ne]),k.useEffect(()=>{if(!s||Array.isArray(r))return;let $e=!0;return re(!0),fetch("/api/record/jobs",{cache:"no-store"}).then(ct=>ct.json()).then(ct=>{$e&&Q(Array.isArray(ct)?ct:[])}).catch(()=>{$e&&Q([])}).finally(()=>{$e&&re(!1)}),()=>{$e=!1}},[s,r]);const fe=k.useMemo(()=>le?u.find($e=>($e.modelKey||"").toLowerCase()===le)??null:null,[u,le]),_e=k.useMemo(()=>le?M.filter($e=>Nw(km($e.output||""))===le):[],[M,le]),Me=k.useMemo(()=>le?be.filter($e=>Nw(km($e.output||""))===le):[],[be,le]),et=k.useMemo(()=>{const $e=j9(fe?.tags),ct=Array.isArray(p?.tags)?p.tags:[],it=new Map;for(const Tt of[...$e,...ct]){const Wt=String(Tt).trim().toLowerCase();Wt&&(it.has(Wt)||it.set(Wt,String(Tt).trim()))}return Array.from(it.values()).sort((Tt,Wt)=>Tt.localeCompare(Wt,"de"))},[fe?.tags,p?.tags]),Ge=p?.display_name||fe?.modelKey||le||"Model",lt=p?.image_url_360x270||p?.image_url||"",At=p?.image_url||lt,mt=p?.chat_room_url_revshare||p?.chat_room_url||"",Vt=(p?.current_show||"").trim().toLowerCase(),Re=Vt?Vt==="public"?"Public":Vt==="private"?"Private":Vt:"",dt=(D?.location||"").trim(),He=D?.follower_count,tt=D?.display_age,nt=(D?.room_status||"").trim(),ot=D?.last_broadcast?$d(D.last_broadcast):"—",Ke=Sv(D?.about_me),pt=Sv(D?.wish_list),yt=Array.isArray(D?.social_medias)?D.social_medias:[],Gt=Array.isArray(D?.photo_sets)?D.photo_sets:[],Ut=Array.isArray(D?.interested_in)?D.interested_in:[],ai=d||O||Y||_||j,Zt=({icon:$e,label:ct,value:it})=>v.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[$e,ct]}),v.jsx("div",{className:"mt-0.5 text-sm font-semibold text-gray-900 dark:text-white",children:it})]});return v.jsxs(Ix,{open:s,onClose:t,title:Ge,width:"max-w-6xl",footer:v.jsx(_i,{variant:"secondary",onClick:t,children:"Schließen"}),children:[v.jsxs("div",{className:"space-y-6",children:[v.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[v.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:le?v.jsxs("span",{children:["Key: ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:le}),y?.fetchedAt?v.jsxs("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:["· Online-Stand: ",$d(y.fetchedAt)]}):null,L?.fetchedAt?v.jsxs("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:["· Bio-Stand: ",$d(L.fetchedAt)]}):null]}):"—"}),v.jsx("div",{className:"flex items-center gap-2",children:mt?v.jsxs("a",{href:mt,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 rounded-lg border border-gray-200/70 bg-white/70 px-2.5 py-1.5 text-xs font-medium text-gray-900 shadow-sm backdrop-blur hover:bg-white dark:border-white/10 dark:bg-white/5 dark:text-white",children:[v.jsx(my,{className:"size-4"}),"Room öffnen"]}):null})]}),v.jsxs("div",{className:"grid gap-5 lg:grid-cols-[320px_1fr]",children:[v.jsx("div",{className:"space-y-4",children:v.jsxs("div",{className:"overflow-hidden rounded-2xl border border-gray-200/70 bg-white/70 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"relative",children:[lt?v.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>te(At,Ge),"aria-label":"Bild vergrößern",children:v.jsx("img",{src:lt,alt:Ge,className:mn("h-52 w-full object-cover transition",Ev(o))})}):v.jsx("div",{className:"h-52 w-full bg-gradient-to-br from-indigo-500/10 via-transparent to-sky-500/10"}),v.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-0 bg-gradient-to-t from-black/40 via-black/0 to-black/0"}),v.jsxs("div",{className:"absolute left-3 top-3 flex flex-wrap items-center gap-2",children:[Re?v.jsx("span",{className:Wr("bg-emerald-500/10 text-emerald-900 ring-emerald-200 backdrop-blur dark:text-emerald-200 dark:ring-emerald-400/20"),children:Re}):null,nt?v.jsx("span",{className:Wr(nt.toLowerCase()==="online"?"bg-emerald-500/10 text-emerald-900 ring-emerald-200 backdrop-blur dark:text-emerald-200 dark:ring-emerald-400/20":"bg-gray-500/10 text-gray-900 ring-gray-200 backdrop-blur dark:text-gray-200 dark:ring-white/15"),children:nt}):null,p?.is_hd?v.jsx("span",{className:Wr("bg-indigo-500/10 text-indigo-900 ring-indigo-200 backdrop-blur dark:text-indigo-200 dark:ring-indigo-400/20"),children:"HD"}):null,p?.is_new?v.jsx("span",{className:Wr("bg-amber-500/10 text-amber-900 ring-amber-200 backdrop-blur dark:text-amber-200 dark:ring-amber-400/20"),children:"NEW"}):null]}),v.jsxs("div",{className:"absolute bottom-3 left-3 right-3",children:[v.jsx("div",{className:"truncate text-sm font-semibold text-white drop-shadow",children:p?.display_name||p?.username||fe?.modelKey||le||"—"}),v.jsx("div",{className:"truncate text-xs text-white/85 drop-shadow",children:p?.username?`@${p.username}`:fe?.modelKey?`@${fe.modelKey}`:""})]}),v.jsxs("div",{className:"absolute bottom-3 right-3 flex items-center gap-2",children:[v.jsx("span",{className:mn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur",fe?.favorite?"bg-amber-500/25 ring-amber-200/30":"bg-black/20 ring-white/15"),title:fe?.favorite?"Favorit":"Nicht favorisiert",children:v.jsxs("span",{className:"relative inline-block size-4",children:[v.jsx(Bv,{className:mn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",fe?.favorite?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),v.jsx(ch,{className:mn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",fe?.favorite?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-amber-200")})]})}),v.jsx("span",{className:mn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur",fe?.liked?"bg-rose-500/25 ring-rose-200/30":"bg-black/20 ring-white/15"),title:fe?.liked?"Gefällt mir":"Nicht geliked",children:v.jsxs("span",{className:"relative inline-block size-4",children:[v.jsx(Wm,{className:mn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",fe?.liked?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),v.jsx(mc,{className:mn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",fe?.liked?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-rose-200")})]})}),v.jsx("span",{className:mn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur",fe?.watching?"bg-sky-500/25 ring-sky-200/30":"bg-black/20 ring-white/15"),title:fe?.watching?"Watched":"Nicht auf Watch",children:v.jsxs("span",{className:"relative inline-block size-4",children:[v.jsx(Pv,{className:mn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",fe?.watching?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),v.jsx(uh,{className:mn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",fe?.watching?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-sky-200")})]})})]})]}),v.jsxs("div",{className:"p-4",children:[v.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[v.jsx(Zt,{icon:v.jsx(RO,{className:"size-4"}),label:"Viewer",value:_v(p?.num_users)}),v.jsx(Zt,{icon:v.jsx(wS,{className:"size-4"}),label:"Follower",value:_v(p?.num_followers??He)})]}),v.jsxs("dl",{className:"mt-4 grid gap-2 text-xs",children:[v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[v.jsx(vO,{className:"size-4"}),"Location"]}),v.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:p?.location||dt||"—"})]}),v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[v.jsx(fO,{className:"size-4"}),"Sprache"]}),v.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:p?.spoken_languages||"—"})]}),v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[v.jsx(_S,{className:"size-4"}),"Online"]}),v.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:Iw(p?.seconds_online)})]}),v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[v.jsx(Wm,{className:"size-4"}),"Alter"]}),v.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:tt!=null?String(tt):p?.age!=null?String(p.age):"—"})]}),v.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[v.jsx(_S,{className:"size-4"}),"Last broadcast"]}),v.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:ot})]})]}),y?.enabled===!1?v.jsx("div",{className:"mt-3 rounded-lg border border-amber-200/60 bg-amber-50/70 px-3 py-2 text-xs text-amber-900 dark:border-amber-400/20 dark:bg-amber-400/10 dark:text-amber-200",children:"Chaturbate-Online ist aktuell deaktiviert."}):y?.lastError?v.jsxs("div",{className:"mt-3 rounded-lg border border-rose-200/60 bg-rose-50/70 px-3 py-2 text-xs text-rose-900 dark:border-rose-400/20 dark:bg-rose-400/10 dark:text-rose-200",children:["Online-Info: ",y.lastError]}):null,L?.enabled===!1?v.jsx("div",{className:"mt-3 rounded-lg border border-amber-200/60 bg-amber-50/70 px-3 py-2 text-xs text-amber-900 dark:border-amber-400/20 dark:bg-amber-400/10 dark:text-amber-200",children:"BioContext ist aktuell deaktiviert."}):L?.lastError?v.jsxs("div",{className:"mt-3 rounded-lg border border-rose-200/60 bg-rose-50/70 px-3 py-2 text-xs text-rose-900 dark:border-rose-400/20 dark:bg-rose-400/10 dark:text-rose-200",children:["BioContext: ",L.lastError]}):null]})]})}),v.jsxs("div",{className:"space-y-4",children:[v.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Room Subject"}),ai?v.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null]}),v.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:p?.room_subject?v.jsx("p",{className:"line-clamp-4 whitespace-pre-wrap break-words",children:p.room_subject}):v.jsx("p",{className:"text-gray-600 dark:text-gray-300",children:"Keine Subject-Info vorhanden."})})]}),v.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Bio"}),v.jsxs("div",{className:"flex items-center gap-2",children:[j?v.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null,v.jsx(_i,{variant:"secondary",className:"h-7 px-2 text-xs",disabled:j||!e,onClick:()=>H($e=>$e+1),title:"BioContext neu abrufen",children:"Aktualisieren"})]})]}),v.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[v.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[v.jsx(uO,{className:"size-4"}),"Über mich"]}),v.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:Ke?v.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:Ke}):v.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]}),v.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[v.jsx(wS,{className:"size-4"}),"Wishlist"]}),v.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:pt?v.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:pt}):v.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]})]}),v.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[v.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[v.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Real name:"})," ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:D?.real_name?Sv(D.real_name):"—"})]}),v.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[v.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Body type:"})," ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:D?.body_type||"—"})]}),v.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[v.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Smoke/Drink:"})," ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:D?.smoke_drink||"—"})]}),v.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[v.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Sex:"})," ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:D?.sex||"—"})]})]}),Ut.length?v.jsxs("div",{className:"mt-3",children:[v.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Interested in"}),v.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Ut.map($e=>v.jsx("span",{className:Wr("bg-sky-500/10 text-sky-900 ring-sky-200 dark:text-sky-200 dark:ring-sky-400/20"),children:$e},$e))})]}):null]}),v.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tags"}),et.length?v.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:et.map($e=>v.jsx(la,{tag:$e},$e))}):v.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Tags vorhanden."})]}),v.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Socials"}),yt.length?v.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[yt.length," Links"]}):null]}),yt.length?v.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:yt.map($e=>{const ct=H9($e.link);return v.jsxs("a",{href:ct,target:"_blank",rel:"noreferrer",className:mn("group flex items-center gap-3 rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-gray-900","transition hover:border-indigo-200 hover:bg-gray-50/80 hover:text-gray-900 dark:border-white/10 dark:bg-white/5 dark:text-white dark:hover:border-indigo-400/30 dark:hover:bg-white/10 dark:hover:text-white"),title:$e.title_name,children:[v.jsx("div",{className:"flex size-9 items-center justify-center rounded-lg bg-black/5 dark:bg-white/5",children:$e.image_url?v.jsx("img",{src:$e.image_url,alt:"",className:"size-5"}):v.jsx(pO,{className:"size-5"})}),v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:$e.title_name}),v.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:$e.label_text?$e.label_text:$e.tokens!=null?`${$e.tokens} token(s)`:"Link"})]}),v.jsx(my,{className:"ml-auto size-4 text-gray-400 transition group-hover:text-indigo-500 dark:text-gray-500 dark:group-hover:text-indigo-400"})]},$e.id)})}):v.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Social-Medias vorhanden."})]}),v.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Photo sets"}),Gt.length?v.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[Gt.length," Sets"]}):null]}),Gt.length?v.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:Gt.slice(0,6).map($e=>v.jsxs("div",{className:"overflow-hidden rounded-xl border border-gray-200/70 bg-white/60 dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"relative",children:[$e.cover_url?v.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>te($e.cover_url,$e.name),"aria-label":"Bild vergrößern",children:v.jsx("img",{src:$e.cover_url,alt:$e.name,className:mn("h-28 w-full object-cover transition",Ev(o))})}):v.jsx("div",{className:"flex h-28 w-full items-center justify-center bg-black/5 dark:bg-white/5",children:v.jsx(bO,{className:"size-6 text-gray-500"})}),v.jsxs("div",{className:"absolute left-2 top-2 flex flex-wrap gap-2",children:[$e.is_video?v.jsx("span",{className:Wr("bg-indigo-500/10 text-indigo-900 ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/20"),children:"Video"}):v.jsx("span",{className:Wr("bg-gray-500/10 text-gray-900 ring-gray-200 dark:text-gray-200 dark:ring-white/15"),children:"Photos"}),$e.fan_club_only?v.jsx("span",{className:Wr("bg-amber-500/10 text-amber-900 ring-amber-200 dark:text-amber-200 dark:ring-amber-400/20"),children:"FanClub"}):null]})]}),v.jsxs("div",{className:"p-3",children:[v.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:$e.name}),v.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:["Tokens: ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:_v($e.tokens)}),$e.user_can_access===!0?v.jsx("span",{className:"ml-2",children:"· Zugriff: ✅"}):null]})]})]},$e.id))}):v.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Photo-Sets vorhanden."})]})]})]}),v.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[v.jsxs("div",{children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),v.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Inkl. Dateien aus ",v.jsx("span",{className:"font-medium",children:"/done/keep/"})]})]}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx(_i,{size:"sm",variant:"secondary",disabled:ne<=1,onClick:()=>$($e=>Math.max(1,$e-1)),children:"Zurück"}),v.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Seite ",ne]}),v.jsx(_i,{size:"sm",variant:"secondary",disabled:O||_e.length$($e=>$e+1),children:"Weiter"})]})]}),v.jsx("div",{className:"mt-3",children:O?v.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade Downloads…"}):_e.length===0?v.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine abgeschlossenen Downloads für dieses Model gefunden."}):v.jsx("div",{className:"grid gap-2",children:_e.map($e=>{const ct=km($e.output||""),it=$9($e.output||""),Tt=ct.startsWith("HOT "),Wt=$e.endedAt?$d($e.endedAt):"—";return v.jsxs("div",{role:i?"button":void 0,tabIndex:i?0:void 0,className:mn("group flex w-full items-center justify-between gap-3 overflow-hidden rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2","transition hover:border-indigo-200 hover:bg-gray-50/80 dark:border-white/10 dark:bg-white/5 dark:hover:border-indigo-400/30 dark:hover:bg-white/10",i?"cursor-pointer":""),onClick:()=>i?.($e),onKeyDown:Xe=>{i&&(Xe.key==="Enter"||Xe.key===" ")&&i($e)},children:[v.jsxs("div",{className:"min-w-0",children:[v.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[v.jsx("div",{className:"min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white",children:ct||"—"}),Tt?v.jsx("span",{className:Wr("shrink-0 bg-orange-500/10 text-orange-900 ring-orange-200 dark:text-orange-200 dark:ring-orange-400/20"),children:"HOT"}):null,it?v.jsx("span",{className:Wr("shrink-0 bg-indigo-500/10 text-indigo-900 ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/20"),children:"KEEP"}):null]}),v.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-600 dark:text-gray-300",children:[v.jsxs("span",{children:["Ende: ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Wt})]}),v.jsxs("span",{children:["Dauer:"," ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Iw($e.durationSeconds)})]}),v.jsxs("span",{children:["Größe:"," ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:U9($e.sizeBytes)})]})]})]}),i?v.jsx("span",{className:"hidden shrink-0 text-xs font-medium text-indigo-600 opacity-0 transition group-hover:opacity-100 dark:text-indigo-400 sm:inline",children:"Öffnen"}):null]},`${$e.id}-${ct}`)})})})]}),v.jsxs("div",{className:"rounded-2xl border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[v.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Laufende Jobs"}),v.jsx("div",{className:"mt-2",children:Y?v.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade…"}):Me.length===0?v.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine laufenden Jobs."}):v.jsx("div",{className:"grid gap-2",children:Me.map($e=>v.jsx("div",{className:"overflow-hidden rounded-xl border border-gray-200/70 bg-white/60 px-3 py-2 text-sm dark:border-white/10 dark:bg-white/5",children:v.jsxs("div",{className:"flex items-start gap-3",children:[v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsx("div",{className:"break-words line-clamp-2 font-medium text-gray-900 dark:text-white",children:km($e.output||"")}),v.jsxs("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:["Start:"," ",v.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:$d($e.startedAt)})]})]}),i?v.jsx(_i,{size:"sm",variant:"secondary",className:"shrink-0",onClick:()=>i($e),children:"Öffnen"}):null]})},$e.id))})})]})]}),v.jsx(Ix,{open:!!K,onClose:()=>ie(null),title:K?.alt||"Bild",width:"max-w-4xl",footer:v.jsxs("div",{className:"flex items-center justify-end gap-2",children:[K?.src?v.jsxs("a",{href:K.src,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 rounded-lg border border-gray-200/70 bg-white/70 px-3 py-1.5 text-xs font-medium text-gray-900 shadow-sm backdrop-blur hover:bg-white dark:border-white/10 dark:bg-white/5 dark:text-white",children:[v.jsx(my,{className:"size-4"}),"In neuem Tab"]}):null,v.jsx(_i,{variant:"secondary",onClick:()=>ie(null),children:"Schließen"})]}),children:v.jsx("div",{className:"grid place-items-center",children:K?.src?v.jsx("img",{src:K.src,alt:K.alt||"",className:mn("max-h-[80vh] w-auto max-w-full rounded-xl object-contain",Ev(o))}):null})})]})}const Dm=s=>Math.max(0,Math.min(1,s));function Lm(s){return s==="good"?"bg-emerald-500":s==="warn"?"bg-amber-500":"bg-red-500"}function q9(s){return s==null?"–":`${Math.round(s)}ms`}function Ow(s){return s==null?"–":`${Math.round(s)}%`}function wv(s){if(s==null||!Number.isFinite(s)||s<=0)return"–";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(n)} ${e[i]}`}function K9(s=1e3){const[e,t]=Bt.useState(null);return Bt.useEffect(()=>{let i=0,n=performance.now(),r=0,o=!0,u=!1;const c=g=>{if(!o||!u)return;r+=1;const y=g-n;if(y>=s){const x=Math.round(r*1e3/y);t(x),r=0,n=g}i=requestAnimationFrame(c)},d=()=>{o&&(document.hidden||u||(u=!0,n=performance.now(),r=0,i=requestAnimationFrame(c)))},f=()=>{u=!1,cancelAnimationFrame(i)},p=()=>{document.hidden?f():d()};return d(),document.addEventListener("visibilitychange",p),()=>{o=!1,document.removeEventListener("visibilitychange",p),f()}},[s]),e}function Mw({mode:s="inline",className:e,pollMs:t=3e3}){const i=K9(1e3),[n,r]=Bt.useState(null),[o,u]=Bt.useState(null),[c,d]=Bt.useState(null),[f,p]=Bt.useState(null),[g,y]=Bt.useState(null),x=5*1024*1024*1024,_=8*1024*1024*1024,w=Bt.useRef(!1);Bt.useEffect(()=>{const Y=`/api/perf/stream?ms=${encodeURIComponent(String(t))}`,re=jL(Y,"perf",Z=>{const H=typeof Z?.cpuPercent=="number"?Z.cpuPercent:null,K=typeof Z?.diskFreeBytes=="number"?Z.diskFreeBytes:null,ie=typeof Z?.diskTotalBytes=="number"?Z.diskTotalBytes:null,te=typeof Z?.diskUsedPercent=="number"?Z.diskUsedPercent:null;u(H),d(K),p(ie),y(te);const ne=typeof Z?.serverMs=="number"?Z.serverMs:null;r(ne!=null?Math.max(0,Date.now()-ne):null)});return()=>re()},[t]);const D=n==null?"bad":n<=120?"good":n<=300?"warn":"bad",I=i==null?"bad":i>=55?"good":i>=30?"warn":"bad",L=o==null?"bad":o<=60?"good":o<=85?"warn":"bad",B=Dm((n??999)/500),j=Dm((i??0)/60),V=Dm((o??0)/100),M=c!=null&&f!=null&&f>0?c/f:null,z=g??(M!=null?(1-M)*100:null),O=Dm((z??0)/100);c==null?w.current=!1:w.current?c>=_&&(w.current=!1):c<=x&&(w.current=!0);const N=c==null||w.current||M==null?"bad":M>=.15?"good":M>=.07?"warn":"bad",q=c==null?"Disk: –":`Free: ${wv(c)} / Total: ${wv(f)} · Used: ${Ow(z)}`,Q=s==="floating"?"fixed bottom-4 right-4 z-[80]":"flex items-center";return v.jsx("div",{className:`${Q} ${e??""}`,children:v.jsxs("div",{className:`\r + rounded-lg border border-gray-200/70 bg-white/70 px-2.5 py-1.5 shadow-sm backdrop-blur\r + dark:border-white/10 dark:bg-white/5\r + grid grid-cols-2 gap-x-3 gap-y-2\r + sm:flex sm:items-center sm:gap-3\r + `,children:[v.jsxs("div",{className:"flex items-center gap-2",title:q,children:[v.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Disk"}),v.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:v.jsx("div",{className:`h-full ${Lm(N)}`,style:{width:`${Math.round(O*100)}%`}})}),v.jsx("span",{className:"text-[11px] w-11 tabular-nums text-gray-900 dark:text-gray-100",children:wv(c)})]}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Ping"}),v.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:v.jsx("div",{className:`h-full ${Lm(D)}`,style:{width:`${Math.round(B*100)}%`}})}),v.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:q9(n)})]}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"FPS"}),v.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:v.jsx("div",{className:`h-full ${Lm(I)}`,style:{width:`${Math.round(j*100)}%`}})}),v.jsx("span",{className:"text-[11px] w-8 tabular-nums text-gray-900 dark:text-gray-100",children:i??"–"})]}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"CPU"}),v.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:v.jsx("div",{className:`h-full ${Lm(L)}`,style:{width:`${Math.round(V*100)}%`}})}),v.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:Ow(o)})]})]})})}function Y9(s,e){const t=[];for(let i=0;i{t!=null&&(window.clearTimeout(t),t=null)},c=()=>{if(i){try{i.abort()}catch{}i=null}},d=p=>{o||(u(),t=window.setTimeout(()=>{f()},p))},f=async()=>{if(!o)try{const p=(s.getModels?.()??[]).map(z=>String(z||"").trim()).filter(Boolean),y=(s.getShow?.()??[]).map(z=>String(z||"").trim()).filter(Boolean).slice().sort(),x=p.slice().sort();if(x.length===0){c();const z={enabled:r?.enabled??!1,rooms:[]};r=z,s.onData(z);const O=document.hidden?Math.max(15e3,e):e;d(O);return}const _=`${y.join(",")}|${x.join(",")}`,w=_;n=_,c();const D=new AbortController;i=D;const L=Y9(x,350);let B=[],j=!1,V=!1;for(const z of L){if(D.signal.aborted||w!==n||o)return;const O=await fetch("/api/chaturbate/online",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({q:z,show:y,refresh:!1}),signal:D.signal,cache:"no-store"});if(!O.ok)continue;V=!0;const N=await O.json();j=j||!!N?.enabled,B.push(...Array.isArray(N?.rooms)?N.rooms:[])}if(!V){const z=document.hidden?Math.max(15e3,e):e;d(z);return}const M={enabled:j,rooms:W9(B)};if(D.signal.aborted||w!==n||o)return;r=M,s.onData(M)}catch(p){if(p?.name==="AbortError")return;s.onError?.(p)}finally{const p=document.hidden?Math.max(15e3,e):e;d(p)}};return f(),()=>{o=!0,u(),c()}}const Av="record_cookies";function Rm(s){return Object.fromEntries(Object.entries(s??{}).map(([t,i])=>[t.trim().toLowerCase(),String(i??"").trim()]).filter(([t,i])=>t.length>0&&i.length>0))}async function Ds(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}const Pw={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!1,autoStartAddedDownloads:!1,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!1,autoDeleteSmallDownloadsBelowMB:50,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1};function Vm(s){let e=(s??"").trim();if(!e)return null;e=e.replace(/^[("'[{<]+/,"").replace(/[)"'\]}>.,;:]+$/,""),/^https?:\/\//i.test(e)||(e=`https://${e}`);try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function Gu(s){const e=(s??"").trim();if(!e)return null;for(const t of e.split(/\s+/g)){const i=Vm(t);if(i)return i}return null}function Bw(s){try{const e=new URL(s).hostname.replace(/^www\./i,"").toLowerCase();return e==="chaturbate.com"||e.endsWith(".chaturbate.com")?"chaturbate":e==="myfreecams.com"||e.endsWith(".myfreecams.com")?"mfc":null}catch{return null}}const Os=s=>(s||"").replaceAll("\\","/").split("/").pop()||"";function Cv(s,e){const i=(s||"").replaceAll("\\","/").split("/");return i[i.length-1]=e,i.join("/")}function Q9(s){return s.startsWith("HOT ")?s.slice(4):s}const Z9=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function Hd(s){const t=Q9(Os(s)).replace(/\.[^.]+$/,""),i=t.match(Z9);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function J9(){const s=xA(),e=8,t="finishedDownloads_sort",[i,n]=k.useState(()=>{try{return window.localStorage.getItem(t)||"completed_desc"}catch{return"completed_desc"}});k.useEffect(()=>{try{window.localStorage.setItem(t,i)}catch{}},[i]);const[r,o]=k.useState(null),[u,c]=k.useState(""),[d,f]=k.useState([]),[p,g]=k.useState([]),[y,x]=k.useState(1),[_,w]=k.useState(0),[D,I]=k.useState(0),[L,B]=k.useState(()=>Date.now()),[j,V]=k.useState(()=>Date.now());k.useEffect(()=>{const he=window.setInterval(()=>V(Date.now()),1e3);return()=>window.clearInterval(he)},[]);const M=he=>(he||"").toLowerCase().trim(),z=he=>{const ye=Math.max(0,Math.floor(he/1e3));if(ye<2)return"gerade eben";if(ye<60)return`vor ${ye} Sekunden`;const me=Math.floor(ye/60);if(me===1)return"vor 1 Minute";if(me<60)return`vor ${me} Minuten`;const Qe=Math.floor(me/60);return Qe===1?"vor 1 Stunde":`vor ${Qe} Stunden`},O=k.useMemo(()=>{const he=j-L;return`(zuletzt aktualisiert: ${z(he)})`},[j,L]),[N,q]=k.useState({}),Q=k.useCallback(he=>{const ye={};for(const me of Array.isArray(he)?he:[]){const Qe=(me?.modelKey||"").trim().toLowerCase();if(!Qe)continue;const Ie=Ct=>(Ct.favorite?4:0)+(Ct.liked===!0?2:0)+(Ct.watching?1:0),Ye=ye[Qe];(!Ye||Ie(me)>=Ie(Ye))&&(ye[Qe]=me)}return ye},[]),Y=k.useCallback(async()=>{try{const he=await Ds("/api/models/list",{cache:"no-store"});q(Q(Array.isArray(he)?he:[])),B(Date.now())}catch{}},[Q]),[re,Z]=k.useState(null),H=k.useRef(null),[K,ie]=k.useState(null);k.useEffect(()=>{const he=ye=>{let Ie=(ye.detail?.modelKey??"").trim().replace(/^https?:\/\//i,"");Ie.includes("/")&&(Ie=Ie.split("/").filter(Boolean).pop()||Ie),Ie.includes(":")&&(Ie=Ie.split(":").pop()||Ie),Ie=Ie.trim().toLowerCase(),Ie&&ie(Ie)};return window.addEventListener("open-model-details",he),()=>window.removeEventListener("open-model-details",he)},[]);const te=k.useCallback(he=>{const ye=Date.now(),me=H.current;if(!me){H.current={ts:ye,list:[he]};return}me.ts=ye;const Qe=me.list.findIndex(Ie=>Ie.id===he.id);Qe>=0?me.list[Qe]=he:me.list.unshift(he)},[]);k.useEffect(()=>{Y();const he=ye=>{const Qe=ye?.detail??{},Ie=Qe?.model;if(Ie&&typeof Ie=="object"){const Ye=String(Ie.modelKey??"").toLowerCase().trim();Ye&&q(Ct=>({...Ct,[Ye]:Ie}));try{te(Ie)}catch{}Z(Ct=>Ct?.id===Ie.id?Ie:Ct),B(Date.now());return}if(Qe?.removed){const Ye=String(Qe?.id??"").trim(),Ct=String(Qe?.modelKey??"").toLowerCase().trim();Ct&&q(Je=>{const{[Ct]:Rt,...Mt}=Je;return Mt}),Ye&&Z(Je=>Je?.id===Ye?null:Je),B(Date.now());return}Y()};return window.addEventListener("models-changed",he),()=>window.removeEventListener("models-changed",he)},[Y,te]);const[ne,$]=k.useState(null),[ee,le]=k.useState(!1),[be,fe]=k.useState(!1),[_e,Me]=k.useState({}),[et,Ge]=k.useState(!1),[lt,At]=k.useState("running"),[mt,Vt]=k.useState(null),[Re,dt]=k.useState(!1),[He,tt]=k.useState(0),nt=k.useCallback(()=>tt(he=>he+1),[]),ot=k.useRef(null),Ke=k.useCallback(()=>{nt(),ot.current&&window.clearTimeout(ot.current),ot.current=window.setTimeout(()=>nt(),3500)},[nt]),[pt,yt]=k.useState(Pw),Gt=k.useRef(pt);k.useEffect(()=>{Gt.current=pt},[pt]);const Ut=!!pt.autoAddToDownloadList,ai=!!pt.autoStartAddedDownloads,[Zt,$e]=k.useState([]),[ct,it]=k.useState({}),Tt=k.useRef(!1),Wt=k.useRef({}),Xe=k.useRef([]);k.useEffect(()=>{Tt.current=ee},[ee]),k.useEffect(()=>{Wt.current=_e},[_e]),k.useEffect(()=>{Xe.current=d},[d]);const Ot=k.useRef(null),kt=k.useRef(""),[Xt,ni]=k.useState({}),[hi,Ai]=k.useState({}),Nt=k.useRef({});k.useEffect(()=>{Nt.current=hi},[hi]);const bt=k.useCallback(he=>{const ye=String(he?.host??"").toLowerCase(),me=String(he?.input??"").toLowerCase();return ye.includes("chaturbate")||me.includes("chaturbate.com")},[]),xi=k.useMemo(()=>{const he=new Set;for(const ye of Object.values(N)){if(!bt(ye))continue;const me=M(String(ye?.modelKey??""));me&&he.add(me)}return Array.from(he)},[N,bt]),bi=k.useRef(N);k.useEffect(()=>{bi.current=N},[N]);const G=k.useRef(ct);k.useEffect(()=>{G.current=ct},[ct]);const W=k.useRef(xi);k.useEffect(()=>{W.current=xi},[xi]);const oe=k.useRef(lt);k.useEffect(()=>{oe.current=lt},[lt]);const Ee=k.useCallback(async(he,ye)=>{const me=Vm(he);if(!me)return!1;const Qe=!!ye?.silent;Qe||$(null);const Ie=Bw(me);if(!Ie)return Qe||$("Nur chaturbate.com oder myfreecams.com werden unterstützt."),!1;const Ye=Wt.current;if(Ie==="chaturbate"&&!Pi(Ye))return Qe||$('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;if(Xe.current.some(Je=>Je.status!=="running"?!1:Vm(String(Je.sourceUrl||""))===me))return!0;if(Ie==="chaturbate"&&Gt.current.useChaturbateApi)try{const Je=await Ds("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:me})}),Rt=String(Je?.modelKey??"").trim().toLowerCase();if(Rt){if(Tt.current)return it(rt=>({...rt||{},[Rt]:me})),!0;const Mt=Nt.current[Rt],Kt=String(Mt?.current_show??"");if(Mt&&Kt&&Kt!=="public")return it(rt=>({...rt||{},[Rt]:me})),!0}}catch{}else if(Tt.current)return Ot.current=me,!0;if(Tt.current)return!1;le(!0),Tt.current=!0;try{const Je=Object.entries(Ye).map(([Mt,Kt])=>`${Mt}=${Kt}`).join("; "),Rt=await Ds("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:me,cookie:Je})});return f(Mt=>[Rt,...Mt]),Xe.current=[Rt,...Xe.current],!0}catch(Je){return Qe||$(Je?.message??String(Je)),!1}finally{le(!1),Tt.current=!1}},[]);k.useEffect(()=>{let he=!1;const ye=async()=>{try{const Ie=await Ds("/api/settings",{cache:"no-store"});!he&&Ie&&yt({...Pw,...Ie})}catch{}},me=()=>{ye()},Qe=()=>{ye()};return window.addEventListener("recorder-settings-updated",me),window.addEventListener("hover",Qe),document.addEventListener("visibilitychange",Qe),ye(),()=>{he=!0,window.removeEventListener("recorder-settings-updated",me),window.removeEventListener("hover",Qe),document.removeEventListener("visibilitychange",Qe)}},[]),k.useEffect(()=>{let he=!1;const ye=async()=>{try{const Qe=await Ds("/api/models/meta",{cache:"no-store"}),Ie=Number(Qe?.count??0);!he&&Number.isFinite(Ie)&&(I(Ie),B(Date.now()))}catch{}};ye();const me=window.setInterval(ye,document.hidden?6e4:3e4);return()=>{he=!0,window.clearInterval(me)}},[]);const Ze=k.useMemo(()=>Object.entries(_e).map(([he,ye])=>({name:he,value:ye})),[_e]),Et=k.useCallback(he=>{H.current=null,Z(null),Vt(he),dt(!1)},[]),Jt=d.filter(he=>he.status==="running"),Li=k.useMemo(()=>{let he=0;for(const ye of Object.values(N)){const me=M(String(ye?.modelKey??""));me&&Xt[me]&&he++}return he},[N,Xt]),{onlineFavCount:Ji,onlineLikedCount:Ci}=k.useMemo(()=>{let he=0,ye=0;for(const me of Object.values(N)){const Qe=M(String(me?.modelKey??""));Qe&&Xt[Qe]&&(me?.favorite&&he++,me?.liked===!0&&ye++)}return{onlineFavCount:he,onlineLikedCount:ye}},[N,Xt]),ss=[{id:"running",label:"Laufende Downloads",count:Jt.length},{id:"finished",label:"Abgeschlossene Downloads",count:_},{id:"models",label:"Models",count:D},{id:"settings",label:"Einstellungen"}],Hi=k.useMemo(()=>u.trim().length>0&&!ee,[u,ee]);k.useEffect(()=>{let he=!1;return(async()=>{try{const me=await Ds("/api/cookies",{cache:"no-store"}),Qe=Rm(me?.cookies);if(he||Me(Qe),Object.keys(Qe).length===0){const Ie=localStorage.getItem(Av);if(Ie)try{const Ye=JSON.parse(Ie),Ct=Rm(Ye);Object.keys(Ct).length>0&&(he||Me(Ct),await Ds("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:Ct})}))}catch{}}}catch{const me=localStorage.getItem(Av);if(me)try{const Qe=JSON.parse(me);he||Me(Rm(Qe))}catch{}}finally{he||Ge(!0)}})(),()=>{he=!0}},[]),k.useEffect(()=>{et&&localStorage.setItem(Av,JSON.stringify(_e))},[_e,et]),k.useEffect(()=>{let he=!1,ye;const me=async()=>{try{const Ie=await fetch("/api/record/done/meta",{cache:"no-store"});if(!Ie.ok)return;const Ye=await Ie.json();he||(w(Ye.count??0),B(Date.now()))}catch{}finally{if(!he){const Ie=document.hidden?6e4:3e4;ye=window.setTimeout(me,Ie)}}},Qe=()=>{document.hidden||me()};return document.addEventListener("visibilitychange",Qe),me(),()=>{he=!0,ye&&window.clearTimeout(ye),document.removeEventListener("visibilitychange",Qe)}},[]),k.useEffect(()=>{const he=Math.max(1,Math.ceil(_/e));y>he&&x(he)},[_,y]),k.useEffect(()=>{let he=!1,ye=null,me=null,Qe=!1;const Ie=Mt=>{const Kt=Array.isArray(Mt)?Mt:[];if(he)return;const rt=Xe.current,at=new Map(rt.map(wt=>[wt.id,wt.status])),ft=Kt.some(wt=>{const It=at.get(wt.id);return It&&It!==wt.status&&(wt.status==="finished"||wt.status==="stopped")});f(Kt),Xe.current=Kt,B(Date.now()),ft&&Ke(),Vt(wt=>{if(!wt)return wt;const It=Kt.find(ti=>ti.id===wt.id);return It||(wt.status==="running"?null:wt)})},Ye=async()=>{if(!(he||Qe)){Qe=!0;try{const Mt=await Ds("/api/record/list");Ie(Mt)}catch{}finally{Qe=!1}}},Ct=()=>{me||(me=window.setInterval(Ye,document.hidden?15e3:5e3))};Ye(),ye=new EventSource("/api/record/stream");const Je=Mt=>{try{Ie(JSON.parse(Mt.data))}catch{}};ye.addEventListener("jobs",Je),ye.onerror=()=>Ct();const Rt=()=>{document.hidden||Ye()};return document.addEventListener("visibilitychange",Rt),window.addEventListener("hover",Rt),()=>{he=!0,me&&window.clearInterval(me),document.removeEventListener("visibilitychange",Rt),window.removeEventListener("hover",Rt),ye?.removeEventListener("jobs",Je),ye?.close(),ye=null}},[Ke]),k.useEffect(()=>{if(lt!=="finished")return;let he=!1,ye=!1;const me=async()=>{if(!(he||ye)){ye=!0;try{const Je=await Ds(`/api/record/done?page=${y}&pageSize=${e}&sort=${encodeURIComponent(i)}`,{cache:"no-store"});he||g(Array.isArray(Je)?Je:[])}catch{he||g([])}finally{ye=!1}}};me();const Ie=document.hidden?6e4:2e4,Ye=window.setInterval(me,Ie),Ct=()=>{document.hidden||me()};return document.addEventListener("visibilitychange",Ct),()=>{he=!0,window.clearInterval(Ye),document.removeEventListener("visibilitychange",Ct)}},[lt,y,i]);const fi=k.useCallback(async he=>{try{const ye=await Ds("/api/record/done/meta",{cache:"no-store"}),me=typeof ye?.count=="number"?ye.count:0,Qe=Number.isFinite(me)&&me>=0?me:0;w(Qe);const Ie=Math.max(1,Math.ceil(Qe/e)),Ct=Math.min(Math.max(1,typeof he=="number"?he:y),Ie);Ct!==y&&x(Ct);const Je=await Ds(`/api/record/done?page=${Ct}&pageSize=${e}&sort=${encodeURIComponent(i)}`,{cache:"no-store"});g(Array.isArray(Je)?Je:[])}catch{}},[y,i]);function ns(he){const ye=Vm(he);if(!ye)return!1;try{return new URL(ye).hostname.includes("chaturbate.com")}catch{return!1}}function es(he,ye){const me=Object.fromEntries(Object.entries(he).map(([Qe,Ie])=>[Qe.trim().toLowerCase(),Ie]));for(const Qe of ye){const Ie=me[Qe.toLowerCase()];if(Ie)return Ie}}function Pi(he){const ye=es(he,["cf_clearance"]),me=es(he,["sessionid","session_id","sessionId"]);return!!(ye&&me)}async function oi(he){try{await Ds(`/api/record/stop?id=${encodeURIComponent(he)}`,{method:"POST"})}catch(ye){s.error("Stop fehlgeschlagen",ye?.message??String(ye))}}k.useEffect(()=>{if(!mt){Z(null),o(null);return}const he=(Hd(mt.output||"")||"").trim().toLowerCase();o(he||null);const ye=he?N[he]:void 0;Z(ye??null)},[mt,N]);async function ei(){return Ee(u)}const Ht=k.useCallback(async he=>{const ye=Os(he.output||"");if(ye){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ye,phase:"start"}}));try{await Ds(`/api/record/delete?file=${encodeURIComponent(ye)}`,{method:"POST"}),window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ye,phase:"success"}})),window.setTimeout(()=>{g(me=>me.filter(Qe=>Os(Qe.output||"")!==ye)),f(me=>me.filter(Qe=>Os(Qe.output||"")!==ye)),Vt(me=>me&&Os(me.output||"")===ye?null:me)},320)}catch(me){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ye,phase:"error"}})),s.error("Löschen fehlgeschlagen",me?.message??String(me));return}}},[]),Rs=k.useCallback(async he=>{const ye=Os(he.output||"");if(ye){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ye,phase:"start"}}));try{await Ds(`/api/record/keep?file=${encodeURIComponent(ye)}`,{method:"POST"}),window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ye,phase:"success"}})),window.setTimeout(()=>{g(me=>me.filter(Qe=>Os(Qe.output||"")!==ye)),f(me=>me.filter(Qe=>Os(Qe.output||"")!==ye)),Vt(me=>me&&Os(me.output||"")===ye?null:me)},320),lt!=="finished"&&fi()}catch(me){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ye,phase:"error"}})),s.error("Keep fehlgeschlagen",me?.message??String(me));return}}},[lt,fi]),Zs=k.useCallback(async he=>{const ye=Os(he.output||"");if(ye)try{const me=await Ds(`/api/record/toggle-hot?file=${encodeURIComponent(ye)}`,{method:"POST"}),Qe=Cv(he.output||"",me.newFile);Vt(Ie=>Ie&&{...Ie,output:Qe}),g(Ie=>Ie.map(Ye=>Os(Ye.output||"")===ye?{...Ye,output:Cv(Ye.output||"",me.newFile)}:Ye)),f(Ie=>Ie.map(Ye=>Os(Ye.output||"")===ye?{...Ye,output:Cv(Ye.output||"",me.newFile)}:Ye))}catch(me){s.error("Umbenennen fehlgeschlagen",me?.message??String(me));return}},[s]);async function xe(he){const ye=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(he)});if(ye.status===204)return null;if(!ye.ok){const me=await ye.text().catch(()=>"");throw new Error(me||`HTTP ${ye.status}`)}return ye.json()}const Ne=k.useCallback(he=>{const ye=H.current;!ye||!he||(ye.ts=Date.now(),ye.list=ye.list.filter(me=>me.id!==he))},[]),Oe=k.useRef({}),Fe=k.useCallback(async he=>{const ye=Os(he.output||""),me=!!(mt&&Os(mt.output||"")===ye),Qe=rt=>{try{const at=String(rt.sourceUrl??rt.SourceURL??""),ft=Gu(at);return ft?new URL(ft).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},Ie=(Hd(he.output||"")||"").trim().toLowerCase();if(Ie){const rt=Ie;if(Oe.current[rt])return;Oe.current[rt]=!0;const at=N[Ie]??{id:"",input:"",host:Qe(he)||void 0,modelKey:Ie,watching:!1,favorite:!1,liked:null,isUrl:!1},ft=!at.favorite,wt={...at,modelKey:at.modelKey||Ie,favorite:ft,liked:ft?!1:at.liked};q(It=>({...It,[Ie]:wt})),te(wt),me&&Z(wt);try{const It=await xe({...wt.id?{id:wt.id}:{},host:wt.host||Qe(he)||"",modelKey:Ie,favorite:ft,...ft?{liked:!1}:{}});if(!It){q(Vi=>{const{[Ie]:Js,...ms}=Vi;return ms}),at.id&&Ne(at.id),me&&Z(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:at.id,modelKey:Ie}}));return}const ti=M(It.modelKey||Ie);ti&&q(Vi=>({...Vi,[ti]:It})),te(It),me&&Z(It),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:It}}))}catch(It){q(ti=>({...ti,[Ie]:at})),te(at),me&&Z(at),s.error("Favorit umschalten fehlgeschlagen",It?.message??String(It))}finally{delete Oe.current[rt]}return}let Ye=me?re:null;if(Ye||(Ye=await Ce(he,{ensure:!0})),!Ye)return;const Ct=M(Ye.modelKey||Ye.id||"");if(!Ct||Oe.current[Ct])return;Oe.current[Ct]=!0;const Je=Ye,Rt=!Je.favorite,Mt={...Je,favorite:Rt,liked:Rt?!1:Je.liked},Kt=M(Je.modelKey||"");Kt&&q(rt=>({...rt,[Kt]:Mt})),te(Mt),me&&Z(Mt);try{const rt=await xe({id:Je.id,favorite:Rt,...Rt?{liked:!1}:{}});if(!rt){q(ft=>{const wt=M(Je.modelKey||"");if(!wt)return ft;const{[wt]:It,...ti}=ft;return ti}),Ne(Je.id),me&&Z(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Je.id,modelKey:Je.modelKey}}));return}const at=M(rt.modelKey||"");at&&q(ft=>({...ft,[at]:rt})),te(rt),me&&Z(rt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:rt}}))}catch(rt){const at=M(Je.modelKey||"");at&&q(ft=>({...ft,[at]:Je})),te(Je),me&&Z(Je),s.error("Favorit umschalten fehlgeschlagen",rt?.message??String(rt))}finally{delete Oe.current[Ct]}},[s,mt,re,Ce,xe,te,Ne,N]),ht=k.useCallback(async he=>{const ye=Os(he.output||""),me=!!(mt&&Os(mt.output||"")===ye),Qe=rt=>{try{const at=String(rt.sourceUrl??rt.SourceURL??""),ft=Gu(at);return ft?new URL(ft).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},Ie=(Hd(he.output||"")||"").trim().toLowerCase();if(Ie){const rt=Ie;if(Oe.current[rt])return;Oe.current[rt]=!0;const at=N[Ie]??{id:"",input:"",host:Qe(he)||void 0,modelKey:Ie,watching:!1,favorite:!1,liked:null,isUrl:!1},ft=at.liked!==!0,wt={...at,modelKey:at.modelKey||Ie,liked:ft,favorite:ft?!1:at.favorite};q(It=>({...It,[Ie]:wt})),te(wt),me&&Z(wt);try{const It=await xe({...wt.id?{id:wt.id}:{},host:wt.host||Qe(he)||"",modelKey:Ie,liked:ft,...ft?{favorite:!1}:{}});if(!It){q(Vi=>{const{[Ie]:Js,...ms}=Vi;return ms}),at.id&&Ne(at.id),me&&Z(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:at.id,modelKey:Ie}}));return}const ti=M(It.modelKey||Ie);ti&&q(Vi=>({...Vi,[ti]:It})),te(It),me&&Z(It),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:It}}))}catch(It){q(ti=>({...ti,[Ie]:at})),te(at),me&&Z(at),s.error("Like umschalten fehlgeschlagen",It?.message??String(It))}finally{delete Oe.current[rt]}return}let Ye=me?re:null;if(Ye||(Ye=await Ce(he,{ensure:!0})),!Ye)return;const Ct=M(Ye.modelKey||Ye.id||"");if(!Ct||Oe.current[Ct])return;Oe.current[Ct]=!0;const Je=Ye,Rt=Je.liked!==!0,Mt={...Je,liked:Rt,favorite:Rt?!1:Je.favorite},Kt=M(Je.modelKey||"");Kt&&q(rt=>({...rt,[Kt]:Mt})),te(Mt),me&&Z(Mt);try{const rt=Rt?await xe({id:Je.id,liked:!0,favorite:!1}):await xe({id:Je.id,liked:!1});if(!rt){q(ft=>{const wt=M(Je.modelKey||"");if(!wt)return ft;const{[wt]:It,...ti}=ft;return ti}),Ne(Je.id),me&&Z(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Je.id,modelKey:Je.modelKey}}));return}const at=M(rt.modelKey||"");at&&q(ft=>({...ft,[at]:rt})),te(rt),me&&Z(rt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:rt}}))}catch(rt){const at=M(Je.modelKey||"");at&&q(ft=>({...ft,[at]:Je})),te(Je),me&&Z(Je),s.error("Like umschalten fehlgeschlagen",rt?.message??String(rt))}finally{delete Oe.current[Ct]}},[s,mt,re,Ce,xe,te,Ne,N]),ve=k.useCallback(async he=>{const ye=Os(he.output||""),me=!!(mt&&Os(mt.output||"")===ye),Qe=rt=>{try{const at=String(rt.sourceUrl??rt.SourceURL??""),ft=Gu(at);return ft?new URL(ft).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},Ie=(Hd(he.output||"")||"").trim().toLowerCase();if(Ie){const rt=Ie;if(Oe.current[rt])return;Oe.current[rt]=!0;const at=N[Ie]??{id:"",input:"",host:Qe(he)||void 0,modelKey:Ie,watching:!1,favorite:!1,liked:null,isUrl:!1},ft=!at.watching,wt={...at,modelKey:at.modelKey||Ie,watching:ft};q(It=>({...It,[Ie]:wt})),te(wt),me&&Z(wt);try{const It=await xe({...wt.id?{id:wt.id}:{},host:wt.host||Qe(he)||"",modelKey:Ie,watched:ft});if(!It){q(Vi=>{const{[Ie]:Js,...ms}=Vi;return ms}),at.id&&Ne(at.id),me&&Z(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:at.id,modelKey:Ie}}));return}const ti=M(It.modelKey||Ie);ti&&q(Vi=>({...Vi,[ti]:It})),te(It),me&&Z(It),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:It}}))}catch(It){q(ti=>({...ti,[Ie]:at})),te(at),me&&Z(at),s.error("Watched umschalten fehlgeschlagen",It?.message??String(It))}finally{delete Oe.current[rt]}return}let Ye=me?re:null;if(Ye||(Ye=await Ce(he,{ensure:!0})),!Ye)return;const Ct=M(Ye.modelKey||Ye.id||"");if(!Ct||Oe.current[Ct])return;Oe.current[Ct]=!0;const Je=Ye,Rt=!Je.watching,Mt={...Je,watching:Rt},Kt=M(Je.modelKey||"");Kt&&q(rt=>({...rt,[Kt]:Mt})),te(Mt),me&&Z(Mt);try{const rt=await xe({id:Je.id,watched:Rt});if(!rt){q(ft=>{const wt=M(Je.modelKey||"");if(!wt)return ft;const{[wt]:It,...ti}=ft;return ti}),Ne(Je.id),me&&Z(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Je.id,modelKey:Je.modelKey}}));return}const at=M(rt.modelKey||"");at&&q(ft=>({...ft,[at]:rt})),te(rt),me&&Z(rt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:rt}}))}catch(rt){const at=M(Je.modelKey||"");at&&q(ft=>({...ft,[at]:Je})),te(Je),me&&Z(Je),s.error("Watched umschalten fehlgeschlagen",rt?.message??String(rt))}finally{delete Oe.current[Ct]}},[s,mt,re,Ce,xe,te,Ne,N]);async function Ce(he,ye){const me=!!ye?.ensure,Qe=Mt=>{const Kt=Date.now(),rt=H.current;if(!rt){H.current={ts:Kt,list:[Mt]};return}rt.ts=Kt;const at=rt.list.findIndex(ft=>ft.id===Mt.id);at>=0?rt.list[at]=Mt:rt.list.unshift(Mt)},Ie=async Mt=>{if(!Mt)return null;const Kt=Mt.trim().toLowerCase();if(!Kt)return null;const rt=N[Kt];if(rt)return Qe(rt),rt;if(me){let ti;try{const Js=he.sourceUrl??he.SourceURL??"",ms=Gu(Js);ms&&(ti=new URL(ms).hostname.replace(/^www\./i,"").toLowerCase())}catch{}const Vi=await Ds("/api/models/ensure",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({modelKey:Mt,...ti?{host:ti}:{}})});return te(Vi),Vi}const at=Date.now(),ft=H.current;if(!ft||at-ft.ts>3e4){const ti=Object.values(N);if(ti.length)H.current={ts:at,list:ti};else{const Vi=await Ds("/api/models/list",{cache:"no-store"});H.current={ts:at,list:Array.isArray(Vi)?Vi:[]}}}const It=(H.current?.list??[]).find(ti=>(ti.modelKey||"").trim().toLowerCase()===Kt);return It||null},Ye=Hd(he.output||"");if(Ye)return Ie(Ye);const Ct=he.status==="running",Je=he.sourceUrl??he.SourceURL??"",Rt=Gu(Je);if(Ct&&Rt){const Mt=await Ds("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:Rt})}),Kt=await Ds("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Mt)});return te(Kt),Kt}return null}return k.useEffect(()=>{if(!Ut&&!ai||!navigator.clipboard?.readText)return;let he=!1,ye=!1,me=null;const Qe=async()=>{if(!(he||ye)){ye=!0;try{const Ct=await navigator.clipboard.readText(),Je=Gu(Ct);if(!Je||!Bw(Je)||Je===kt.current)return;kt.current=Je,Ut&&c(Je),ai&&(Tt.current?Ot.current=Je:(Ot.current=null,await Ee(Je)))}catch{}finally{ye=!1}}},Ie=Ct=>{he||(me=window.setTimeout(async()=>{await Qe(),Ie(document.hidden?5e3:1500)},Ct))},Ye=()=>{Qe()};return window.addEventListener("hover",Ye),document.addEventListener("visibilitychange",Ye),Ie(0),()=>{he=!0,me&&window.clearTimeout(me),window.removeEventListener("hover",Ye),document.removeEventListener("visibilitychange",Ye)}},[Ut,ai,Ee]),k.useEffect(()=>{if(ee||!ai)return;const he=Ot.current;he&&(Ot.current=null,Ee(he))},[ee,ai,Ee]),k.useEffect(()=>{const he=X9({getModels:()=>{if(!Gt.current.useChaturbateApi)return[];const ye=bi.current,me=G.current,Qe=Object.values(ye).filter(Ye=>!!Ye?.watching&&String(Ye?.host??"").toLowerCase().includes("chaturbate")).map(Ye=>String(Ye?.modelKey??"").trim().toLowerCase()).filter(Boolean),Ie=Object.keys(me||{}).map(Ye=>String(Ye||"").trim().toLowerCase()).filter(Boolean);return Array.from(new Set([...Qe,...Ie]))},getShow:()=>["public","private","hidden","away"],intervalMs:12e3,onData:ye=>{(async()=>{if(!ye?.enabled){Ai({}),Nt.current={},ni({}),$e([]),B(Date.now());return}const me={};for(const Je of Array.isArray(ye.rooms)?ye.rooms:[]){const Rt=String(Je?.username??"").trim().toLowerCase();Rt&&(me[Rt]=Je)}Ai(me),Nt.current=me;const Qe=W.current,Ie={};for(const Je of Qe||[]){const Rt=String(Je||"").trim().toLowerCase();Rt&&me[Rt]&&(Ie[Rt]=!0)}if(ni(Ie),!Gt.current.useChaturbateApi)$e([]);else if(oe.current==="running"){const Je=bi.current,Rt=G.current,Mt=Array.from(new Set(Object.values(Je).filter(ft=>!!ft?.watching&&String(ft?.host??"").toLowerCase().includes("chaturbate")).map(ft=>String(ft?.modelKey??"").trim().toLowerCase()).filter(Boolean))),Kt=Object.keys(Rt||{}).map(ft=>String(ft||"").trim().toLowerCase()).filter(Boolean),rt=new Set(Kt),at=Array.from(new Set([...Mt,...Kt]));if(at.length===0)$e([]);else{const ft=[];for(const wt of at){const It=me[wt];if(!It)continue;const ti=String(It?.username??"").trim(),Vi=String(It?.current_show??"unknown");if(Vi==="public"&&!rt.has(wt))continue;const Js=`https://chaturbate.com/${(ti||wt).trim()}/`;ft.push({id:wt,modelKey:ti||wt,url:Js,currentShow:Vi,imageUrl:String(It?.image_url??"")})}ft.sort((wt,It)=>wt.modelKey.localeCompare(It.modelKey,void 0,{sensitivity:"base"})),$e(ft)}}if(!Gt.current.useChaturbateApi||Tt.current)return;const Ye=G.current,Ct=Object.keys(Ye||{}).map(Je=>String(Je||"").toLowerCase()).filter(Boolean);for(const Je of Ct){const Rt=me[Je];if(!Rt||String(Rt.current_show??"")!=="public")continue;const Mt=Ye[Je];if(!Mt)continue;await Ee(Mt,{silent:!0})&&it(rt=>{const at={...rt||{}};return delete at[Je],G.current=at,at})}B(Date.now())})()}});return()=>he()},[]),v.jsxs("div",{className:"min-h-screen bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100",children:[v.jsxs("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 overflow-hidden",children:[v.jsx("div",{className:"absolute -top-28 left-1/2 h-80 w-[52rem] -translate-x-1/2 rounded-full bg-indigo-500/10 blur-3xl dark:bg-indigo-400/10"}),v.jsx("div",{className:"absolute -bottom-28 right-[-6rem] h-80 w-[46rem] rounded-full bg-sky-500/10 blur-3xl dark:bg-sky-400/10"})]}),v.jsxs("div",{className:"relative",children:[v.jsx("header",{className:"z-30 bg-white/70 backdrop-blur dark:bg-gray-950/60 sm:sticky sm:top-0 sm:border-b sm:border-gray-200/70 sm:dark:border-white/10",children:v.jsxs("div",{className:"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-3 sm:py-4 space-y-2 sm:space-y-3",children:[v.jsxs("div",{className:"flex items-center sm:items-start justify-between gap-3 sm:gap-4",children:[v.jsx("div",{className:"min-w-0",children:v.jsxs("div",{className:"min-w-0",children:[v.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[v.jsx("h1",{className:"text-lg font-semibold tracking-tight text-gray-900 dark:text-white",children:"Recorder"}),v.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[v.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-100/80 px-2 py-1 text-[11px] font-semibold text-gray-900 ring-1 ring-gray-200/60 dark:bg-white/10 dark:text-gray-100 dark:ring-white/10",title:"online",children:[v.jsx(qO,{className:"size-4 opacity-80"}),v.jsx("span",{className:"tabular-nums",children:Li})]}),v.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-100/80 px-2 py-1 text-[11px] font-semibold text-gray-900 ring-1 ring-gray-200/60 dark:bg-white/10 dark:text-gray-100 dark:ring-white/10",title:"Fav online",children:[v.jsx(mc,{className:"size-4 opacity-80"}),v.jsx("span",{className:"tabular-nums",children:Ji})]}),v.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-gray-100/80 px-2 py-1 text-[11px] font-semibold text-gray-900 ring-1 ring-gray-200/60 dark:bg-white/10 dark:text-gray-100 dark:ring-white/10",title:"Like online",children:[v.jsx(UO,{className:"size-4 opacity-80"}),v.jsx("span",{className:"tabular-nums",children:Ci})]})]}),v.jsx("div",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:O})]}),v.jsx("div",{className:"sm:hidden mt-2",children:v.jsx("div",{className:"mt-2",children:v.jsx(Mw,{mode:"inline",className:"w-full"})})})]})}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx(Mw,{mode:"inline",className:"hidden sm:flex"}),v.jsx(_i,{variant:"secondary",onClick:()=>fe(!0),className:"h-9 px-3",children:"Cookies"})]})]}),v.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_auto] sm:items-stretch",children:[v.jsxs("div",{className:"relative",children:[v.jsx("label",{className:"sr-only",children:"Source URL"}),v.jsx("input",{value:u,onChange:he=>c(he.target.value),placeholder:"https://…",className:"block w-full rounded-lg px-3 py-2.5 text-sm bg-white text-gray-900 shadow-sm ring-1 ring-gray-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:bg-white/10 dark:text-white dark:ring-white/10"})]}),v.jsx(_i,{variant:"primary",onClick:ei,disabled:!Hi,className:"w-full sm:w-auto rounded-lg",children:"Start"})]}),ne?v.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-200",children:v.jsxs("div",{className:"flex items-start justify-between gap-3",children:[v.jsx("div",{className:"min-w-0 break-words",children:ne}),v.jsx("button",{type:"button",className:"shrink-0 rounded px-2 py-1 text-xs font-medium text-red-700 hover:bg-red-100 dark:text-red-200 dark:hover:bg-white/10",onClick:()=>$(null),"aria-label":"Fehlermeldung schließen",title:"Schließen",children:"✕"})]})}):null,ns(u)&&!Pi(_e)?v.jsxs("div",{className:"text-xs text-amber-700 dark:text-amber-300",children:["⚠️ Für Chaturbate werden die Cookies ",v.jsx("code",{children:"cf_clearance"})," und ",v.jsx("code",{children:"sessionId"})," benötigt."]}):null,ee?v.jsx("div",{className:"pt-1",children:v.jsx(fc,{label:"Starte Download…",indeterminate:!0})}):null,v.jsx("div",{className:"hidden sm:block pt-2",children:v.jsx(yS,{tabs:ss,value:lt,onChange:At,ariaLabel:"Tabs",variant:"barUnderline"})})]})}),v.jsx("div",{className:"sm:hidden sticky top-0 z-20 border-b border-gray-200/70 bg-white/70 backdrop-blur dark:border-white/10 dark:bg-gray-950/60",children:v.jsx("div",{className:"mx-auto max-w-7xl px-4 py-2",children:v.jsx(yS,{tabs:ss,value:lt,onChange:At,ariaLabel:"Tabs",variant:"barUnderline"})})}),v.jsxs("main",{className:"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-6 space-y-6",children:[lt==="running"?v.jsx(O9,{jobs:Jt,modelsByKey:N,pending:Zt,onOpenPlayer:Et,onStopJob:oi,onToggleFavorite:Fe,onToggleLike:ht,onToggleWatch:ve,blurPreviews:!!pt.blurPreviews}):null,lt==="finished"?v.jsx(hM,{jobs:d,modelsByKey:N,doneJobs:p,doneTotal:_,page:y,pageSize:e,onPageChange:x,onOpenPlayer:Et,onDeleteJob:Ht,onToggleHot:Zs,onToggleFavorite:Fe,onToggleLike:ht,onToggleWatch:ve,blurPreviews:!!pt.blurPreviews,teaserPlayback:pt.teaserPlayback??"hover",teaserAudio:!!pt.teaserAudio,assetNonce:He,sortMode:i,onSortModeChange:he=>{n(he),x(1)},onRefreshDone:fi}):null,lt==="models"?v.jsx(B9,{}):null,lt==="settings"?v.jsx(N5,{onAssetsGenerated:nt}):null]}),v.jsx(D5,{open:be,onClose:()=>fe(!1),initialCookies:Ze,onApply:he=>{const ye=Rm(Object.fromEntries(he.map(me=>[me.name,me.value])));Me(ye),Ds("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:ye})}).catch(()=>{})}}),mt?v.jsx(_8,{job:mt,modelKey:r??void 0,expanded:Re,onToggleExpand:()=>dt(he=>!he),onClose:()=>Vt(null),isHot:Os(mt.output||"").startsWith("HOT "),isFavorite:!!re?.favorite,isLiked:re?.liked===!0,isWatching:!!re?.watching,onKeep:Rs,onDelete:Ht,onToggleHot:Zs,onToggleFavorite:Fe,onToggleLike:ht,onStopJob:oi,onToggleWatch:ve}):null,v.jsx(z9,{open:!!K,modelKey:K,onClose:()=>ie(null),onOpenPlayer:Et,runningJobs:Jt,cookies:_e,blurPreviews:pt.blurPreviews})]})]})}gI.createRoot(document.getElementById("root")).render(v.jsx(k.StrictMode,{children:v.jsx(uM,{position:"bottom-right",maxToasts:3,defaultDurationMs:3500,children:v.jsx(J9,{})})})); diff --git a/backend/web/dist/assets/index-zKk-xTZ_.js b/backend/web/dist/assets/index-zKk-xTZ_.js deleted file mode 100644 index 3e8d259..0000000 --- a/backend/web/dist/assets/index-zKk-xTZ_.js +++ /dev/null @@ -1,267 +0,0 @@ -function lk(s,e){for(var t=0;ti[n]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(n){if(n.ep)return;n.ep=!0;const r=t(n);fetch(n.href,r)}})();var Dp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function oc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function uk(s){if(Object.prototype.hasOwnProperty.call(s,"__esModule"))return s;var e=s.default;if(typeof e=="function"){var t=function i(){var n=!1;try{n=this instanceof i}catch{}return n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(i){var n=Object.getOwnPropertyDescriptor(s,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return s[i]}})}),t}var F0={exports:{}},md={};var mS;function ck(){if(mS)return md;mS=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,n,r){var o=null;if(r!==void 0&&(o=""+r),n.key!==void 0&&(o=""+n.key),"key"in n){r={};for(var u in n)u!=="key"&&(r[u]=n[u])}else r=n;return n=r.ref,{$$typeof:s,type:i,key:o,ref:n!==void 0?n:null,props:r}}return md.Fragment=e,md.jsx=t,md.jsxs=t,md}var gS;function dk(){return gS||(gS=1,F0.exports=ck()),F0.exports}var O=dk(),U0={exports:{}},St={};var yS;function hk(){if(yS)return St;yS=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.consumer"),o=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),m=Symbol.for("react.activity"),g=Symbol.iterator;function v($){return $===null||typeof $!="object"?null:($=g&&$[g]||$["@@iterator"],typeof $=="function"?$:null)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,E={};function L($,ie,he){this.props=$,this.context=ie,this.refs=E,this.updater=he||b}L.prototype.isReactComponent={},L.prototype.setState=function($,ie){if(typeof $!="object"&&typeof $!="function"&&$!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,$,ie,"setState")},L.prototype.forceUpdate=function($){this.updater.enqueueForceUpdate(this,$,"forceUpdate")};function I(){}I.prototype=L.prototype;function w($,ie,he){this.props=$,this.context=ie,this.refs=E,this.updater=he||b}var F=w.prototype=new I;F.constructor=w,_(F,L.prototype),F.isPureReactComponent=!0;var U=Array.isArray;function V(){}var B={H:null,A:null,T:null,S:null},q=Object.prototype.hasOwnProperty;function k($,ie,he){var Ce=he.ref;return{$$typeof:s,type:$,key:ie,ref:Ce!==void 0?Ce:null,props:he}}function R($,ie){return k($.type,ie,$.props)}function K($){return typeof $=="object"&&$!==null&&$.$$typeof===s}function X($){var ie={"=":"=0",":":"=2"};return"$"+$.replace(/[=:]/g,function(he){return ie[he]})}var ee=/\/+/g;function le($,ie){return typeof $=="object"&&$!==null&&$.key!=null?X(""+$.key):ie.toString(36)}function ae($){switch($.status){case"fulfilled":return $.value;case"rejected":throw $.reason;default:switch(typeof $.status=="string"?$.then(V,V):($.status="pending",$.then(function(ie){$.status==="pending"&&($.status="fulfilled",$.value=ie)},function(ie){$.status==="pending"&&($.status="rejected",$.reason=ie)})),$.status){case"fulfilled":return $.value;case"rejected":throw $.reason}}throw $}function Y($,ie,he,Ce,be){var Ue=typeof $;(Ue==="undefined"||Ue==="boolean")&&($=null);var Ee=!1;if($===null)Ee=!0;else switch(Ue){case"bigint":case"string":case"number":Ee=!0;break;case"object":switch($.$$typeof){case s:case e:Ee=!0;break;case f:return Ee=$._init,Y(Ee($._payload),ie,he,Ce,be)}}if(Ee)return be=be($),Ee=Ce===""?"."+le($,0):Ce,U(be)?(he="",Ee!=null&&(he=Ee.replace(ee,"$&/")+"/"),Y(be,ie,he,"",function(tt){return tt})):be!=null&&(K(be)&&(be=R(be,he+(be.key==null||$&&$.key===be.key?"":(""+be.key).replace(ee,"$&/")+"/")+Ee)),ie.push(be)),1;Ee=0;var je=Ce===""?".":Ce+":";if(U($))for(var Ve=0;Ve<$.length;Ve++)Ce=$[Ve],Ue=je+le(Ce,Ve),Ee+=Y(Ce,ie,he,Ue,be);else if(Ve=v($),typeof Ve=="function")for($=Ve.call($),Ve=0;!(Ce=$.next()).done;)Ce=Ce.value,Ue=je+le(Ce,Ve++),Ee+=Y(Ce,ie,he,Ue,be);else if(Ue==="object"){if(typeof $.then=="function")return Y(ae($),ie,he,Ce,be);throw ie=String($),Error("Objects are not valid as a React child (found: "+(ie==="[object Object]"?"object with keys {"+Object.keys($).join(", ")+"}":ie)+"). If you meant to render a collection of children, use an array instead.")}return Ee}function Q($,ie,he){if($==null)return $;var Ce=[],be=0;return Y($,Ce,"","",function(Ue){return ie.call(he,Ue,be++)}),Ce}function te($){if($._status===-1){var ie=$._result;ie=ie(),ie.then(function(he){($._status===0||$._status===-1)&&($._status=1,$._result=he)},function(he){($._status===0||$._status===-1)&&($._status=2,$._result=he)}),$._status===-1&&($._status=0,$._result=ie)}if($._status===1)return $._result.default;throw $._result}var oe=typeof reportError=="function"?reportError:function($){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var ie=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof $=="object"&&$!==null&&typeof $.message=="string"?String($.message):String($),error:$});if(!window.dispatchEvent(ie))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",$);return}console.error($)},de={map:Q,forEach:function($,ie,he){Q($,function(){ie.apply(this,arguments)},he)},count:function($){var ie=0;return Q($,function(){ie++}),ie},toArray:function($){return Q($,function(ie){return ie})||[]},only:function($){if(!K($))throw Error("React.Children.only expected to receive a single React element child.");return $}};return St.Activity=m,St.Children=de,St.Component=L,St.Fragment=t,St.Profiler=n,St.PureComponent=w,St.StrictMode=i,St.Suspense=c,St.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=B,St.__COMPILER_RUNTIME={__proto__:null,c:function($){return B.H.useMemoCache($)}},St.cache=function($){return function(){return $.apply(null,arguments)}},St.cacheSignal=function(){return null},St.cloneElement=function($,ie,he){if($==null)throw Error("The argument must be a React element, but you passed "+$+".");var Ce=_({},$.props),be=$.key;if(ie!=null)for(Ue in ie.key!==void 0&&(be=""+ie.key),ie)!q.call(ie,Ue)||Ue==="key"||Ue==="__self"||Ue==="__source"||Ue==="ref"&&ie.ref===void 0||(Ce[Ue]=ie[Ue]);var Ue=arguments.length-2;if(Ue===1)Ce.children=he;else if(1>>1,de=Y[oe];if(0>>1;oe<$;){var ie=2*(oe+1)-1,he=Y[ie],Ce=ie+1,be=Y[Ce];if(0>n(he,te))Cen(be,he)?(Y[oe]=be,Y[Ce]=te,oe=Ce):(Y[oe]=he,Y[ie]=te,oe=ie);else if(Cen(be,te))Y[oe]=be,Y[Ce]=te,oe=Ce;else break e}}return Q}function n(Y,Q){var te=Y.sortIndex-Q.sortIndex;return te!==0?te:Y.id-Q.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var r=performance;s.unstable_now=function(){return r.now()}}else{var o=Date,u=o.now();s.unstable_now=function(){return o.now()-u}}var c=[],d=[],f=1,m=null,g=3,v=!1,b=!1,_=!1,E=!1,L=typeof setTimeout=="function"?setTimeout:null,I=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;function F(Y){for(var Q=t(d);Q!==null;){if(Q.callback===null)i(d);else if(Q.startTime<=Y)i(d),Q.sortIndex=Q.expirationTime,e(c,Q);else break;Q=t(d)}}function U(Y){if(_=!1,F(Y),!b)if(t(c)!==null)b=!0,V||(V=!0,X());else{var Q=t(d);Q!==null&&ae(U,Q.startTime-Y)}}var V=!1,B=-1,q=5,k=-1;function R(){return E?!0:!(s.unstable_now()-kY&&R());){var oe=m.callback;if(typeof oe=="function"){m.callback=null,g=m.priorityLevel;var de=oe(m.expirationTime<=Y);if(Y=s.unstable_now(),typeof de=="function"){m.callback=de,F(Y),Q=!0;break t}m===t(c)&&i(c),F(Y)}else i(c);m=t(c)}if(m!==null)Q=!0;else{var $=t(d);$!==null&&ae(U,$.startTime-Y),Q=!1}}break e}finally{m=null,g=te,v=!1}Q=void 0}}finally{Q?X():V=!1}}}var X;if(typeof w=="function")X=function(){w(K)};else if(typeof MessageChannel<"u"){var ee=new MessageChannel,le=ee.port2;ee.port1.onmessage=K,X=function(){le.postMessage(null)}}else X=function(){L(K,0)};function ae(Y,Q){B=L(function(){Y(s.unstable_now())},Q)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(Y){Y.callback=null},s.unstable_forceFrameRate=function(Y){0>Y||125oe?(Y.sortIndex=te,e(d,Y),t(c)===null&&Y===t(d)&&(_?(I(B),B=-1):_=!0,ae(U,te-oe))):(Y.sortIndex=de,e(c,Y),b||v||(b=!0,V||(V=!0,X()))),Y},s.unstable_shouldYield=R,s.unstable_wrapCallback=function(Y){var Q=g;return function(){var te=g;g=Q;try{return Y.apply(this,arguments)}finally{g=te}}}})(H0)),H0}var _S;function pk(){return _S||(_S=1,j0.exports=fk()),j0.exports}var G0={exports:{}},Es={};var xS;function mk(){if(xS)return Es;xS=1;var s=lm();function e(c){var d="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),G0.exports=mk(),G0.exports}var ES;function gk(){if(ES)return gd;ES=1;var s=pk(),e=lm(),t=Y2();function i(a){var l="https://react.dev/errors/"+a;if(1de||(a.current=oe[de],oe[de]=null,de--)}function he(a,l){de++,oe[de]=a.current,a.current=l}var Ce=$(null),be=$(null),Ue=$(null),Ee=$(null);function je(a,l){switch(he(Ue,l),he(be,a),he(Ce,null),l.nodeType){case 9:case 11:a=(a=l.documentElement)&&(a=a.namespaceURI)?Fx(a):0;break;default:if(a=l.tagName,l=l.namespaceURI)l=Fx(l),a=Ux(l,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}ie(Ce),he(Ce,a)}function Ve(){ie(Ce),ie(be),ie(Ue)}function tt(a){a.memoizedState!==null&&he(Ee,a);var l=Ce.current,h=Ux(l,a.type);l!==h&&(he(be,a),he(Ce,h))}function lt(a){be.current===a&&(ie(Ce),ie(be)),Ee.current===a&&(ie(Ee),dd._currentValue=te)}var Me,Je;function st(a){if(Me===void 0)try{throw Error()}catch(h){var l=h.stack.trim().match(/\n( *(at )?)/);Me=l&&l[1]||"",Je=-1)":-1T||ue[p]!==Se[T]){var Oe=` -`+ue[p].replace(" at new "," at ");return a.displayName&&Oe.includes("")&&(Oe=Oe.replace("",a.displayName)),Oe}while(1<=p&&0<=T);break}}}finally{Ct=!1,Error.prepareStackTrace=h}return(h=a?a.displayName||a.name:"")?st(h):""}function ut(a,l){switch(a.tag){case 26:case 27:case 5:return st(a.type);case 16:return st("Lazy");case 13:return a.child!==l&&l!==null?st("Suspense Fallback"):st("Suspense");case 19:return st("SuspenseList");case 0:case 15:return Fe(a.type,!1);case 11:return Fe(a.type.render,!1);case 1:return Fe(a.type,!0);case 31:return st("Activity");default:return""}}function xt(a){try{var l="",h=null;do l+=ut(a,h),h=a,a=a.return;while(a);return l}catch(p){return` -Error generating stack: `+p.message+` -`+p.stack}}var Tt=Object.prototype.hasOwnProperty,_e=s.unstable_scheduleCallback,$e=s.unstable_cancelCallback,He=s.unstable_shouldYield,Xe=s.unstable_requestPaint,We=s.unstable_now,pt=s.unstable_getCurrentPriorityLevel,mt=s.unstable_ImmediatePriority,jt=s.unstable_UserBlockingPriority,fi=s.unstable_NormalPriority,Ai=s.unstable_LowPriority,Yi=s.unstable_IdlePriority,ts=s.log,$t=s.unstable_setDisableYieldValue,Ls=null,Ti=null;function Ri(a){if(typeof ts=="function"&&$t(a),Ti&&typeof Ti.setStrictMode=="function")try{Ti.setStrictMode(Ls,a)}catch{}}var ce=Math.clz32?Math.clz32:ze,ye=Math.log,Ae=Math.LN2;function ze(a){return a>>>=0,a===0?32:31-(ye(a)/Ae|0)|0}var ht=256,bi=262144,Wi=4194304;function H(a){var l=a&42;if(l!==0)return l;switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return a&261888;case 262144:case 524288:case 1048576:case 2097152:return a&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return a&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return a}}function G(a,l,h){var p=a.pendingLanes;if(p===0)return 0;var T=0,x=a.suspendedLanes,M=a.pingedLanes;a=a.warmLanes;var z=p&134217727;return z!==0?(p=z&~x,p!==0?T=H(p):(M&=z,M!==0?T=H(M):h||(h=z&~a,h!==0&&(T=H(h))))):(z=p&~x,z!==0?T=H(z):M!==0?T=H(M):h||(h=p&~a,h!==0&&(T=H(h)))),T===0?0:l!==0&&l!==T&&(l&x)===0&&(x=T&-T,h=l&-l,x>=h||x===32&&(h&4194048)!==0)?l:T}function re(a,l){return(a.pendingLanes&~(a.suspendedLanes&~a.pingedLanes)&l)===0}function we(a,l){switch(a){case 1:case 2:case 4:case 8:case 64:return l+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ge(){var a=Wi;return Wi<<=1,(Wi&62914560)===0&&(Wi=4194304),a}function Ye(a){for(var l=[],h=0;31>h;h++)l.push(a);return l}function wt(a,l){a.pendingLanes|=l,l!==268435456&&(a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0)}function Ci(a,l,h,p,T,x){var M=a.pendingLanes;a.pendingLanes=h,a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0,a.expiredLanes&=h,a.entangledLanes&=h,a.errorRecoveryDisabledLanes&=h,a.shellSuspendCounter=0;var z=a.entanglements,ue=a.expirationTimes,Se=a.hiddenUpdates;for(h=M&~h;0"u")return null;try{return a.activeElement||a.body}catch{return a.body}}var rr=/[\n"\\]/g;function fs(a){return a.replace(rr,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function gc(a,l,h,p,T,x,M,z){a.name="",M!=null&&typeof M!="function"&&typeof M!="symbol"&&typeof M!="boolean"?a.type=M:a.removeAttribute("type"),l!=null?M==="number"?(l===0&&a.value===""||a.value!=l)&&(a.value=""+ss(l)):a.value!==""+ss(l)&&(a.value=""+ss(l)):M!=="submit"&&M!=="reset"||a.removeAttribute("value"),l!=null?Io(a,M,ss(l)):h!=null?Io(a,M,ss(h)):p!=null&&a.removeAttribute("value"),T==null&&x!=null&&(a.defaultChecked=!!x),T!=null&&(a.checked=T&&typeof T!="function"&&typeof T!="symbol"),z!=null&&typeof z!="function"&&typeof z!="symbol"&&typeof z!="boolean"?a.name=""+ss(z):a.removeAttribute("name")}function Ol(a,l,h,p,T,x,M,z){if(x!=null&&typeof x!="function"&&typeof x!="symbol"&&typeof x!="boolean"&&(a.type=x),l!=null||h!=null){if(!(x!=="submit"&&x!=="reset"||l!=null)){kl(a);return}h=h!=null?""+ss(h):"",l=l!=null?""+ss(l):h,z||l===a.value||(a.value=l),a.defaultValue=l}p=p??T,p=typeof p!="function"&&typeof p!="symbol"&&!!p,a.checked=z?a.checked:!!p,a.defaultChecked=!!p,M!=null&&typeof M!="function"&&typeof M!="symbol"&&typeof M!="boolean"&&(a.name=M),kl(a)}function Io(a,l,h){l==="number"&&Rl(a.ownerDocument)===a||a.defaultValue===""+h||(a.defaultValue=""+h)}function ns(a,l,h,p){if(a=a.options,l){l={};for(var T=0;T"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$l=!1;if(Us)try{var Ro={};Object.defineProperty(Ro,"passive",{get:function(){$l=!0}}),window.addEventListener("test",Ro,Ro),window.removeEventListener("test",Ro,Ro)}catch{$l=!1}var or=null,jl=null,Oo=null;function Th(){if(Oo)return Oo;var a,l=jl,h=l.length,p,T="value"in or?or.value:or.textContent,x=T.length;for(a=0;a=Uo),Ih=" ",_c=!1;function Wl(a,l){switch(a){case"keyup":return ig.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function kh(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var La=!1;function sg(a,l){switch(a){case"compositionend":return kh(l);case"keypress":return l.which!==32?null:(_c=!0,Ih);case"textInput":return a=l.data,a===Ih&&_c?null:a;default:return null}}function xc(a,l){if(La)return a==="compositionend"||!wa&&Wl(a,l)?(a=Th(),Oo=jl=or=null,La=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1=l)return{node:h,offset:l-a};a=p}e:{for(;h;){if(h.nextSibling){h=h.nextSibling;break e}h=h.parentNode}h=void 0}h=ka(h)}}function Yr(a,l){return a&&l?a===l?!0:a&&a.nodeType===3?!1:l&&l.nodeType===3?Yr(a,l.parentNode):"contains"in a?a.contains(l):a.compareDocumentPosition?!!(a.compareDocumentPosition(l)&16):!1:!1}function Xl(a){a=a!=null&&a.ownerDocument!=null&&a.ownerDocument.defaultView!=null?a.ownerDocument.defaultView:window;for(var l=Rl(a.document);l instanceof a.HTMLIFrameElement;){try{var h=typeof l.contentWindow.location.href=="string"}catch{h=!1}if(h)a=l.contentWindow;else break;l=Rl(a.document)}return l}function wc(a){var l=a&&a.nodeName&&a.nodeName.toLowerCase();return l&&(l==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||l==="textarea"||a.contentEditable==="true")}var ug=Us&&"documentMode"in document&&11>=document.documentMode,Ra=null,Lc=null,Oa=null,Ql=!1;function Ic(a,l,h){var p=h.window===h?h.document:h.nodeType===9?h:h.ownerDocument;Ql||Ra==null||Ra!==Rl(p)||(p=Ra,"selectionStart"in p&&wc(p)?p={start:p.selectionStart,end:p.selectionEnd}:(p=(p.ownerDocument&&p.ownerDocument.defaultView||window).getSelection(),p={anchorNode:p.anchorNode,anchorOffset:p.anchorOffset,focusNode:p.focusNode,focusOffset:p.focusOffset}),Oa&&ur(Oa,p)||(Oa=p,p=Af(Lc,"onSelect"),0>=M,T-=M,cn=1<<32-ce(l)+T|h<Dt?(Ut=at,at=null):Ut=at.sibling;var qt=De(me,at,xe[Dt],Ne);if(qt===null){at===null&&(at=Ut);break}a&&at&&qt.alternate===null&&l(me,at),fe=x(qt,fe,Dt),Vt===null?ct=qt:Vt.sibling=qt,Vt=qt,at=Ut}if(Dt===xe.length)return h(me,at),Pt&&Lt(me,Dt),ct;if(at===null){for(;DtDt?(Ut=at,at=null):Ut=at.sibling;var no=De(me,at,qt.value,Ne);if(no===null){at===null&&(at=Ut);break}a&&at&&no.alternate===null&&l(me,at),fe=x(no,fe,Dt),Vt===null?ct=no:Vt.sibling=no,Vt=no,at=Ut}if(qt.done)return h(me,at),Pt&&Lt(me,Dt),ct;if(at===null){for(;!qt.done;Dt++,qt=xe.next())qt=Be(me,qt.value,Ne),qt!==null&&(fe=x(qt,fe,Dt),Vt===null?ct=qt:Vt.sibling=qt,Vt=qt);return Pt&&Lt(me,Dt),ct}for(at=p(at);!qt.done;Dt++,qt=xe.next())qt=Ie(at,me,Dt,qt.value,Ne),qt!==null&&(a&&qt.alternate!==null&&at.delete(qt.key===null?Dt:qt.key),fe=x(qt,fe,Dt),Vt===null?ct=qt:Vt.sibling=qt,Vt=qt);return a&&at.forEach(function(ok){return l(me,ok)}),Pt&&Lt(me,Dt),ct}function ii(me,fe,xe,Ne){if(typeof xe=="object"&&xe!==null&&xe.type===_&&xe.key===null&&(xe=xe.props.children),typeof xe=="object"&&xe!==null){switch(xe.$$typeof){case v:e:{for(var ct=xe.key;fe!==null;){if(fe.key===ct){if(ct=xe.type,ct===_){if(fe.tag===7){h(me,fe.sibling),Ne=T(fe,xe.props.children),Ne.return=me,me=Ne;break e}}else if(fe.elementType===ct||typeof ct=="object"&&ct!==null&&ct.$$typeof===q&&Xo(ct)===fe.type){h(me,fe.sibling),Ne=T(fe,xe.props),Hc(Ne,xe),Ne.return=me,me=Ne;break e}h(me,fe);break}else l(me,fe);fe=fe.sibling}xe.type===_?(Ne=dr(xe.props.children,me.mode,Ne,xe.key),Ne.return=me,me=Ne):(Ne=Bc(xe.type,xe.key,xe.props,null,me.mode,Ne),Hc(Ne,xe),Ne.return=me,me=Ne)}return M(me);case b:e:{for(ct=xe.key;fe!==null;){if(fe.key===ct)if(fe.tag===4&&fe.stateNode.containerInfo===xe.containerInfo&&fe.stateNode.implementation===xe.implementation){h(me,fe.sibling),Ne=T(fe,xe.children||[]),Ne.return=me,me=Ne;break e}else{h(me,fe);break}else l(me,fe);fe=fe.sibling}Ne=Fa(xe,me.mode,Ne),Ne.return=me,me=Ne}return M(me);case q:return xe=Xo(xe),ii(me,fe,xe,Ne)}if(ae(xe))return nt(me,fe,xe,Ne);if(X(xe)){if(ct=X(xe),typeof ct!="function")throw Error(i(150));return xe=ct.call(xe),ft(me,fe,xe,Ne)}if(typeof xe.then=="function")return ii(me,fe,Yh(xe),Ne);if(xe.$$typeof===w)return ii(me,fe,vt(me,xe),Ne);Wh(me,xe)}return typeof xe=="string"&&xe!==""||typeof xe=="number"||typeof xe=="bigint"?(xe=""+xe,fe!==null&&fe.tag===6?(h(me,fe.sibling),Ne=T(fe,xe),Ne.return=me,me=Ne):(h(me,fe),Ne=qo(xe,me.mode,Ne),Ne.return=me,me=Ne),M(me)):h(me,fe)}return function(me,fe,xe,Ne){try{jc=0;var ct=ii(me,fe,xe,Ne);return su=null,ct}catch(at){if(at===iu||at===zh)throw at;var Vt=Di(29,at,null,me.mode);return Vt.lanes=Ne,Vt.return=me,Vt}}}var Zo=Lb(!0),Ib=Lb(!1),ja=!1;function pg(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mg(a,l){a=a.updateQueue,l.updateQueue===a&&(l.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,callbacks:null})}function Ha(a){return{lane:a,tag:0,payload:null,callback:null,next:null}}function Ga(a,l,h){var p=a.updateQueue;if(p===null)return null;if(p=p.shared,(zt&2)!==0){var T=p.pending;return T===null?l.next=l:(l.next=T.next,T.next=l),p.pending=l,l=eu(a),jh(a,null,h),l}return Jl(a,p,l,h),eu(a)}function Gc(a,l,h){if(l=l.updateQueue,l!==null&&(l=l.shared,(h&4194048)!==0)){var p=l.lanes;p&=a.pendingLanes,h|=p,l.lanes=h,ji(a,h)}}function gg(a,l){var h=a.updateQueue,p=a.alternate;if(p!==null&&(p=p.updateQueue,h===p)){var T=null,x=null;if(h=h.firstBaseUpdate,h!==null){do{var M={lane:h.lane,tag:h.tag,payload:h.payload,callback:null,next:null};x===null?T=x=M:x=x.next=M,h=h.next}while(h!==null);x===null?T=x=l:x=x.next=l}else T=x=l;h={baseState:p.baseState,firstBaseUpdate:T,lastBaseUpdate:x,shared:p.shared,callbacks:p.callbacks},a.updateQueue=h;return}a=h.lastBaseUpdate,a===null?h.firstBaseUpdate=l:a.next=l,h.lastBaseUpdate=l}var yg=!1;function Vc(){if(yg){var a=rs;if(a!==null)throw a}}function qc(a,l,h,p){yg=!1;var T=a.updateQueue;ja=!1;var x=T.firstBaseUpdate,M=T.lastBaseUpdate,z=T.shared.pending;if(z!==null){T.shared.pending=null;var ue=z,Se=ue.next;ue.next=null,M===null?x=Se:M.next=Se,M=ue;var Oe=a.alternate;Oe!==null&&(Oe=Oe.updateQueue,z=Oe.lastBaseUpdate,z!==M&&(z===null?Oe.firstBaseUpdate=Se:z.next=Se,Oe.lastBaseUpdate=ue))}if(x!==null){var Be=T.baseState;M=0,Oe=Se=ue=null,z=x;do{var De=z.lane&-536870913,Ie=De!==z.lane;if(Ie?(Ft&De)===De:(p&De)===De){De!==0&&De===wn&&(yg=!0),Oe!==null&&(Oe=Oe.next={lane:0,tag:z.tag,payload:z.payload,callback:null,next:null});e:{var nt=a,ft=z;De=l;var ii=h;switch(ft.tag){case 1:if(nt=ft.payload,typeof nt=="function"){Be=nt.call(ii,Be,De);break e}Be=nt;break e;case 3:nt.flags=nt.flags&-65537|128;case 0:if(nt=ft.payload,De=typeof nt=="function"?nt.call(ii,Be,De):nt,De==null)break e;Be=m({},Be,De);break e;case 2:ja=!0}}De=z.callback,De!==null&&(a.flags|=64,Ie&&(a.flags|=8192),Ie=T.callbacks,Ie===null?T.callbacks=[De]:Ie.push(De))}else Ie={lane:De,tag:z.tag,payload:z.payload,callback:z.callback,next:null},Oe===null?(Se=Oe=Ie,ue=Be):Oe=Oe.next=Ie,M|=De;if(z=z.next,z===null){if(z=T.shared.pending,z===null)break;Ie=z,z=Ie.next,Ie.next=null,T.lastBaseUpdate=Ie,T.shared.pending=null}}while(!0);Oe===null&&(ue=Be),T.baseState=ue,T.firstBaseUpdate=Se,T.lastBaseUpdate=Oe,x===null&&(T.shared.lanes=0),Ya|=M,a.lanes=M,a.memoizedState=Be}}function kb(a,l){if(typeof a!="function")throw Error(i(191,a));a.call(l)}function Rb(a,l){var h=a.callbacks;if(h!==null)for(a.callbacks=null,a=0;ax?x:8;var M=Y.T,z={};Y.T=z,Ng(a,!1,l,h);try{var ue=T(),Se=Y.S;if(Se!==null&&Se(z,ue),ue!==null&&typeof ue=="object"&&typeof ue.then=="function"){var Oe=XL(ue,p);Yc(a,l,Oe,mn(a))}else Yc(a,l,p,mn(a))}catch(Be){Yc(a,l,{then:function(){},status:"rejected",reason:Be},mn())}finally{Q.p=x,M!==null&&z.types!==null&&(M.types=z.types),Y.T=M}}function iI(){}function Pg(a,l,h,p){if(a.tag!==5)throw Error(i(476));var T=c_(a).queue;u_(a,T,l,te,h===null?iI:function(){return d_(a),h(p)})}function c_(a){var l=a.memoizedState;if(l!==null)return l;l={memoizedState:te,baseState:te,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Jr,lastRenderedState:te},next:null};var h={};return l.next={memoizedState:h,baseState:h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Jr,lastRenderedState:h},next:null},a.memoizedState=l,a=a.alternate,a!==null&&(a.memoizedState=l),l}function d_(a){var l=c_(a);l.next===null&&(l=a.alternate.memoizedState),Yc(a,l.next.queue,{},mn())}function Mg(){return Ze(dd)}function h_(){return Fi().memoizedState}function f_(){return Fi().memoizedState}function sI(a){for(var l=a.return;l!==null;){switch(l.tag){case 24:case 3:var h=mn();a=Ha(h);var p=Ga(l,a,h);p!==null&&(Ws(p,l,h),Gc(p,l,h)),l={cache:Qr()},a.payload=l;return}l=l.return}}function nI(a,l,h){var p=mn();h={lane:p,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null},af(a)?m_(l,h):(h=Mc(a,l,h,p),h!==null&&(Ws(h,a,p),g_(h,l,p)))}function p_(a,l,h){var p=mn();Yc(a,l,h,p)}function Yc(a,l,h,p){var T={lane:p,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null};if(af(a))m_(l,T);else{var x=a.alternate;if(a.lanes===0&&(x===null||x.lanes===0)&&(x=l.lastRenderedReducer,x!==null))try{var M=l.lastRenderedState,z=x(M,h);if(T.hasEagerState=!0,T.eagerState=z,xs(z,M))return Jl(a,l,T,0),ai===null&&Zl(),!1}catch{}if(h=Mc(a,l,T,p),h!==null)return Ws(h,a,p),g_(h,l,p),!0}return!1}function Ng(a,l,h,p){if(p={lane:2,revertLane:p0(),gesture:null,action:p,hasEagerState:!1,eagerState:null,next:null},af(a)){if(l)throw Error(i(479))}else l=Mc(a,h,p,2),l!==null&&Ws(l,a,2)}function af(a){var l=a.alternate;return a===At||l!==null&&l===At}function m_(a,l){ru=Zh=!0;var h=a.pending;h===null?l.next=l:(l.next=h.next,h.next=l),a.pending=l}function g_(a,l,h){if((h&4194048)!==0){var p=l.lanes;p&=a.pendingLanes,h|=p,l.lanes=h,ji(a,h)}}var Wc={readContext:Ze,use:tf,useCallback:wi,useContext:wi,useEffect:wi,useImperativeHandle:wi,useLayoutEffect:wi,useInsertionEffect:wi,useMemo:wi,useReducer:wi,useRef:wi,useState:wi,useDebugValue:wi,useDeferredValue:wi,useTransition:wi,useSyncExternalStore:wi,useId:wi,useHostTransitionStatus:wi,useFormState:wi,useActionState:wi,useOptimistic:wi,useMemoCache:wi,useCacheRefresh:wi};Wc.useEffectEvent=wi;var y_={readContext:Ze,use:tf,useCallback:function(a,l){return Os().memoizedState=[a,l===void 0?null:l],a},useContext:Ze,useEffect:e_,useImperativeHandle:function(a,l,h){h=h!=null?h.concat([a]):null,nf(4194308,4,n_.bind(null,l,a),h)},useLayoutEffect:function(a,l){return nf(4194308,4,a,l)},useInsertionEffect:function(a,l){nf(4,2,a,l)},useMemo:function(a,l){var h=Os();l=l===void 0?null:l;var p=a();if(Jo){Ri(!0);try{a()}finally{Ri(!1)}}return h.memoizedState=[p,l],p},useReducer:function(a,l,h){var p=Os();if(h!==void 0){var T=h(l);if(Jo){Ri(!0);try{h(l)}finally{Ri(!1)}}}else T=l;return p.memoizedState=p.baseState=T,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:T},p.queue=a,a=a.dispatch=nI.bind(null,At,a),[p.memoizedState,a]},useRef:function(a){var l=Os();return a={current:a},l.memoizedState=a},useState:function(a){a=Lg(a);var l=a.queue,h=p_.bind(null,At,l);return l.dispatch=h,[a.memoizedState,h]},useDebugValue:Rg,useDeferredValue:function(a,l){var h=Os();return Og(h,a,l)},useTransition:function(){var a=Lg(!1);return a=u_.bind(null,At,a.queue,!0,!1),Os().memoizedState=a,[!1,a]},useSyncExternalStore:function(a,l,h){var p=At,T=Os();if(Pt){if(h===void 0)throw Error(i(407));h=h()}else{if(h=l(),ai===null)throw Error(i(349));(Ft&127)!==0||Fb(p,l,h)}T.memoizedState=h;var x={value:h,getSnapshot:l};return T.queue=x,e_($b.bind(null,p,x,a),[a]),p.flags|=2048,ou(9,{destroy:void 0},Ub.bind(null,p,x,h,l),null),h},useId:function(){var a=Os(),l=ai.identifierPrefix;if(Pt){var h=ps,p=cn;h=(p&~(1<<32-ce(p)-1)).toString(32)+h,l="_"+l+"R_"+h,h=Jh++,0<\/script>",x=x.removeChild(x.firstChild);break;case"select":x=typeof p.is=="string"?M.createElement("select",{is:p.is}):M.createElement("select"),p.multiple?x.multiple=!0:p.size&&(x.size=p.size);break;default:x=typeof p.is=="string"?M.createElement(T,{is:p.is}):M.createElement(T)}}x[Gt]=l,x[Bt]=p;e:for(M=l.child;M!==null;){if(M.tag===5||M.tag===6)x.appendChild(M.stateNode);else if(M.tag!==4&&M.tag!==27&&M.child!==null){M.child.return=M,M=M.child;continue}if(M===l)break e;for(;M.sibling===null;){if(M.return===null||M.return===l)break e;M=M.return}M.sibling.return=M.return,M=M.sibling}l.stateNode=x;e:switch(gs(x,T,p),T){case"button":case"input":case"select":case"textarea":p=!!p.autoFocus;break e;case"img":p=!0;break e;default:p=!1}p&&ta(l)}}return hi(l),Xg(l,l.type,a===null?null:a.memoizedProps,l.pendingProps,h),null;case 6:if(a&&l.stateNode!=null)a.memoizedProps!==p&&ta(l);else{if(typeof p!="string"&&l.stateNode===null)throw Error(i(166));if(a=Ue.current,y(l)){if(a=l.stateNode,h=l.memoizedProps,p=null,T=Gi,T!==null)switch(T.tag){case 27:case 5:p=T.memoizedProps}a[Gt]=l,a=!!(a.nodeValue===h||p!==null&&p.suppressHydrationWarning===!0||Nx(a.nodeValue,h)),a||mr(l,!0)}else a=Cf(a).createTextNode(p),a[Gt]=l,l.stateNode=a}return hi(l),null;case 31:if(h=l.memoizedState,a===null||a.memoizedState!==null){if(p=y(l),h!==null){if(a===null){if(!p)throw Error(i(318));if(a=l.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(i(557));a[Gt]=l}else S(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;hi(l),a=!1}else h=C(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=h),a=!0;if(!a)return l.flags&256?(hn(l),l):(hn(l),null);if((l.flags&128)!==0)throw Error(i(558))}return hi(l),null;case 13:if(p=l.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(T=y(l),p!==null&&p.dehydrated!==null){if(a===null){if(!T)throw Error(i(318));if(T=l.memoizedState,T=T!==null?T.dehydrated:null,!T)throw Error(i(317));T[Gt]=l}else S(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;hi(l),T=!1}else T=C(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=T),T=!0;if(!T)return l.flags&256?(hn(l),l):(hn(l),null)}return hn(l),(l.flags&128)!==0?(l.lanes=h,l):(h=p!==null,a=a!==null&&a.memoizedState!==null,h&&(p=l.child,T=null,p.alternate!==null&&p.alternate.memoizedState!==null&&p.alternate.memoizedState.cachePool!==null&&(T=p.alternate.memoizedState.cachePool.pool),x=null,p.memoizedState!==null&&p.memoizedState.cachePool!==null&&(x=p.memoizedState.cachePool.pool),x!==T&&(p.flags|=2048)),h!==a&&h&&(l.child.flags|=8192),df(l,l.updateQueue),hi(l),null);case 4:return Ve(),a===null&&v0(l.stateNode.containerInfo),hi(l),null;case 10:return J(l.type),hi(l),null;case 19:if(ie(Bi),p=l.memoizedState,p===null)return hi(l),null;if(T=(l.flags&128)!==0,x=p.rendering,x===null)if(T)Qc(p,!1);else{if(Li!==0||a!==null&&(a.flags&128)!==0)for(a=l.child;a!==null;){if(x=Qh(a),x!==null){for(l.flags|=128,Qc(p,!1),a=x.updateQueue,l.updateQueue=a,df(l,a),l.subtreeFlags=0,a=h,h=l.child;h!==null;)Hh(h,a),h=h.sibling;return he(Bi,Bi.current&1|2),Pt&&Lt(l,p.treeForkCount),l.child}a=a.sibling}p.tail!==null&&We()>gf&&(l.flags|=128,T=!0,Qc(p,!1),l.lanes=4194304)}else{if(!T)if(a=Qh(x),a!==null){if(l.flags|=128,T=!0,a=a.updateQueue,l.updateQueue=a,df(l,a),Qc(p,!0),p.tail===null&&p.tailMode==="hidden"&&!x.alternate&&!Pt)return hi(l),null}else 2*We()-p.renderingStartTime>gf&&h!==536870912&&(l.flags|=128,T=!0,Qc(p,!1),l.lanes=4194304);p.isBackwards?(x.sibling=l.child,l.child=x):(a=p.last,a!==null?a.sibling=x:l.child=x,p.last=x)}return p.tail!==null?(a=p.tail,p.rendering=a,p.tail=a.sibling,p.renderingStartTime=We(),a.sibling=null,h=Bi.current,he(Bi,T?h&1|2:h&1),Pt&&Lt(l,p.treeForkCount),a):(hi(l),null);case 22:case 23:return hn(l),Tg(),p=l.memoizedState!==null,a!==null?a.memoizedState!==null!==p&&(l.flags|=8192):p&&(l.flags|=8192),p?(h&536870912)!==0&&(l.flags&128)===0&&(hi(l),l.subtreeFlags&6&&(l.flags|=8192)):hi(l),h=l.updateQueue,h!==null&&df(l,h.retryQueue),h=null,a!==null&&a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(h=a.memoizedState.cachePool.pool),p=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(p=l.memoizedState.cachePool.pool),p!==h&&(l.flags|=2048),a!==null&&ie(Wo),null;case 24:return h=null,a!==null&&(h=a.memoizedState.cache),l.memoizedState.cache!==h&&(l.flags|=2048),J(ci),hi(l),null;case 25:return null;case 30:return null}throw Error(i(156,l.tag))}function uI(a,l){switch(Gs(l),l.tag){case 1:return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 3:return J(ci),Ve(),a=l.flags,(a&65536)!==0&&(a&128)===0?(l.flags=a&-65537|128,l):null;case 26:case 27:case 5:return lt(l),null;case 31:if(l.memoizedState!==null){if(hn(l),l.alternate===null)throw Error(i(340));S()}return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 13:if(hn(l),a=l.memoizedState,a!==null&&a.dehydrated!==null){if(l.alternate===null)throw Error(i(340));S()}return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 19:return ie(Bi),null;case 4:return Ve(),null;case 10:return J(l.type),null;case 22:case 23:return hn(l),Tg(),a!==null&&ie(Wo),a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 24:return J(ci),null;case 25:return null;default:return null}}function j_(a,l){switch(Gs(l),l.tag){case 3:J(ci),Ve();break;case 26:case 27:case 5:lt(l);break;case 4:Ve();break;case 31:l.memoizedState!==null&&hn(l);break;case 13:hn(l);break;case 19:ie(Bi);break;case 10:J(l.type);break;case 22:case 23:hn(l),Tg(),a!==null&&ie(Wo);break;case 24:J(ci)}}function Zc(a,l){try{var h=l.updateQueue,p=h!==null?h.lastEffect:null;if(p!==null){var T=p.next;h=T;do{if((h.tag&a)===a){p=void 0;var x=h.create,M=h.inst;p=x(),M.destroy=p}h=h.next}while(h!==T)}}catch(z){Xt(l,l.return,z)}}function za(a,l,h){try{var p=l.updateQueue,T=p!==null?p.lastEffect:null;if(T!==null){var x=T.next;p=x;do{if((p.tag&a)===a){var M=p.inst,z=M.destroy;if(z!==void 0){M.destroy=void 0,T=l;var ue=h,Se=z;try{Se()}catch(Oe){Xt(T,ue,Oe)}}}p=p.next}while(p!==x)}}catch(Oe){Xt(l,l.return,Oe)}}function H_(a){var l=a.updateQueue;if(l!==null){var h=a.stateNode;try{Rb(l,h)}catch(p){Xt(a,a.return,p)}}}function G_(a,l,h){h.props=el(a.type,a.memoizedProps),h.state=a.memoizedState;try{h.componentWillUnmount()}catch(p){Xt(a,l,p)}}function Jc(a,l){try{var h=a.ref;if(h!==null){switch(a.tag){case 26:case 27:case 5:var p=a.stateNode;break;case 30:p=a.stateNode;break;default:p=a.stateNode}typeof h=="function"?a.refCleanup=h(p):h.current=p}}catch(T){Xt(a,l,T)}}function vr(a,l){var h=a.ref,p=a.refCleanup;if(h!==null)if(typeof p=="function")try{p()}catch(T){Xt(a,l,T)}finally{a.refCleanup=null,a=a.alternate,a!=null&&(a.refCleanup=null)}else if(typeof h=="function")try{h(null)}catch(T){Xt(a,l,T)}else h.current=null}function V_(a){var l=a.type,h=a.memoizedProps,p=a.stateNode;try{e:switch(l){case"button":case"input":case"select":case"textarea":h.autoFocus&&p.focus();break e;case"img":h.src?p.src=h.src:h.srcSet&&(p.srcset=h.srcSet)}}catch(T){Xt(a,a.return,T)}}function Qg(a,l,h){try{var p=a.stateNode;kI(p,a.type,h,l),p[Bt]=l}catch(T){Xt(a,a.return,T)}}function q_(a){return a.tag===5||a.tag===3||a.tag===26||a.tag===27&&Ja(a.type)||a.tag===4}function Zg(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||q_(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.tag===27&&Ja(a.type)||a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function Jg(a,l,h){var p=a.tag;if(p===5||p===6)a=a.stateNode,l?(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h).insertBefore(a,l):(l=h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,l.appendChild(a),h=h._reactRootContainer,h!=null||l.onclick!==null||(l.onclick=Vn));else if(p!==4&&(p===27&&Ja(a.type)&&(h=a.stateNode,l=null),a=a.child,a!==null))for(Jg(a,l,h),a=a.sibling;a!==null;)Jg(a,l,h),a=a.sibling}function hf(a,l,h){var p=a.tag;if(p===5||p===6)a=a.stateNode,l?h.insertBefore(a,l):h.appendChild(a);else if(p!==4&&(p===27&&Ja(a.type)&&(h=a.stateNode),a=a.child,a!==null))for(hf(a,l,h),a=a.sibling;a!==null;)hf(a,l,h),a=a.sibling}function z_(a){var l=a.stateNode,h=a.memoizedProps;try{for(var p=a.type,T=l.attributes;T.length;)l.removeAttributeNode(T[0]);gs(l,p,h),l[Gt]=a,l[Bt]=h}catch(x){Xt(a,a.return,x)}}var ia=!1,zi=!1,e0=!1,K_=typeof WeakSet=="function"?WeakSet:Set,as=null;function cI(a,l){if(a=a.containerInfo,_0=Of,a=Xl(a),wc(a)){if("selectionStart"in a)var h={start:a.selectionStart,end:a.selectionEnd};else e:{h=(h=a.ownerDocument)&&h.defaultView||window;var p=h.getSelection&&h.getSelection();if(p&&p.rangeCount!==0){h=p.anchorNode;var T=p.anchorOffset,x=p.focusNode;p=p.focusOffset;try{h.nodeType,x.nodeType}catch{h=null;break e}var M=0,z=-1,ue=-1,Se=0,Oe=0,Be=a,De=null;t:for(;;){for(var Ie;Be!==h||T!==0&&Be.nodeType!==3||(z=M+T),Be!==x||p!==0&&Be.nodeType!==3||(ue=M+p),Be.nodeType===3&&(M+=Be.nodeValue.length),(Ie=Be.firstChild)!==null;)De=Be,Be=Ie;for(;;){if(Be===a)break t;if(De===h&&++Se===T&&(z=M),De===x&&++Oe===p&&(ue=M),(Ie=Be.nextSibling)!==null)break;Be=De,De=Be.parentNode}Be=Ie}h=z===-1||ue===-1?null:{start:z,end:ue}}else h=null}h=h||{start:0,end:0}}else h=null;for(x0={focusedElem:a,selectionRange:h},Of=!1,as=l;as!==null;)if(l=as,a=l.child,(l.subtreeFlags&1028)!==0&&a!==null)a.return=l,as=a;else for(;as!==null;){switch(l=as,x=l.alternate,a=l.flags,l.tag){case 0:if((a&4)!==0&&(a=l.updateQueue,a=a!==null?a.events:null,a!==null))for(h=0;h title"))),gs(x,p,h),x[Gt]=a,Hi(x),p=x;break e;case"link":var M=Jx("link","href",T).get(p+(h.href||""));if(M){for(var z=0;zii&&(M=ii,ii=ft,ft=M);var me=pi(z,ft),fe=pi(z,ii);if(me&&fe&&(Ie.rangeCount!==1||Ie.anchorNode!==me.node||Ie.anchorOffset!==me.offset||Ie.focusNode!==fe.node||Ie.focusOffset!==fe.offset)){var xe=Be.createRange();xe.setStart(me.node,me.offset),Ie.removeAllRanges(),ft>ii?(Ie.addRange(xe),Ie.extend(fe.node,fe.offset)):(xe.setEnd(fe.node,fe.offset),Ie.addRange(xe))}}}}for(Be=[],Ie=z;Ie=Ie.parentNode;)Ie.nodeType===1&&Be.push({element:Ie,left:Ie.scrollLeft,top:Ie.scrollTop});for(typeof z.focus=="function"&&z.focus(),z=0;zh?32:h,Y.T=null,h=o0,o0=null;var x=Xa,M=oa;if(Qi=0,hu=Xa=null,oa=0,(zt&6)!==0)throw Error(i(331));var z=zt;if(zt|=4,nx(x.current),tx(x,x.current,M,h),zt=z,rd(0,!1),Ti&&typeof Ti.onPostCommitFiberRoot=="function")try{Ti.onPostCommitFiberRoot(Ls,x)}catch{}return!0}finally{Q.p=T,Y.T=p,xx(a,l)}}function Ex(a,l,h){l=js(h,l),l=$g(a.stateNode,l,2),a=Ga(a,l,2),a!==null&&(wt(a,2),Tr(a))}function Xt(a,l,h){if(a.tag===3)Ex(a,a,h);else for(;l!==null;){if(l.tag===3){Ex(l,a,h);break}else if(l.tag===1){var p=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof p.componentDidCatch=="function"&&(Wa===null||!Wa.has(p))){a=js(h,a),h=A_(2),p=Ga(l,h,2),p!==null&&(C_(h,p,l,a),wt(p,2),Tr(p));break}}l=l.return}}function d0(a,l,h){var p=a.pingCache;if(p===null){p=a.pingCache=new fI;var T=new Set;p.set(l,T)}else T=p.get(l),T===void 0&&(T=new Set,p.set(l,T));T.has(h)||(s0=!0,T.add(h),a=vI.bind(null,a,l,h),l.then(a,a))}function vI(a,l,h){var p=a.pingCache;p!==null&&p.delete(l),a.pingedLanes|=a.suspendedLanes&h,a.warmLanes&=~h,ai===a&&(Ft&h)===h&&(Li===4||Li===3&&(Ft&62914560)===Ft&&300>We()-mf?(zt&2)===0&&fu(a,0):n0|=h,du===Ft&&(du=0)),Tr(a)}function Ax(a,l){l===0&&(l=Ge()),a=Xr(a,l),a!==null&&(wt(a,l),Tr(a))}function TI(a){var l=a.memoizedState,h=0;l!==null&&(h=l.retryLane),Ax(a,h)}function bI(a,l){var h=0;switch(a.tag){case 31:case 13:var p=a.stateNode,T=a.memoizedState;T!==null&&(h=T.retryLane);break;case 19:p=a.stateNode;break;case 22:p=a.stateNode._retryCache;break;default:throw Error(i(314))}p!==null&&p.delete(l),Ax(a,h)}function _I(a,l){return _e(a,l)}var xf=null,mu=null,h0=!1,Sf=!1,f0=!1,Za=0;function Tr(a){a!==mu&&a.next===null&&(mu===null?xf=mu=a:mu=mu.next=a),Sf=!0,h0||(h0=!0,SI())}function rd(a,l){if(!f0&&Sf){f0=!0;do for(var h=!1,p=xf;p!==null;){if(a!==0){var T=p.pendingLanes;if(T===0)var x=0;else{var M=p.suspendedLanes,z=p.pingedLanes;x=(1<<31-ce(42|a)+1)-1,x&=T&~(M&~z),x=x&201326741?x&201326741|1:x?x|2:0}x!==0&&(h=!0,Lx(p,x))}else x=Ft,x=G(p,p===ai?x:0,p.cancelPendingCommit!==null||p.timeoutHandle!==-1),(x&3)===0||re(p,x)||(h=!0,Lx(p,x));p=p.next}while(h);f0=!1}}function xI(){Cx()}function Cx(){Sf=h0=!1;var a=0;Za!==0&&OI()&&(a=Za);for(var l=We(),h=null,p=xf;p!==null;){var T=p.next,x=Dx(p,l);x===0?(p.next=null,h===null?xf=T:h.next=T,T===null&&(mu=h)):(h=p,(a!==0||(x&3)!==0)&&(Sf=!0)),p=T}Qi!==0&&Qi!==5||rd(a),Za!==0&&(Za=0)}function Dx(a,l){for(var h=a.suspendedLanes,p=a.pingedLanes,T=a.expirationTimes,x=a.pendingLanes&-62914561;0z)break;var Oe=ue.transferSize,Be=ue.initiatorType;Oe&&Bx(Be)&&(ue=ue.responseEnd,M+=Oe*(ue"u"?null:document;function Wx(a,l,h){var p=gu;if(p&&typeof l=="string"&&l){var T=fs(l);T='link[rel="'+a+'"][href="'+T+'"]',typeof h=="string"&&(T+='[crossorigin="'+h+'"]'),Yx.has(T)||(Yx.add(T),a={rel:a,crossOrigin:h,href:l},p.querySelector(T)===null&&(l=p.createElement("link"),gs(l,"link",a),Hi(l),p.head.appendChild(l)))}}function HI(a){la.D(a),Wx("dns-prefetch",a,null)}function GI(a,l){la.C(a,l),Wx("preconnect",a,l)}function VI(a,l,h){la.L(a,l,h);var p=gu;if(p&&a&&l){var T='link[rel="preload"][as="'+fs(l)+'"]';l==="image"&&h&&h.imageSrcSet?(T+='[imagesrcset="'+fs(h.imageSrcSet)+'"]',typeof h.imageSizes=="string"&&(T+='[imagesizes="'+fs(h.imageSizes)+'"]')):T+='[href="'+fs(a)+'"]';var x=T;switch(l){case"style":x=yu(a);break;case"script":x=vu(a)}kn.has(x)||(a=m({rel:"preload",href:l==="image"&&h&&h.imageSrcSet?void 0:a,as:l},h),kn.set(x,a),p.querySelector(T)!==null||l==="style"&&p.querySelector(ud(x))||l==="script"&&p.querySelector(cd(x))||(l=p.createElement("link"),gs(l,"link",a),Hi(l),p.head.appendChild(l)))}}function qI(a,l){la.m(a,l);var h=gu;if(h&&a){var p=l&&typeof l.as=="string"?l.as:"script",T='link[rel="modulepreload"][as="'+fs(p)+'"][href="'+fs(a)+'"]',x=T;switch(p){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":x=vu(a)}if(!kn.has(x)&&(a=m({rel:"modulepreload",href:a},l),kn.set(x,a),h.querySelector(T)===null)){switch(p){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(h.querySelector(cd(x)))return}p=h.createElement("link"),gs(p,"link",a),Hi(p),h.head.appendChild(p)}}}function zI(a,l,h){la.S(a,l,h);var p=gu;if(p&&a){var T=xa(p).hoistableStyles,x=yu(a);l=l||"default";var M=T.get(x);if(!M){var z={loading:0,preload:null};if(M=p.querySelector(ud(x)))z.loading=5;else{a=m({rel:"stylesheet",href:a,"data-precedence":l},h),(h=kn.get(x))&&L0(a,h);var ue=M=p.createElement("link");Hi(ue),gs(ue,"link",a),ue._p=new Promise(function(Se,Oe){ue.onload=Se,ue.onerror=Oe}),ue.addEventListener("load",function(){z.loading|=1}),ue.addEventListener("error",function(){z.loading|=2}),z.loading|=4,wf(M,l,p)}M={type:"stylesheet",instance:M,count:1,state:z},T.set(x,M)}}}function KI(a,l){la.X(a,l);var h=gu;if(h&&a){var p=xa(h).hoistableScripts,T=vu(a),x=p.get(T);x||(x=h.querySelector(cd(T)),x||(a=m({src:a,async:!0},l),(l=kn.get(T))&&I0(a,l),x=h.createElement("script"),Hi(x),gs(x,"link",a),h.head.appendChild(x)),x={type:"script",instance:x,count:1,state:null},p.set(T,x))}}function YI(a,l){la.M(a,l);var h=gu;if(h&&a){var p=xa(h).hoistableScripts,T=vu(a),x=p.get(T);x||(x=h.querySelector(cd(T)),x||(a=m({src:a,async:!0,type:"module"},l),(l=kn.get(T))&&I0(a,l),x=h.createElement("script"),Hi(x),gs(x,"link",a),h.head.appendChild(x)),x={type:"script",instance:x,count:1,state:null},p.set(T,x))}}function Xx(a,l,h,p){var T=(T=Ue.current)?Df(T):null;if(!T)throw Error(i(446));switch(a){case"meta":case"title":return null;case"style":return typeof h.precedence=="string"&&typeof h.href=="string"?(l=yu(h.href),h=xa(T).hoistableStyles,p=h.get(l),p||(p={type:"style",instance:null,count:0,state:null},h.set(l,p)),p):{type:"void",instance:null,count:0,state:null};case"link":if(h.rel==="stylesheet"&&typeof h.href=="string"&&typeof h.precedence=="string"){a=yu(h.href);var x=xa(T).hoistableStyles,M=x.get(a);if(M||(T=T.ownerDocument||T,M={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},x.set(a,M),(x=T.querySelector(ud(a)))&&!x._p&&(M.instance=x,M.state.loading=5),kn.has(a)||(h={rel:"preload",as:"style",href:h.href,crossOrigin:h.crossOrigin,integrity:h.integrity,media:h.media,hrefLang:h.hrefLang,referrerPolicy:h.referrerPolicy},kn.set(a,h),x||WI(T,a,h,M.state))),l&&p===null)throw Error(i(528,""));return M}if(l&&p!==null)throw Error(i(529,""));return null;case"script":return l=h.async,h=h.src,typeof h=="string"&&l&&typeof l!="function"&&typeof l!="symbol"?(l=vu(h),h=xa(T).hoistableScripts,p=h.get(l),p||(p={type:"script",instance:null,count:0,state:null},h.set(l,p)),p):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,a))}}function yu(a){return'href="'+fs(a)+'"'}function ud(a){return'link[rel="stylesheet"]['+a+"]"}function Qx(a){return m({},a,{"data-precedence":a.precedence,precedence:null})}function WI(a,l,h,p){a.querySelector('link[rel="preload"][as="style"]['+l+"]")?p.loading=1:(l=a.createElement("link"),p.preload=l,l.addEventListener("load",function(){return p.loading|=1}),l.addEventListener("error",function(){return p.loading|=2}),gs(l,"link",h),Hi(l),a.head.appendChild(l))}function vu(a){return'[src="'+fs(a)+'"]'}function cd(a){return"script[async]"+a}function Zx(a,l,h){if(l.count++,l.instance===null)switch(l.type){case"style":var p=a.querySelector('style[data-href~="'+fs(h.href)+'"]');if(p)return l.instance=p,Hi(p),p;var T=m({},h,{"data-href":h.href,"data-precedence":h.precedence,href:null,precedence:null});return p=(a.ownerDocument||a).createElement("style"),Hi(p),gs(p,"style",T),wf(p,h.precedence,a),l.instance=p;case"stylesheet":T=yu(h.href);var x=a.querySelector(ud(T));if(x)return l.state.loading|=4,l.instance=x,Hi(x),x;p=Qx(h),(T=kn.get(T))&&L0(p,T),x=(a.ownerDocument||a).createElement("link"),Hi(x);var M=x;return M._p=new Promise(function(z,ue){M.onload=z,M.onerror=ue}),gs(x,"link",p),l.state.loading|=4,wf(x,h.precedence,a),l.instance=x;case"script":return x=vu(h.src),(T=a.querySelector(cd(x)))?(l.instance=T,Hi(T),T):(p=h,(T=kn.get(x))&&(p=m({},h),I0(p,T)),a=a.ownerDocument||a,T=a.createElement("script"),Hi(T),gs(T,"link",p),a.head.appendChild(T),l.instance=T);case"void":return null;default:throw Error(i(443,l.type))}else l.type==="stylesheet"&&(l.state.loading&4)===0&&(p=l.instance,l.state.loading|=4,wf(p,h.precedence,a));return l.instance}function wf(a,l,h){for(var p=h.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),T=p.length?p[p.length-1]:null,x=T,M=0;M title"):null)}function XI(a,l,h){if(h===1||l.itemProp!=null)return!1;switch(a){case"meta":case"title":return!0;case"style":if(typeof l.precedence!="string"||typeof l.href!="string"||l.href==="")break;return!0;case"link":if(typeof l.rel!="string"||typeof l.href!="string"||l.href===""||l.onLoad||l.onError)break;return l.rel==="stylesheet"?(a=l.disabled,typeof l.precedence=="string"&&a==null):!0;case"script":if(l.async&&typeof l.async!="function"&&typeof l.async!="symbol"&&!l.onLoad&&!l.onError&&l.src&&typeof l.src=="string")return!0}return!1}function tS(a){return!(a.type==="stylesheet"&&(a.state.loading&3)===0)}function QI(a,l,h,p){if(h.type==="stylesheet"&&(typeof p.media!="string"||matchMedia(p.media).matches!==!1)&&(h.state.loading&4)===0){if(h.instance===null){var T=yu(p.href),x=l.querySelector(ud(T));if(x){l=x._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(a.count++,a=If.bind(a),l.then(a,a)),h.state.loading|=4,h.instance=x,Hi(x);return}x=l.ownerDocument||l,p=Qx(p),(T=kn.get(T))&&L0(p,T),x=x.createElement("link"),Hi(x);var M=x;M._p=new Promise(function(z,ue){M.onload=z,M.onerror=ue}),gs(x,"link",p),h.instance=x}a.stylesheets===null&&(a.stylesheets=new Map),a.stylesheets.set(h,l),(l=h.state.preload)&&(h.state.loading&3)===0&&(a.count++,h=If.bind(a),l.addEventListener("load",h),l.addEventListener("error",h))}}var k0=0;function ZI(a,l){return a.stylesheets&&a.count===0&&Rf(a,a.stylesheets),0k0?50:800)+l);return a.unsuspend=h,function(){a.unsuspend=null,clearTimeout(p),clearTimeout(T)}}:null}function If(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Rf(this,this.stylesheets);else if(this.unsuspend){var a=this.unsuspend;this.unsuspend=null,a()}}}var kf=null;function Rf(a,l){a.stylesheets=null,a.unsuspend!==null&&(a.count++,kf=new Map,l.forEach(JI,a),kf=null,If.call(a))}function JI(a,l){if(!(l.state.loading&4)){var h=kf.get(a);if(h)var p=h.get(null);else{h=new Map,kf.set(a,h);for(var T=a.querySelectorAll("link[data-precedence],style[data-precedence]"),x=0;x"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),$0.exports=gk(),$0.exports}var vk=yk();function Tk(...s){return s.filter(Boolean).join(" ")}const bk="inline-flex items-center justify-center font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",_k={sm:"rounded-sm",md:"rounded-md",full:"rounded-full"},xk={xs:"px-2 py-1 text-xs",sm:"px-2.5 py-1.5 text-sm",md:"px-3 py-2 text-sm",lg:"px-3.5 py-2.5 text-sm"},Sk={indigo:{primary:"bg-indigo-600 text-white shadow-xs hover:bg-indigo-500 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:shadow-none dark:hover:bg-indigo-400 dark:focus-visible:outline-indigo-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-indigo-50 text-indigo-600 shadow-xs hover:bg-indigo-100 dark:bg-indigo-500/20 dark:text-indigo-400 dark:shadow-none dark:hover:bg-indigo-500/30"},blue:{primary:"bg-blue-600 text-white shadow-xs hover:bg-blue-500 focus-visible:outline-blue-600 dark:bg-blue-500 dark:shadow-none dark:hover:bg-blue-400 dark:focus-visible:outline-blue-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-blue-50 text-blue-600 shadow-xs hover:bg-blue-100 dark:bg-blue-500/20 dark:text-blue-400 dark:shadow-none dark:hover:bg-blue-500/30"},emerald:{primary:"bg-emerald-600 text-white shadow-xs hover:bg-emerald-500 focus-visible:outline-emerald-600 dark:bg-emerald-500 dark:shadow-none dark:hover:bg-emerald-400 dark:focus-visible:outline-emerald-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-emerald-50 text-emerald-700 shadow-xs hover:bg-emerald-100 dark:bg-emerald-500/20 dark:text-emerald-400 dark:shadow-none dark:hover:bg-emerald-500/30"},red:{primary:"bg-red-600 text-white shadow-xs hover:bg-red-500 focus-visible:outline-red-600 dark:bg-red-500 dark:shadow-none dark:hover:bg-red-400 dark:focus-visible:outline-red-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-red-50 text-red-700 shadow-xs hover:bg-red-100 dark:bg-red-500/20 dark:text-red-400 dark:shadow-none dark:hover:bg-red-500/30"},amber:{primary:"bg-amber-500 text-white shadow-xs hover:bg-amber-400 focus-visible:outline-amber-500 dark:bg-amber-500 dark:shadow-none dark:hover:bg-amber-400 dark:focus-visible:outline-amber-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-amber-50 text-amber-800 shadow-xs hover:bg-amber-100 dark:bg-amber-500/20 dark:text-amber-300 dark:shadow-none dark:hover:bg-amber-500/30"}};function Ek(){return O.jsxs("svg",{viewBox:"0 0 24 24",className:"size-4 animate-spin","aria-hidden":"true",children:[O.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.25"}),O.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.9"})]})}function es({children:s,variant:e="primary",color:t="indigo",size:i="md",rounded:n="md",leadingIcon:r,trailingIcon:o,isLoading:u=!1,disabled:c,className:d,type:f="button",...m}){const g=r||o||u?"gap-x-1.5":"";return O.jsxs("button",{type:f,disabled:c||u,className:Tk(bk,_k[n],xk[i],Sk[t][e],g,d),...m,children:[u?O.jsx("span",{className:"-ml-0.5",children:O.jsx(Ek,{})}):r&&O.jsx("span",{className:"-ml-0.5",children:r}),O.jsx("span",{children:s}),o&&!u&&O.jsx("span",{className:"-mr-0.5",children:o})]})}function W2(s){var e,t,i="";if(typeof s=="string"||typeof s=="number")i+=s;else if(typeof s=="object")if(Array.isArray(s)){var n=s.length;for(e=0;ee in s?Ak(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,V0=(s,e,t)=>(Ck(s,typeof e!="symbol"?e+"":e,t),t);let Dk=class{constructor(){V0(this,"current",this.detect()),V0(this,"handoffState","pending"),V0(this,"currentId",0)}set(e){this.current!==e&&(this.handoffState="pending",this.currentId=0,this.current=e)}reset(){this.set(this.detect())}nextId(){return++this.currentId}get isServer(){return this.current==="server"}get isClient(){return this.current==="client"}detect(){return typeof window>"u"||typeof document>"u"?"server":"client"}handoff(){this.handoffState==="pending"&&(this.handoffState="complete")}get isHandoffComplete(){return this.handoffState==="complete"}},Pr=new Dk;function nh(s){var e;return Pr.isServer?null:s==null?document:(e=s?.ownerDocument)!=null?e:document}function ov(s){var e,t;return Pr.isServer?null:s==null?document:(t=(e=s?.getRootNode)==null?void 0:e.call(s))!=null?t:document}function X2(s){var e,t;return(t=(e=ov(s))==null?void 0:e.activeElement)!=null?t:null}function wk(s){return X2(s)===s}function um(s){typeof queueMicrotask=="function"?queueMicrotask(s):Promise.resolve().then(s).catch(e=>setTimeout(()=>{throw e}))}function _a(){let s=[],e={addEventListener(t,i,n,r){return t.addEventListener(i,n,r),e.add(()=>t.removeEventListener(i,n,r))},requestAnimationFrame(...t){let i=requestAnimationFrame(...t);return e.add(()=>cancelAnimationFrame(i))},nextFrame(...t){return e.requestAnimationFrame(()=>e.requestAnimationFrame(...t))},setTimeout(...t){let i=setTimeout(...t);return e.add(()=>clearTimeout(i))},microTask(...t){let i={current:!0};return um(()=>{i.current&&t[0]()}),e.add(()=>{i.current=!1})},style(t,i,n){let r=t.style.getPropertyValue(i);return Object.assign(t.style,{[i]:n}),this.add(()=>{Object.assign(t.style,{[i]:r})})},group(t){let i=_a();return t(i),this.add(()=>i.dispose())},add(t){return s.includes(t)||s.push(t),()=>{let i=s.indexOf(t);if(i>=0)for(let n of s.splice(i,1))n()}},dispose(){for(let t of s.splice(0))t()}};return e}function cm(){let[s]=j.useState(_a);return j.useEffect(()=>()=>s.dispose(),[s]),s}let nn=(s,e)=>{Pr.isServer?j.useEffect(s,e):j.useLayoutEffect(s,e)};function Dl(s){let e=j.useRef(s);return nn(()=>{e.current=s},[s]),e}let li=function(s){let e=Dl(s);return bt.useCallback((...t)=>e.current(...t),[e])};function rh(s){return j.useMemo(()=>s,Object.values(s))}let Lk=j.createContext(void 0);function Ik(){return j.useContext(Lk)}function lv(...s){return Array.from(new Set(s.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function Ta(s,e,...t){if(s in e){let n=e[s];return typeof n=="function"?n(...t):n}let i=new Error(`Tried to handle "${s}" but there is no handler defined. Only defined handlers are: ${Object.keys(e).map(n=>`"${n}"`).join(", ")}.`);throw Error.captureStackTrace&&Error.captureStackTrace(i,Ta),i}var wp=(s=>(s[s.None=0]="None",s[s.RenderStrategy=1]="RenderStrategy",s[s.Static=2]="Static",s))(wp||{}),vo=(s=>(s[s.Unmount=0]="Unmount",s[s.Hidden=1]="Hidden",s))(vo||{});function Un(){let s=Rk();return j.useCallback(e=>kk({mergeRefs:s,...e}),[s])}function kk({ourProps:s,theirProps:e,slot:t,defaultTag:i,features:n,visible:r=!0,name:o,mergeRefs:u}){u=u??Ok;let c=Q2(e,s);if(r)return $f(c,t,i,o,u);let d=n??0;if(d&2){let{static:f=!1,...m}=c;if(f)return $f(m,t,i,o,u)}if(d&1){let{unmount:f=!0,...m}=c;return Ta(f?0:1,{0(){return null},1(){return $f({...m,hidden:!0,style:{display:"none"}},t,i,o,u)}})}return $f(c,t,i,o,u)}function $f(s,e={},t,i,n){let{as:r=t,children:o,refName:u="ref",...c}=q0(s,["unmount","static"]),d=s.ref!==void 0?{[u]:s.ref}:{},f=typeof o=="function"?o(e):o;"className"in c&&c.className&&typeof c.className=="function"&&(c.className=c.className(e)),c["aria-labelledby"]&&c["aria-labelledby"]===c.id&&(c["aria-labelledby"]=void 0);let m={};if(e){let g=!1,v=[];for(let[b,_]of Object.entries(e))typeof _=="boolean"&&(g=!0),_===!0&&v.push(b.replace(/([A-Z])/g,E=>`-${E.toLowerCase()}`));if(g){m["data-headlessui-state"]=v.join(" ");for(let b of v)m[`data-${b}`]=""}}if(Rd(r)&&(Object.keys(ul(c)).length>0||Object.keys(ul(m)).length>0))if(!j.isValidElement(f)||Array.isArray(f)&&f.length>1||Mk(f)){if(Object.keys(ul(c)).length>0)throw new Error(['Passing props on "Fragment"!',"",`The current component <${i} /> is rendering a "Fragment".`,"However we need to passthrough the following props:",Object.keys(ul(c)).concat(Object.keys(ul(m))).map(g=>` - ${g}`).join(` -`),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(g=>` - ${g}`).join(` -`)].join(` -`))}else{let g=f.props,v=g?.className,b=typeof v=="function"?(...L)=>lv(v(...L),c.className):lv(v,c.className),_=b?{className:b}:{},E=Q2(f.props,ul(q0(c,["ref"])));for(let L in m)L in E&&delete m[L];return j.cloneElement(f,Object.assign({},E,m,d,{ref:n(Pk(f),d.ref)},_))}return j.createElement(r,Object.assign({},q0(c,["ref"]),!Rd(r)&&d,!Rd(r)&&m),f)}function Rk(){let s=j.useRef([]),e=j.useCallback(t=>{for(let i of s.current)i!=null&&(typeof i=="function"?i(t):i.current=t)},[]);return(...t)=>{if(!t.every(i=>i==null))return s.current=t,e}}function Ok(...s){return s.every(e=>e==null)?void 0:e=>{for(let t of s)t!=null&&(typeof t=="function"?t(e):t.current=e)}}function Q2(...s){if(s.length===0)return{};if(s.length===1)return s[0];let e={},t={};for(let i of s)for(let n in i)n.startsWith("on")&&typeof i[n]=="function"?(t[n]!=null||(t[n]=[]),t[n].push(i[n])):e[n]=i[n];if(e.disabled||e["aria-disabled"])for(let i in t)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(i)&&(t[i]=[n=>{var r;return(r=n?.preventDefault)==null?void 0:r.call(n)}]);for(let i in t)Object.assign(e,{[i](n,...r){let o=t[i];for(let u of o){if((n instanceof Event||n?.nativeEvent instanceof Event)&&n.defaultPrevented)return;u(n,...r)}}});return e}function an(s){var e;return Object.assign(j.forwardRef(s),{displayName:(e=s.displayName)!=null?e:s.name})}function ul(s){let e=Object.assign({},s);for(let t in e)e[t]===void 0&&delete e[t];return e}function q0(s,e=[]){let t=Object.assign({},s);for(let i of e)i in t&&delete t[i];return t}function Pk(s){return bt.version.split(".")[0]>="19"?s.props.ref:s.ref}function Rd(s){return s===j.Fragment||s===Symbol.for("react.fragment")}function Mk(s){return Rd(s.type)}let Nk="span";var Lp=(s=>(s[s.None=1]="None",s[s.Focusable=2]="Focusable",s[s.Hidden=4]="Hidden",s))(Lp||{});function Bk(s,e){var t;let{features:i=1,...n}=s,r={ref:e,"aria-hidden":(i&2)===2?!0:(t=n["aria-hidden"])!=null?t:void 0,hidden:(i&4)===4?!0:void 0,style:{position:"fixed",top:1,left:1,width:1,height:0,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0",...(i&4)===4&&(i&2)!==2&&{display:"none"}}};return Un()({ourProps:r,theirProps:n,slot:{},defaultTag:Nk,name:"Hidden"})}let uv=an(Bk);function Fk(s){return typeof s!="object"||s===null?!1:"nodeType"in s}function bo(s){return Fk(s)&&"tagName"in s}function Sl(s){return bo(s)&&"accessKey"in s}function To(s){return bo(s)&&"tabIndex"in s}function Uk(s){return bo(s)&&"style"in s}function $k(s){return Sl(s)&&s.nodeName==="IFRAME"}function jk(s){return Sl(s)&&s.nodeName==="INPUT"}let Z2=Symbol();function Hk(s,e=!0){return Object.assign(s,{[Z2]:e})}function $r(...s){let e=j.useRef(s);j.useEffect(()=>{e.current=s},[s]);let t=li(i=>{for(let n of e.current)n!=null&&(typeof n=="function"?n(i):n.current=i)});return s.every(i=>i==null||i?.[Z2])?void 0:t}let lT=j.createContext(null);lT.displayName="DescriptionContext";function J2(){let s=j.useContext(lT);if(s===null){let e=new Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(e,J2),e}return s}function Gk(){let[s,e]=j.useState([]);return[s.length>0?s.join(" "):void 0,j.useMemo(()=>function(t){let i=li(r=>(e(o=>[...o,r]),()=>e(o=>{let u=o.slice(),c=u.indexOf(r);return c!==-1&&u.splice(c,1),u}))),n=j.useMemo(()=>({register:i,slot:t.slot,name:t.name,props:t.props,value:t.value}),[i,t.slot,t.name,t.props,t.value]);return bt.createElement(lT.Provider,{value:n},t.children)},[e])]}let Vk="p";function qk(s,e){let t=j.useId(),i=Ik(),{id:n=`headlessui-description-${t}`,...r}=s,o=J2(),u=$r(e);nn(()=>o.register(n),[n,o.register]);let c=rh({...o.slot,disabled:i||!1}),d={ref:u,...o.props,id:n};return Un()({ourProps:d,theirProps:r,slot:c,defaultTag:Vk,name:o.name||"Description"})}let zk=an(qk),Kk=Object.assign(zk,{});var eA=(s=>(s.Space=" ",s.Enter="Enter",s.Escape="Escape",s.Backspace="Backspace",s.Delete="Delete",s.ArrowLeft="ArrowLeft",s.ArrowUp="ArrowUp",s.ArrowRight="ArrowRight",s.ArrowDown="ArrowDown",s.Home="Home",s.End="End",s.PageUp="PageUp",s.PageDown="PageDown",s.Tab="Tab",s))(eA||{});let Yk=j.createContext(()=>{});function Wk({value:s,children:e}){return bt.createElement(Yk.Provider,{value:s},e)}let tA=class extends Map{constructor(e){super(),this.factory=e}get(e){let t=super.get(e);return t===void 0&&(t=this.factory(e),this.set(e,t)),t}};var Xk=Object.defineProperty,Qk=(s,e,t)=>e in s?Xk(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Zk=(s,e,t)=>(Qk(s,e+"",t),t),iA=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Rn=(s,e,t)=>(iA(s,e,"read from private field"),t?t.call(s):e.get(s)),z0=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)},CS=(s,e,t,i)=>(iA(s,e,"write to private field"),e.set(s,t),t),Sr,Ad,Cd;let Jk=class{constructor(e){z0(this,Sr,{}),z0(this,Ad,new tA(()=>new Set)),z0(this,Cd,new Set),Zk(this,"disposables",_a()),CS(this,Sr,e),Pr.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return Rn(this,Sr)}subscribe(e,t){if(Pr.isServer)return()=>{};let i={selector:e,callback:t,current:e(Rn(this,Sr))};return Rn(this,Cd).add(i),this.disposables.add(()=>{Rn(this,Cd).delete(i)})}on(e,t){return Pr.isServer?()=>{}:(Rn(this,Ad).get(e).add(t),this.disposables.add(()=>{Rn(this,Ad).get(e).delete(t)}))}send(e){let t=this.reduce(Rn(this,Sr),e);if(t!==Rn(this,Sr)){CS(this,Sr,t);for(let i of Rn(this,Cd)){let n=i.selector(Rn(this,Sr));sA(i.current,n)||(i.current=n,i.callback(n))}for(let i of Rn(this,Ad).get(e.type))i(Rn(this,Sr),e)}}};Sr=new WeakMap,Ad=new WeakMap,Cd=new WeakMap;function sA(s,e){return Object.is(s,e)?!0:typeof s!="object"||s===null||typeof e!="object"||e===null?!1:Array.isArray(s)&&Array.isArray(e)?s.length!==e.length?!1:K0(s[Symbol.iterator](),e[Symbol.iterator]()):s instanceof Map&&e instanceof Map||s instanceof Set&&e instanceof Set?s.size!==e.size?!1:K0(s.entries(),e.entries()):DS(s)&&DS(e)?K0(Object.entries(s)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function K0(s,e){do{let t=s.next(),i=e.next();if(t.done&&i.done)return!0;if(t.done||i.done||!Object.is(t.value,i.value))return!1}while(!0)}function DS(s){if(Object.prototype.toString.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||Object.getPrototypeOf(e)===null}var eR=Object.defineProperty,tR=(s,e,t)=>e in s?eR(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,wS=(s,e,t)=>(tR(s,typeof e!="symbol"?e+"":e,t),t),iR=(s=>(s[s.Push=0]="Push",s[s.Pop=1]="Pop",s))(iR||{});let sR={0(s,e){let t=e.id,i=s.stack,n=s.stack.indexOf(t);if(n!==-1){let r=s.stack.slice();return r.splice(n,1),r.push(t),i=r,{...s,stack:i}}return{...s,stack:[...s.stack,t]}},1(s,e){let t=e.id,i=s.stack.indexOf(t);if(i===-1)return s;let n=s.stack.slice();return n.splice(i,1),{...s,stack:n}}},nR=class nA extends Jk{constructor(){super(...arguments),wS(this,"actions",{push:e=>this.send({type:0,id:e}),pop:e=>this.send({type:1,id:e})}),wS(this,"selectors",{isTop:(e,t)=>e.stack[e.stack.length-1]===t,inStack:(e,t)=>e.stack.includes(t)})}static new(){return new nA({stack:[]})}reduce(e,t){return Ta(t.type,sR,e,t)}};const rA=new tA(()=>nR.new());var Y0={exports:{}},W0={};var LS;function rR(){if(LS)return W0;LS=1;var s=lm();function e(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var t=typeof Object.is=="function"?Object.is:e,i=s.useSyncExternalStore,n=s.useRef,r=s.useEffect,o=s.useMemo,u=s.useDebugValue;return W0.useSyncExternalStoreWithSelector=function(c,d,f,m,g){var v=n(null);if(v.current===null){var b={hasValue:!1,value:null};v.current=b}else b=v.current;v=o(function(){function E(U){if(!L){if(L=!0,I=U,U=m(U),g!==void 0&&b.hasValue){var V=b.value;if(g(V,U))return w=V}return w=U}if(V=w,t(I,U))return V;var B=m(U);return g!==void 0&&g(V,B)?(I=U,V):(I=U,w=B)}var L=!1,I,w,F=f===void 0?null:f;return[function(){return E(d())},F===null?void 0:function(){return E(F())}]},[d,f,m,g]);var _=i(c,v[0],v[1]);return r(function(){b.hasValue=!0,b.value=_},[_]),u(_),_},W0}var IS;function aR(){return IS||(IS=1,Y0.exports=rR()),Y0.exports}var oR=aR();function aA(s,e,t=sA){return oR.useSyncExternalStoreWithSelector(li(i=>s.subscribe(lR,i)),li(()=>s.state),li(()=>s.state),li(e),t)}function lR(s){return s}function ah(s,e){let t=j.useId(),i=rA.get(e),[n,r]=aA(i,j.useCallback(o=>[i.selectors.isTop(o,t),i.selectors.inStack(o,t)],[i,t]));return nn(()=>{if(s)return i.actions.push(t),()=>i.actions.pop(t)},[i,s,t]),s?r?n:!0:!1}let cv=new Map,Od=new Map;function kS(s){var e;let t=(e=Od.get(s))!=null?e:0;return Od.set(s,t+1),t!==0?()=>RS(s):(cv.set(s,{"aria-hidden":s.getAttribute("aria-hidden"),inert:s.inert}),s.setAttribute("aria-hidden","true"),s.inert=!0,()=>RS(s))}function RS(s){var e;let t=(e=Od.get(s))!=null?e:1;if(t===1?Od.delete(s):Od.set(s,t-1),t!==1)return;let i=cv.get(s);i&&(i["aria-hidden"]===null?s.removeAttribute("aria-hidden"):s.setAttribute("aria-hidden",i["aria-hidden"]),s.inert=i.inert,cv.delete(s))}function uR(s,{allowed:e,disallowed:t}={}){let i=ah(s,"inert-others");nn(()=>{var n,r;if(!i)return;let o=_a();for(let c of(n=t?.())!=null?n:[])c&&o.add(kS(c));let u=(r=e?.())!=null?r:[];for(let c of u){if(!c)continue;let d=nh(c);if(!d)continue;let f=c.parentElement;for(;f&&f!==d.body;){for(let m of f.children)u.some(g=>m.contains(g))||o.add(kS(m));f=f.parentElement}}return o.dispose},[i,e,t])}function cR(s,e,t){let i=Dl(n=>{let r=n.getBoundingClientRect();r.x===0&&r.y===0&&r.width===0&&r.height===0&&t()});j.useEffect(()=>{if(!s)return;let n=e===null?null:Sl(e)?e:e.current;if(!n)return;let r=_a();if(typeof ResizeObserver<"u"){let o=new ResizeObserver(()=>i.current(n));o.observe(n),r.add(()=>o.disconnect())}if(typeof IntersectionObserver<"u"){let o=new IntersectionObserver(()=>i.current(n));o.observe(n),r.add(()=>o.disconnect())}return()=>r.dispose()},[e,i,s])}let Ip=["[contentEditable=true]","[tabindex]","a[href]","area[href]","button:not([disabled])","iframe","input:not([disabled])","select:not([disabled])","details>summary","textarea:not([disabled])"].map(s=>`${s}:not([tabindex='-1'])`).join(","),dR=["[data-autofocus]"].map(s=>`${s}:not([tabindex='-1'])`).join(",");var pa=(s=>(s[s.First=1]="First",s[s.Previous=2]="Previous",s[s.Next=4]="Next",s[s.Last=8]="Last",s[s.WrapAround=16]="WrapAround",s[s.NoScroll=32]="NoScroll",s[s.AutoFocus=64]="AutoFocus",s))(pa||{}),dv=(s=>(s[s.Error=0]="Error",s[s.Overflow=1]="Overflow",s[s.Success=2]="Success",s[s.Underflow=3]="Underflow",s))(dv||{}),hR=(s=>(s[s.Previous=-1]="Previous",s[s.Next=1]="Next",s))(hR||{});function fR(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(Ip)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}function pR(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(dR)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var oA=(s=>(s[s.Strict=0]="Strict",s[s.Loose=1]="Loose",s))(oA||{});function mR(s,e=0){var t;return s===((t=nh(s))==null?void 0:t.body)?!1:Ta(e,{0(){return s.matches(Ip)},1(){let i=s;for(;i!==null;){if(i.matches(Ip))return!0;i=i.parentElement}return!1}})}var gR=(s=>(s[s.Keyboard=0]="Keyboard",s[s.Mouse=1]="Mouse",s))(gR||{});typeof window<"u"&&typeof document<"u"&&(document.addEventListener("keydown",s=>{s.metaKey||s.altKey||s.ctrlKey||(document.documentElement.dataset.headlessuiFocusVisible="")},!0),document.addEventListener("click",s=>{s.detail===1?delete document.documentElement.dataset.headlessuiFocusVisible:s.detail===0&&(document.documentElement.dataset.headlessuiFocusVisible="")},!0));function ya(s){s?.focus({preventScroll:!0})}let yR=["textarea","input"].join(",");function vR(s){var e,t;return(t=(e=s?.matches)==null?void 0:e.call(s,yR))!=null?t:!1}function TR(s,e=t=>t){return s.slice().sort((t,i)=>{let n=e(t),r=e(i);if(n===null||r===null)return 0;let o=n.compareDocumentPosition(r);return o&Node.DOCUMENT_POSITION_FOLLOWING?-1:o&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function Pd(s,e,{sorted:t=!0,relativeTo:i=null,skipElements:n=[]}={}){let r=Array.isArray(s)?s.length>0?ov(s[0]):document:ov(s),o=Array.isArray(s)?t?TR(s):s:e&64?pR(s):fR(s);n.length>0&&o.length>1&&(o=o.filter(v=>!n.some(b=>b!=null&&"current"in b?b?.current===v:b===v))),i=i??r?.activeElement;let u=(()=>{if(e&5)return 1;if(e&10)return-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),c=(()=>{if(e&1)return 0;if(e&2)return Math.max(0,o.indexOf(i))-1;if(e&4)return Math.max(0,o.indexOf(i))+1;if(e&8)return o.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),d=e&32?{preventScroll:!0}:{},f=0,m=o.length,g;do{if(f>=m||f+m<=0)return 0;let v=c+f;if(e&16)v=(v+m)%m;else{if(v<0)return 3;if(v>=m)return 1}g=o[v],g?.focus(d),f+=u}while(g!==X2(g));return e&6&&vR(g)&&g.select(),2}function lA(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function bR(){return/Android/gi.test(window.navigator.userAgent)}function OS(){return lA()||bR()}function jf(s,e,t,i){let n=Dl(t);j.useEffect(()=>{if(!s)return;function r(o){n.current(o)}return document.addEventListener(e,r,i),()=>document.removeEventListener(e,r,i)},[s,e,i])}function uA(s,e,t,i){let n=Dl(t);j.useEffect(()=>{if(!s)return;function r(o){n.current(o)}return window.addEventListener(e,r,i),()=>window.removeEventListener(e,r,i)},[s,e,i])}const PS=30;function _R(s,e,t){let i=Dl(t),n=j.useCallback(function(u,c){if(u.defaultPrevented)return;let d=c(u);if(d===null||!d.getRootNode().contains(d)||!d.isConnected)return;let f=(function m(g){return typeof g=="function"?m(g()):Array.isArray(g)||g instanceof Set?g:[g]})(e);for(let m of f)if(m!==null&&(m.contains(d)||u.composed&&u.composedPath().includes(m)))return;return!mR(d,oA.Loose)&&d.tabIndex!==-1&&u.preventDefault(),i.current(u,d)},[i,e]),r=j.useRef(null);jf(s,"pointerdown",u=>{var c,d;OS()||(r.current=((d=(c=u.composedPath)==null?void 0:c.call(u))==null?void 0:d[0])||u.target)},!0),jf(s,"pointerup",u=>{if(OS()||!r.current)return;let c=r.current;return r.current=null,n(u,()=>c)},!0);let o=j.useRef({x:0,y:0});jf(s,"touchstart",u=>{o.current.x=u.touches[0].clientX,o.current.y=u.touches[0].clientY},!0),jf(s,"touchend",u=>{let c={x:u.changedTouches[0].clientX,y:u.changedTouches[0].clientY};if(!(Math.abs(c.x-o.current.x)>=PS||Math.abs(c.y-o.current.y)>=PS))return n(u,()=>To(u.target)?u.target:null)},!0),uA(s,"blur",u=>n(u,()=>$k(window.document.activeElement)?window.document.activeElement:null),!0)}function uT(...s){return j.useMemo(()=>nh(...s),[...s])}function cA(s,e,t,i){let n=Dl(t);j.useEffect(()=>{s=s??window;function r(o){n.current(o)}return s.addEventListener(e,r,i),()=>s.removeEventListener(e,r,i)},[s,e,i])}function xR(s){return j.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getSnapshot)}function SR(s,e){let t=s(),i=new Set;return{getSnapshot(){return t},subscribe(n){return i.add(n),()=>i.delete(n)},dispatch(n,...r){let o=e[n].call(t,...r);o&&(t=o,i.forEach(u=>u()))}}}function ER(){let s;return{before({doc:e}){var t;let i=e.documentElement,n=(t=e.defaultView)!=null?t:window;s=Math.max(0,n.innerWidth-i.clientWidth)},after({doc:e,d:t}){let i=e.documentElement,n=Math.max(0,i.clientWidth-i.offsetWidth),r=Math.max(0,s-n);t.style(i,"paddingRight",`${r}px`)}}}function AR(){return lA()?{before({doc:s,d:e,meta:t}){function i(n){for(let r of t().containers)for(let o of r())if(o.contains(n))return!0;return!1}e.microTask(()=>{var n;if(window.getComputedStyle(s.documentElement).scrollBehavior!=="auto"){let u=_a();u.style(s.documentElement,"scrollBehavior","auto"),e.add(()=>e.microTask(()=>u.dispose()))}let r=(n=window.scrollY)!=null?n:window.pageYOffset,o=null;e.addEventListener(s,"click",u=>{if(To(u.target))try{let c=u.target.closest("a");if(!c)return;let{hash:d}=new URL(c.href),f=s.querySelector(d);To(f)&&!i(f)&&(o=f)}catch{}},!0),e.group(u=>{e.addEventListener(s,"touchstart",c=>{if(u.dispose(),To(c.target)&&Uk(c.target))if(i(c.target)){let d=c.target;for(;d.parentElement&&i(d.parentElement);)d=d.parentElement;u.style(d,"overscrollBehavior","contain")}else u.style(c.target,"touchAction","none")})}),e.addEventListener(s,"touchmove",u=>{if(To(u.target)){if(jk(u.target))return;if(i(u.target)){let c=u.target;for(;c.parentElement&&c.dataset.headlessuiPortal!==""&&!(c.scrollHeight>c.clientHeight||c.scrollWidth>c.clientWidth);)c=c.parentElement;c.dataset.headlessuiPortal===""&&u.preventDefault()}else u.preventDefault()}},{passive:!1}),e.add(()=>{var u;let c=(u=window.scrollY)!=null?u:window.pageYOffset;r!==c&&window.scrollTo(0,r),o&&o.isConnected&&(o.scrollIntoView({block:"nearest"}),o=null)})})}}:{}}function CR(){return{before({doc:s,d:e}){e.style(s.documentElement,"overflow","hidden")}}}function MS(s){let e={};for(let t of s)Object.assign(e,t(e));return e}let pl=SR(()=>new Map,{PUSH(s,e){var t;let i=(t=this.get(s))!=null?t:{doc:s,count:0,d:_a(),meta:new Set,computedMeta:{}};return i.count++,i.meta.add(e),i.computedMeta=MS(i.meta),this.set(s,i),this},POP(s,e){let t=this.get(s);return t&&(t.count--,t.meta.delete(e),t.computedMeta=MS(t.meta)),this},SCROLL_PREVENT(s){let e={doc:s.doc,d:s.d,meta(){return s.computedMeta}},t=[AR(),ER(),CR()];t.forEach(({before:i})=>i?.(e)),t.forEach(({after:i})=>i?.(e))},SCROLL_ALLOW({d:s}){s.dispose()},TEARDOWN({doc:s}){this.delete(s)}});pl.subscribe(()=>{let s=pl.getSnapshot(),e=new Map;for(let[t]of s)e.set(t,t.documentElement.style.overflow);for(let t of s.values()){let i=e.get(t.doc)==="hidden",n=t.count!==0;(n&&!i||!n&&i)&&pl.dispatch(t.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",t),t.count===0&&pl.dispatch("TEARDOWN",t)}});function DR(s,e,t=()=>({containers:[]})){let i=xR(pl),n=e?i.get(e):void 0,r=n?n.count>0:!1;return nn(()=>{if(!(!e||!s))return pl.dispatch("PUSH",e,t),()=>pl.dispatch("POP",e,t)},[s,e]),r}function wR(s,e,t=()=>[document.body]){let i=ah(s,"scroll-lock");DR(i,e,n=>{var r;return{containers:[...(r=n.containers)!=null?r:[],t]}})}function LR(s=0){let[e,t]=j.useState(s),i=j.useCallback(c=>t(c),[]),n=j.useCallback(c=>t(d=>d|c),[]),r=j.useCallback(c=>(e&c)===c,[e]),o=j.useCallback(c=>t(d=>d&~c),[]),u=j.useCallback(c=>t(d=>d^c),[]);return{flags:e,setFlag:i,addFlag:n,hasFlag:r,removeFlag:o,toggleFlag:u}}var IR={},NS,BS;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((NS=process==null?void 0:IR)==null?void 0:NS.NODE_ENV)==="test"&&typeof((BS=Element?.prototype)==null?void 0:BS.getAnimations)>"u"&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` -`)),[]});var kR=(s=>(s[s.None=0]="None",s[s.Closed=1]="Closed",s[s.Enter=2]="Enter",s[s.Leave=4]="Leave",s))(kR||{});function RR(s){let e={};for(let t in s)s[t]===!0&&(e[`data-${t}`]="");return e}function OR(s,e,t,i){let[n,r]=j.useState(t),{hasFlag:o,addFlag:u,removeFlag:c}=LR(s&&n?3:0),d=j.useRef(!1),f=j.useRef(!1),m=cm();return nn(()=>{var g;if(s){if(t&&r(!0),!e){t&&u(3);return}return(g=i?.start)==null||g.call(i,t),PR(e,{inFlight:d,prepare(){f.current?f.current=!1:f.current=d.current,d.current=!0,!f.current&&(t?(u(3),c(4)):(u(4),c(2)))},run(){f.current?t?(c(3),u(4)):(c(4),u(3)):t?c(1):u(1)},done(){var v;f.current&&BR(e)||(d.current=!1,c(7),t||r(!1),(v=i?.end)==null||v.call(i,t))}})}},[s,t,e,m]),s?[n,{closed:o(1),enter:o(2),leave:o(4),transition:o(2)||o(4)}]:[t,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function PR(s,{prepare:e,run:t,done:i,inFlight:n}){let r=_a();return NR(s,{prepare:e,inFlight:n}),r.nextFrame(()=>{t(),r.requestAnimationFrame(()=>{r.add(MR(s,i))})}),r.dispose}function MR(s,e){var t,i;let n=_a();if(!s)return n.dispose;let r=!1;n.add(()=>{r=!0});let o=(i=(t=s.getAnimations)==null?void 0:t.call(s).filter(u=>u instanceof CSSTransition))!=null?i:[];return o.length===0?(e(),n.dispose):(Promise.allSettled(o.map(u=>u.finished)).then(()=>{r||e()}),n.dispose)}function NR(s,{inFlight:e,prepare:t}){if(e!=null&&e.current){t();return}let i=s.style.transition;s.style.transition="none",t(),s.offsetHeight,s.style.transition=i}function BR(s){var e,t;return((t=(e=s.getAnimations)==null?void 0:e.call(s))!=null?t:[]).some(i=>i instanceof CSSTransition&&i.playState!=="finished")}function cT(s,e){let t=j.useRef([]),i=li(s);j.useEffect(()=>{let n=[...t.current];for(let[r,o]of e.entries())if(t.current[r]!==o){let u=i(e,n);return t.current=e,u}},[i,...e])}let dm=j.createContext(null);dm.displayName="OpenClosedContext";var er=(s=>(s[s.Open=1]="Open",s[s.Closed=2]="Closed",s[s.Closing=4]="Closing",s[s.Opening=8]="Opening",s))(er||{});function hm(){return j.useContext(dm)}function FR({value:s,children:e}){return bt.createElement(dm.Provider,{value:s},e)}function UR({children:s}){return bt.createElement(dm.Provider,{value:null},s)}function $R(s){function e(){document.readyState!=="loading"&&(s(),document.removeEventListener("DOMContentLoaded",e))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",e),e())}let yo=[];$R(()=>{function s(e){if(!To(e.target)||e.target===document.body||yo[0]===e.target)return;let t=e.target;t=t.closest(Ip),yo.unshift(t??e.target),yo=yo.filter(i=>i!=null&&i.isConnected),yo.splice(10)}window.addEventListener("click",s,{capture:!0}),window.addEventListener("mousedown",s,{capture:!0}),window.addEventListener("focus",s,{capture:!0}),document.body.addEventListener("click",s,{capture:!0}),document.body.addEventListener("mousedown",s,{capture:!0}),document.body.addEventListener("focus",s,{capture:!0})});function dA(s){let e=li(s),t=j.useRef(!1);j.useEffect(()=>(t.current=!1,()=>{t.current=!0,um(()=>{t.current&&e()})}),[e])}let hA=j.createContext(!1);function jR(){return j.useContext(hA)}function FS(s){return bt.createElement(hA.Provider,{value:s.force},s.children)}function HR(s){let e=jR(),t=j.useContext(pA),[i,n]=j.useState(()=>{var r;if(!e&&t!==null)return(r=t.current)!=null?r:null;if(Pr.isServer)return null;let o=s?.getElementById("headlessui-portal-root");if(o)return o;if(s===null)return null;let u=s.createElement("div");return u.setAttribute("id","headlessui-portal-root"),s.body.appendChild(u)});return j.useEffect(()=>{i!==null&&(s!=null&&s.body.contains(i)||s==null||s.body.appendChild(i))},[i,s]),j.useEffect(()=>{e||t!==null&&n(t.current)},[t,n,e]),i}let fA=j.Fragment,GR=an(function(s,e){let{ownerDocument:t=null,...i}=s,n=j.useRef(null),r=$r(Hk(g=>{n.current=g}),e),o=uT(n.current),u=t??o,c=HR(u),d=j.useContext(hv),f=cm(),m=Un();return dA(()=>{var g;c&&c.childNodes.length<=0&&((g=c.parentElement)==null||g.removeChild(c))}),c?sh.createPortal(bt.createElement("div",{"data-headlessui-portal":"",ref:g=>{f.dispose(),d&&g&&f.add(d.register(g))}},m({ourProps:{ref:r},theirProps:i,slot:{},defaultTag:fA,name:"Portal"})),c):null});function VR(s,e){let t=$r(e),{enabled:i=!0,ownerDocument:n,...r}=s,o=Un();return i?bt.createElement(GR,{...r,ownerDocument:n,ref:t}):o({ourProps:{ref:t},theirProps:r,slot:{},defaultTag:fA,name:"Portal"})}let qR=j.Fragment,pA=j.createContext(null);function zR(s,e){let{target:t,...i}=s,n={ref:$r(e)},r=Un();return bt.createElement(pA.Provider,{value:t},r({ourProps:n,theirProps:i,defaultTag:qR,name:"Popover.Group"}))}let hv=j.createContext(null);function KR(){let s=j.useContext(hv),e=j.useRef([]),t=li(r=>(e.current.push(r),s&&s.register(r),()=>i(r))),i=li(r=>{let o=e.current.indexOf(r);o!==-1&&e.current.splice(o,1),s&&s.unregister(r)}),n=j.useMemo(()=>({register:t,unregister:i,portals:e}),[t,i,e]);return[e,j.useMemo(()=>function({children:r}){return bt.createElement(hv.Provider,{value:n},r)},[n])]}let YR=an(VR),mA=an(zR),WR=Object.assign(YR,{Group:mA});function XR(s,e=typeof document<"u"?document.defaultView:null,t){let i=ah(s,"escape");cA(e,"keydown",n=>{i&&(n.defaultPrevented||n.key===eA.Escape&&t(n))})}function QR(){var s;let[e]=j.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null),[t,i]=j.useState((s=e?.matches)!=null?s:!1);return nn(()=>{if(!e)return;function n(r){i(r.matches)}return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[e]),t}function ZR({defaultContainers:s=[],portals:e,mainTreeNode:t}={}){let i=li(()=>{var n,r;let o=nh(t),u=[];for(let c of s)c!==null&&(bo(c)?u.push(c):"current"in c&&bo(c.current)&&u.push(c.current));if(e!=null&&e.current)for(let c of e.current)u.push(c);for(let c of(n=o?.querySelectorAll("html > *, body > *"))!=null?n:[])c!==document.body&&c!==document.head&&bo(c)&&c.id!=="headlessui-portal-root"&&(t&&(c.contains(t)||c.contains((r=t?.getRootNode())==null?void 0:r.host))||u.some(d=>c.contains(d))||u.push(c));return u});return{resolveContainers:i,contains:li(n=>i().some(r=>r.contains(n)))}}let gA=j.createContext(null);function US({children:s,node:e}){let[t,i]=j.useState(null),n=yA(e??t);return bt.createElement(gA.Provider,{value:n},s,n===null&&bt.createElement(uv,{features:Lp.Hidden,ref:r=>{var o,u;if(r){for(let c of(u=(o=nh(r))==null?void 0:o.querySelectorAll("html > *, body > *"))!=null?u:[])if(c!==document.body&&c!==document.head&&bo(c)&&c!=null&&c.contains(r)){i(c);break}}}}))}function yA(s=null){var e;return(e=j.useContext(gA))!=null?e:s}function JR(){let s=typeof document>"u";return"useSyncExternalStore"in TS?(e=>e.useSyncExternalStore)(TS)(()=>()=>{},()=>!1,()=>!s):!1}function fm(){let s=JR(),[e,t]=j.useState(Pr.isHandoffComplete);return e&&Pr.isHandoffComplete===!1&&t(!1),j.useEffect(()=>{e!==!0&&t(!0)},[e]),j.useEffect(()=>Pr.handoff(),[]),s?!1:e}function dT(){let s=j.useRef(!1);return nn(()=>(s.current=!0,()=>{s.current=!1}),[]),s}var Dd=(s=>(s[s.Forwards=0]="Forwards",s[s.Backwards=1]="Backwards",s))(Dd||{});function eO(){let s=j.useRef(0);return uA(!0,"keydown",e=>{e.key==="Tab"&&(s.current=e.shiftKey?1:0)},!0),s}function vA(s){if(!s)return new Set;if(typeof s=="function")return new Set(s());let e=new Set;for(let t of s.current)bo(t.current)&&e.add(t.current);return e}let tO="div";var hl=(s=>(s[s.None=0]="None",s[s.InitialFocus=1]="InitialFocus",s[s.TabLock=2]="TabLock",s[s.FocusLock=4]="FocusLock",s[s.RestoreFocus=8]="RestoreFocus",s[s.AutoFocus=16]="AutoFocus",s))(hl||{});function iO(s,e){let t=j.useRef(null),i=$r(t,e),{initialFocus:n,initialFocusFallback:r,containers:o,features:u=15,...c}=s;fm()||(u=0);let d=uT(t.current);aO(u,{ownerDocument:d});let f=oO(u,{ownerDocument:d,container:t,initialFocus:n,initialFocusFallback:r});lO(u,{ownerDocument:d,container:t,containers:o,previousActiveElement:f});let m=eO(),g=li(I=>{if(!Sl(t.current))return;let w=t.current;(F=>F())(()=>{Ta(m.current,{[Dd.Forwards]:()=>{Pd(w,pa.First,{skipElements:[I.relatedTarget,r]})},[Dd.Backwards]:()=>{Pd(w,pa.Last,{skipElements:[I.relatedTarget,r]})}})})}),v=ah(!!(u&2),"focus-trap#tab-lock"),b=cm(),_=j.useRef(!1),E={ref:i,onKeyDown(I){I.key=="Tab"&&(_.current=!0,b.requestAnimationFrame(()=>{_.current=!1}))},onBlur(I){if(!(u&4))return;let w=vA(o);Sl(t.current)&&w.add(t.current);let F=I.relatedTarget;To(F)&&F.dataset.headlessuiFocusGuard!=="true"&&(TA(w,F)||(_.current?Pd(t.current,Ta(m.current,{[Dd.Forwards]:()=>pa.Next,[Dd.Backwards]:()=>pa.Previous})|pa.WrapAround,{relativeTo:I.target}):To(I.target)&&ya(I.target)))}},L=Un();return bt.createElement(bt.Fragment,null,v&&bt.createElement(uv,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:g,features:Lp.Focusable}),L({ourProps:E,theirProps:c,defaultTag:tO,name:"FocusTrap"}),v&&bt.createElement(uv,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:g,features:Lp.Focusable}))}let sO=an(iO),nO=Object.assign(sO,{features:hl});function rO(s=!0){let e=j.useRef(yo.slice());return cT(([t],[i])=>{i===!0&&t===!1&&um(()=>{e.current.splice(0)}),i===!1&&t===!0&&(e.current=yo.slice())},[s,yo,e]),li(()=>{var t;return(t=e.current.find(i=>i!=null&&i.isConnected))!=null?t:null})}function aO(s,{ownerDocument:e}){let t=!!(s&8),i=rO(t);cT(()=>{t||wk(e?.body)&&ya(i())},[t]),dA(()=>{t&&ya(i())})}function oO(s,{ownerDocument:e,container:t,initialFocus:i,initialFocusFallback:n}){let r=j.useRef(null),o=ah(!!(s&1),"focus-trap#initial-focus"),u=dT();return cT(()=>{if(s===0)return;if(!o){n!=null&&n.current&&ya(n.current);return}let c=t.current;c&&um(()=>{if(!u.current)return;let d=e?.activeElement;if(i!=null&&i.current){if(i?.current===d){r.current=d;return}}else if(c.contains(d)){r.current=d;return}if(i!=null&&i.current)ya(i.current);else{if(s&16){if(Pd(c,pa.First|pa.AutoFocus)!==dv.Error)return}else if(Pd(c,pa.First)!==dv.Error)return;if(n!=null&&n.current&&(ya(n.current),e?.activeElement===n.current))return;console.warn("There are no focusable elements inside the ")}r.current=e?.activeElement})},[n,o,s]),r}function lO(s,{ownerDocument:e,container:t,containers:i,previousActiveElement:n}){let r=dT(),o=!!(s&4);cA(e?.defaultView,"focus",u=>{if(!o||!r.current)return;let c=vA(i);Sl(t.current)&&c.add(t.current);let d=n.current;if(!d)return;let f=u.target;Sl(f)?TA(c,f)?(n.current=f,ya(f)):(u.preventDefault(),u.stopPropagation(),ya(d)):ya(n.current)},!0)}function TA(s,e){for(let t of s)if(t.contains(e))return!0;return!1}function bA(s){var e;return!!(s.enter||s.enterFrom||s.enterTo||s.leave||s.leaveFrom||s.leaveTo)||!Rd((e=s.as)!=null?e:xA)||bt.Children.count(s.children)===1}let pm=j.createContext(null);pm.displayName="TransitionContext";var uO=(s=>(s.Visible="visible",s.Hidden="hidden",s))(uO||{});function cO(){let s=j.useContext(pm);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}function dO(){let s=j.useContext(mm);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}let mm=j.createContext(null);mm.displayName="NestingContext";function gm(s){return"children"in s?gm(s.children):s.current.filter(({el:e})=>e.current!==null).filter(({state:e})=>e==="visible").length>0}function _A(s,e){let t=Dl(s),i=j.useRef([]),n=dT(),r=cm(),o=li((v,b=vo.Hidden)=>{let _=i.current.findIndex(({el:E})=>E===v);_!==-1&&(Ta(b,{[vo.Unmount](){i.current.splice(_,1)},[vo.Hidden](){i.current[_].state="hidden"}}),r.microTask(()=>{var E;!gm(i)&&n.current&&((E=t.current)==null||E.call(t))}))}),u=li(v=>{let b=i.current.find(({el:_})=>_===v);return b?b.state!=="visible"&&(b.state="visible"):i.current.push({el:v,state:"visible"}),()=>o(v,vo.Unmount)}),c=j.useRef([]),d=j.useRef(Promise.resolve()),f=j.useRef({enter:[],leave:[]}),m=li((v,b,_)=>{c.current.splice(0),e&&(e.chains.current[b]=e.chains.current[b].filter(([E])=>E!==v)),e?.chains.current[b].push([v,new Promise(E=>{c.current.push(E)})]),e?.chains.current[b].push([v,new Promise(E=>{Promise.all(f.current[b].map(([L,I])=>I)).then(()=>E())})]),b==="enter"?d.current=d.current.then(()=>e?.wait.current).then(()=>_(b)):_(b)}),g=li((v,b,_)=>{Promise.all(f.current[b].splice(0).map(([E,L])=>L)).then(()=>{var E;(E=c.current.shift())==null||E()}).then(()=>_(b))});return j.useMemo(()=>({children:i,register:u,unregister:o,onStart:m,onStop:g,wait:d,chains:f}),[u,o,i,m,g,f,d])}let xA=j.Fragment,SA=wp.RenderStrategy;function hO(s,e){var t,i;let{transition:n=!0,beforeEnter:r,afterEnter:o,beforeLeave:u,afterLeave:c,enter:d,enterFrom:f,enterTo:m,entered:g,leave:v,leaveFrom:b,leaveTo:_,...E}=s,[L,I]=j.useState(null),w=j.useRef(null),F=bA(s),U=$r(...F?[w,e,I]:e===null?[]:[e]),V=(t=E.unmount)==null||t?vo.Unmount:vo.Hidden,{show:B,appear:q,initial:k}=cO(),[R,K]=j.useState(B?"visible":"hidden"),X=dO(),{register:ee,unregister:le}=X;nn(()=>ee(w),[ee,w]),nn(()=>{if(V===vo.Hidden&&w.current){if(B&&R!=="visible"){K("visible");return}return Ta(R,{hidden:()=>le(w),visible:()=>ee(w)})}},[R,w,ee,le,B,V]);let ae=fm();nn(()=>{if(F&&ae&&R==="visible"&&w.current===null)throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[w,R,ae,F]);let Y=k&&!q,Q=q&&B&&k,te=j.useRef(!1),oe=_A(()=>{te.current||(K("hidden"),le(w))},X),de=li(Ee=>{te.current=!0;let je=Ee?"enter":"leave";oe.onStart(w,je,Ve=>{Ve==="enter"?r?.():Ve==="leave"&&u?.()})}),$=li(Ee=>{let je=Ee?"enter":"leave";te.current=!1,oe.onStop(w,je,Ve=>{Ve==="enter"?o?.():Ve==="leave"&&c?.()}),je==="leave"&&!gm(oe)&&(K("hidden"),le(w))});j.useEffect(()=>{F&&n||(de(B),$(B))},[B,F,n]);let ie=!(!n||!F||!ae||Y),[,he]=OR(ie,L,B,{start:de,end:$}),Ce=ul({ref:U,className:((i=lv(E.className,Q&&d,Q&&f,he.enter&&d,he.enter&&he.closed&&f,he.enter&&!he.closed&&m,he.leave&&v,he.leave&&!he.closed&&b,he.leave&&he.closed&&_,!he.transition&&B&&g))==null?void 0:i.trim())||void 0,...RR(he)}),be=0;R==="visible"&&(be|=er.Open),R==="hidden"&&(be|=er.Closed),B&&R==="hidden"&&(be|=er.Opening),!B&&R==="visible"&&(be|=er.Closing);let Ue=Un();return bt.createElement(mm.Provider,{value:oe},bt.createElement(FR,{value:be},Ue({ourProps:Ce,theirProps:E,defaultTag:xA,features:SA,visible:R==="visible",name:"Transition.Child"})))}function fO(s,e){let{show:t,appear:i=!1,unmount:n=!0,...r}=s,o=j.useRef(null),u=bA(s),c=$r(...u?[o,e]:e===null?[]:[e]);fm();let d=hm();if(t===void 0&&d!==null&&(t=(d&er.Open)===er.Open),t===void 0)throw new Error("A is used but it is missing a `show={true | false}` prop.");let[f,m]=j.useState(t?"visible":"hidden"),g=_A(()=>{t||m("hidden")}),[v,b]=j.useState(!0),_=j.useRef([t]);nn(()=>{v!==!1&&_.current[_.current.length-1]!==t&&(_.current.push(t),b(!1))},[_,t]);let E=j.useMemo(()=>({show:t,appear:i,initial:v}),[t,i,v]);nn(()=>{t?m("visible"):!gm(g)&&o.current!==null&&m("hidden")},[t,g]);let L={unmount:n},I=li(()=>{var U;v&&b(!1),(U=s.beforeEnter)==null||U.call(s)}),w=li(()=>{var U;v&&b(!1),(U=s.beforeLeave)==null||U.call(s)}),F=Un();return bt.createElement(mm.Provider,{value:g},bt.createElement(pm.Provider,{value:E},F({ourProps:{...L,as:j.Fragment,children:bt.createElement(EA,{ref:c,...L,...r,beforeEnter:I,beforeLeave:w})},theirProps:{},defaultTag:j.Fragment,features:SA,visible:f==="visible",name:"Transition"})))}function pO(s,e){let t=j.useContext(pm)!==null,i=hm()!==null;return bt.createElement(bt.Fragment,null,!t&&i?bt.createElement(fv,{ref:e,...s}):bt.createElement(EA,{ref:e,...s}))}let fv=an(fO),EA=an(hO),hT=an(pO),pp=Object.assign(fv,{Child:hT,Root:fv});var mO=(s=>(s[s.Open=0]="Open",s[s.Closed=1]="Closed",s))(mO||{}),gO=(s=>(s[s.SetTitleId=0]="SetTitleId",s))(gO||{});let yO={0(s,e){return s.titleId===e.id?s:{...s,titleId:e.id}}},fT=j.createContext(null);fT.displayName="DialogContext";function ym(s){let e=j.useContext(fT);if(e===null){let t=new Error(`<${s} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,ym),t}return e}function vO(s,e){return Ta(e.type,yO,s,e)}let $S=an(function(s,e){let t=j.useId(),{id:i=`headlessui-dialog-${t}`,open:n,onClose:r,initialFocus:o,role:u="dialog",autoFocus:c=!0,__demoMode:d=!1,unmount:f=!1,...m}=s,g=j.useRef(!1);u=(function(){return u==="dialog"||u==="alertdialog"?u:(g.current||(g.current=!0,console.warn(`Invalid role [${u}] passed to . Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`)),"dialog")})();let v=hm();n===void 0&&v!==null&&(n=(v&er.Open)===er.Open);let b=j.useRef(null),_=$r(b,e),E=uT(b.current),L=n?0:1,[I,w]=j.useReducer(vO,{titleId:null,descriptionId:null,panelRef:j.createRef()}),F=li(()=>r(!1)),U=li(he=>w({type:0,id:he})),V=fm()?L===0:!1,[B,q]=KR(),k={get current(){var he;return(he=I.panelRef.current)!=null?he:b.current}},R=yA(),{resolveContainers:K}=ZR({mainTreeNode:R,portals:B,defaultContainers:[k]}),X=v!==null?(v&er.Closing)===er.Closing:!1;uR(d||X?!1:V,{allowed:li(()=>{var he,Ce;return[(Ce=(he=b.current)==null?void 0:he.closest("[data-headlessui-portal]"))!=null?Ce:null]}),disallowed:li(()=>{var he;return[(he=R?.closest("body > *:not(#headlessui-portal-root)"))!=null?he:null]})});let ee=rA.get(null);nn(()=>{if(V)return ee.actions.push(i),()=>ee.actions.pop(i)},[ee,i,V]);let le=aA(ee,j.useCallback(he=>ee.selectors.isTop(he,i),[ee,i]));_R(le,K,he=>{he.preventDefault(),F()}),XR(le,E?.defaultView,he=>{he.preventDefault(),he.stopPropagation(),document.activeElement&&"blur"in document.activeElement&&typeof document.activeElement.blur=="function"&&document.activeElement.blur(),F()}),wR(d||X?!1:V,E,K),cR(V,b,F);let[ae,Y]=Gk(),Q=j.useMemo(()=>[{dialogState:L,close:F,setTitleId:U,unmount:f},I],[L,F,U,f,I]),te=rh({open:L===0}),oe={ref:_,id:i,role:u,tabIndex:-1,"aria-modal":d?void 0:L===0?!0:void 0,"aria-labelledby":I.titleId,"aria-describedby":ae,unmount:f},de=!QR(),$=hl.None;V&&!d&&($|=hl.RestoreFocus,$|=hl.TabLock,c&&($|=hl.AutoFocus),de&&($|=hl.InitialFocus));let ie=Un();return bt.createElement(UR,null,bt.createElement(FS,{force:!0},bt.createElement(WR,null,bt.createElement(fT.Provider,{value:Q},bt.createElement(mA,{target:b},bt.createElement(FS,{force:!1},bt.createElement(Y,{slot:te},bt.createElement(q,null,bt.createElement(nO,{initialFocus:o,initialFocusFallback:b,containers:K,features:$},bt.createElement(Wk,{value:F},ie({ourProps:oe,theirProps:m,slot:te,defaultTag:TO,features:bO,visible:L===0,name:"Dialog"})))))))))))}),TO="div",bO=wp.RenderStrategy|wp.Static;function _O(s,e){let{transition:t=!1,open:i,...n}=s,r=hm(),o=s.hasOwnProperty("open")||r!==null,u=s.hasOwnProperty("onClose");if(!o&&!u)throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");if(!o)throw new Error("You provided an `onClose` prop to the `Dialog`, but forgot an `open` prop.");if(!u)throw new Error("You provided an `open` prop to the `Dialog`, but forgot an `onClose` prop.");if(!r&&typeof s.open!="boolean")throw new Error(`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${s.open}`);if(typeof s.onClose!="function")throw new Error(`You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${s.onClose}`);return(i!==void 0||t)&&!n.static?bt.createElement(US,null,bt.createElement(pp,{show:i,transition:t,unmount:n.unmount},bt.createElement($S,{ref:e,...n}))):bt.createElement(US,null,bt.createElement($S,{ref:e,open:i,...n}))}let xO="div";function SO(s,e){let t=j.useId(),{id:i=`headlessui-dialog-panel-${t}`,transition:n=!1,...r}=s,[{dialogState:o,unmount:u},c]=ym("Dialog.Panel"),d=$r(e,c.panelRef),f=rh({open:o===0}),m=li(E=>{E.stopPropagation()}),g={ref:d,id:i,onClick:m},v=n?hT:j.Fragment,b=n?{unmount:u}:{},_=Un();return bt.createElement(v,{...b},_({ourProps:g,theirProps:r,slot:f,defaultTag:xO,name:"Dialog.Panel"}))}let EO="div";function AO(s,e){let{transition:t=!1,...i}=s,[{dialogState:n,unmount:r}]=ym("Dialog.Backdrop"),o=rh({open:n===0}),u={ref:e,"aria-hidden":!0},c=t?hT:j.Fragment,d=t?{unmount:r}:{},f=Un();return bt.createElement(c,{...d},f({ourProps:u,theirProps:i,slot:o,defaultTag:EO,name:"Dialog.Backdrop"}))}let CO="h2";function DO(s,e){let t=j.useId(),{id:i=`headlessui-dialog-title-${t}`,...n}=s,[{dialogState:r,setTitleId:o}]=ym("Dialog.Title"),u=$r(e);j.useEffect(()=>(o(i),()=>o(null)),[i,o]);let c=rh({open:r===0}),d={ref:u,id:i};return Un()({ourProps:d,theirProps:n,slot:c,defaultTag:CO,name:"Dialog.Title"})}let wO=an(_O),LO=an(SO);an(AO);let IO=an(DO),Nu=Object.assign(wO,{Panel:LO,Title:IO,Description:Kk});function kO({open:s,onClose:e,onApply:t,initialCookies:i}){const[n,r]=j.useState(""),[o,u]=j.useState(""),[c,d]=j.useState([]),f=j.useRef(!1);j.useEffect(()=>{s&&!f.current&&(r(""),u(""),d(i??[])),f.current=s},[s,i]);function m(){const b=n.trim(),_=o.trim();!b||!_||(d(E=>[...E.filter(I=>I.name!==b),{name:b,value:_}]),r(""),u(""))}function g(b){d(_=>_.filter(E=>E.name!==b))}function v(){t(c),e()}return O.jsxs(Nu,{open:s,onClose:e,className:"relative z-50",children:[O.jsx("div",{className:"fixed inset-0 bg-black/40","aria-hidden":"true"}),O.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:O.jsxs(Nu.Panel,{className:"w-full max-w-lg rounded-lg bg-white dark:bg-gray-800 p-6 shadow-xl dark:outline dark:-outline-offset-1 dark:outline-white/10",children:[O.jsx(Nu.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Zusätzliche Cookies"}),O.jsxs("div",{className:"mt-4 grid grid-cols-1 sm:grid-cols-3 gap-2",children:[O.jsx("input",{value:n,onChange:b=>r(b.target.value),placeholder:"Name (z. B. cf_clearance)",className:"col-span-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),O.jsx("input",{value:o,onChange:b=>u(b.target.value),placeholder:"Wert",className:"col-span-1 sm:col-span-2 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"})]}),O.jsx("div",{className:"mt-2",children:O.jsx(es,{size:"sm",variant:"secondary",onClick:m,disabled:!n.trim()||!o.trim(),children:"Hinzufügen"})}),O.jsx("div",{className:"mt-4",children:c.length===0?O.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Noch keine Cookies hinzugefügt."}):O.jsxs("table",{className:"min-w-full text-sm border divide-y dark:divide-white/10",children:[O.jsx("thead",{className:"bg-gray-50 dark:bg-gray-700/50",children:O.jsxs("tr",{children:[O.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Name"}),O.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Wert"}),O.jsx("th",{className:"px-3 py-2"})]})}),O.jsx("tbody",{className:"divide-y dark:divide-white/10",children:c.map(b=>O.jsxs("tr",{children:[O.jsx("td",{className:"px-3 py-2 font-mono",children:b.name}),O.jsx("td",{className:"px-3 py-2 truncate max-w-[240px]",children:b.value}),O.jsx("td",{className:"px-3 py-2 text-right",children:O.jsx("button",{onClick:()=>g(b.name),className:"text-xs text-red-600 hover:underline dark:text-red-400",children:"Entfernen"})})]},b.name))})]})}),O.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[O.jsx(es,{variant:"secondary",onClick:e,children:"Abbrechen"}),O.jsx(es,{variant:"primary",onClick:v,children:"Übernehmen"})]})]})})]})}function Pn({header:s,footer:e,grayBody:t=!1,grayFooter:i=!1,edgeToEdgeMobile:n=!1,well:r=!1,noBodyPadding:o=!1,className:u,bodyClassName:c,children:d}){const f=r;return O.jsxs("div",{className:Ht("overflow-hidden",n?"sm:rounded-lg":"rounded-lg",f?"bg-gray-50 dark:bg-gray-800 shadow-none":"bg-white shadow-sm dark:bg-gray-800 dark:shadow-none dark:outline dark:-outline-offset-1 dark:outline-white/10",u),children:[s&&O.jsx("div",{className:"shrink-0 px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-white/10",children:s}),O.jsx("div",{className:Ht("min-h-0",o?"p-0":"px-4 py-5 sm:p-6",t&&"bg-gray-50 dark:bg-gray-800",c),children:d}),e&&O.jsx("div",{className:Ht("shrink-0 px-4 py-4 sm:px-6",i&&"bg-gray-50 dark:bg-gray-800/50","border-t border-gray-200 dark:border-white/10"),children:e})]})}function RO({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{fillRule:"evenodd",d:"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const OO=j.forwardRef(RO);function PO({tabs:s,value:e,onChange:t,className:i,ariaLabel:n="Ansicht auswählen",variant:r="underline",hideCountUntilMd:o=!1}){if(!s?.length)return null;const u=s.find(g=>g.id===e)??s[0],c=Ht("col-start-1 row-start-1 w-full appearance-none rounded-md bg-white py-2 pr-8 pl-3 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600 dark:text-gray-100 dark:outline-white/10 dark:*:bg-gray-800 dark:focus:outline-indigo-500",r==="pillsBrand"?"dark:bg-gray-800/50":"dark:bg-white/5"),d=g=>Ht(g?"bg-indigo-100 text-indigo-600 dark:bg-indigo-500/20 dark:text-indigo-400":"bg-gray-100 text-gray-900 dark:bg-white/10 dark:text-gray-300",o?"ml-3 hidden rounded-full px-2.5 py-0.5 text-xs font-medium md:inline-block":"ml-3 rounded-full px-2.5 py-0.5 text-xs font-medium"),f=(g,v)=>v.count===void 0?null:O.jsx("span",{className:d(g),children:v.count}),m=()=>{switch(r){case"underline":case"underlineIcons":return O.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:O.jsx("nav",{"aria-label":n,className:"-mb-px flex space-x-8",children:s.map(g=>{const v=g.id===u.id,b=!!g.disabled;return O.jsxs("button",{type:"button",onClick:()=>!b&&t(g.id),disabled:b,"aria-current":v?"page":void 0,className:Ht(v?"border-indigo-500 text-indigo-600 dark:border-indigo-400 dark:text-indigo-400":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:border-white/20 dark:hover:text-gray-200",r==="underlineIcons"?"group inline-flex items-center border-b-2 px-1 py-4 text-sm font-medium":"flex items-center border-b-2 px-1 py-4 text-sm font-medium whitespace-nowrap",b&&"cursor-not-allowed opacity-50 hover:border-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[r==="underlineIcons"&&g.icon?O.jsx(g.icon,{"aria-hidden":"true",className:Ht(v?"text-indigo-500 dark:text-indigo-400":"text-gray-400 group-hover:text-gray-500 dark:text-gray-500 dark:group-hover:text-gray-400","mr-2 -ml-0.5 size-5")}):null,O.jsx("span",{children:g.label}),f(v,g)]},g.id)})})});case"pills":case"pillsGray":case"pillsBrand":{const g=r==="pills"?"bg-gray-100 text-gray-700 dark:bg-white/10 dark:text-gray-200":r==="pillsGray"?"bg-gray-200 text-gray-800 dark:bg-white/10 dark:text-white":"bg-indigo-100 text-indigo-700 dark:bg-indigo-500/20 dark:text-indigo-300",v=r==="pills"?"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200":r==="pillsGray"?"text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-white":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200";return O.jsx("nav",{"aria-label":n,className:"flex space-x-4",children:s.map(b=>{const _=b.id===u.id,E=!!b.disabled;return O.jsxs("button",{type:"button",onClick:()=>!E&&t(b.id),disabled:E,"aria-current":_?"page":void 0,className:Ht(_?g:v,"inline-flex items-center rounded-md px-3 py-2 text-sm font-medium",E&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:[O.jsx("span",{children:b.label}),b.count!==void 0?O.jsx("span",{className:Ht(_?"ml-2 bg-white/70 text-gray-900 dark:bg-white/10 dark:text-white":"ml-2 bg-gray-100 text-gray-900 dark:bg-white/10 dark:text-gray-300","rounded-full px-2 py-0.5 text-xs font-medium"),children:b.count}):null]},b.id)})})}case"fullWidthUnderline":return O.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:O.jsx("nav",{"aria-label":n,className:"-mb-px flex",children:s.map(g=>{const v=g.id===u.id,b=!!g.disabled;return O.jsx("button",{type:"button",onClick:()=>!b&&t(g.id),disabled:b,"aria-current":v?"page":void 0,className:Ht(v?"border-indigo-500 text-indigo-600 dark:border-indigo-400 dark:text-indigo-400":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:border-white/20 dark:hover:text-gray-300","flex-1 border-b-2 px-1 py-4 text-center text-sm font-medium",b&&"cursor-not-allowed opacity-50 hover:border-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:g.label},g.id)})})});case"barUnderline":return O.jsx("nav",{"aria-label":n,className:"isolate flex divide-x divide-gray-200 rounded-lg bg-white shadow-sm dark:divide-white/10 dark:bg-gray-800/50 dark:shadow-none dark:outline dark:-outline-offset-1 dark:outline-white/10",children:s.map((g,v)=>{const b=g.id===u.id,_=!!g.disabled;return O.jsxs("button",{type:"button",onClick:()=>!_&&t(g.id),disabled:_,"aria-current":b?"page":void 0,className:Ht(b?"text-gray-900 dark:text-white":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-white",v===0?"rounded-l-lg":"",v===s.length-1?"rounded-r-lg":"","group relative min-w-0 flex-1 overflow-hidden px-4 py-4 text-center text-sm font-medium hover:bg-gray-50 focus:z-10 dark:hover:bg-white/5",_&&"cursor-not-allowed opacity-50 hover:bg-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[O.jsxs("span",{className:"inline-flex items-center justify-center",children:[g.label,g.count!==void 0?O.jsx("span",{className:"ml-2 rounded-full bg-white/70 px-2 py-0.5 text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-white",children:g.count}):null]}),O.jsx("span",{"aria-hidden":"true",className:Ht(b?"bg-indigo-500 dark:bg-indigo-400":"bg-transparent","absolute inset-x-0 bottom-0 h-0.5")})]},g.id)})});case"simple":return O.jsx("nav",{className:"flex border-b border-gray-200 py-4 dark:border-white/10","aria-label":n,children:O.jsx("ul",{role:"list",className:"flex min-w-full flex-none gap-x-8 px-2 text-sm/6 font-semibold text-gray-500 dark:text-gray-400",children:s.map(g=>{const v=g.id===u.id,b=!!g.disabled;return O.jsx("li",{children:O.jsx("button",{type:"button",onClick:()=>!b&&t(g.id),disabled:b,"aria-current":v?"page":void 0,className:Ht(v?"text-indigo-600 dark:text-indigo-400":"hover:text-gray-700 dark:hover:text-white",b&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:g.label})},g.id)})})});default:return null}};return O.jsxs("div",{className:i,children:[O.jsxs("div",{className:"grid grid-cols-1 sm:hidden",children:[O.jsx("select",{value:u.id,onChange:g=>t(g.target.value),"aria-label":n,className:c,children:s.map(g=>O.jsx("option",{value:g.id,children:g.label},g.id))}),O.jsx(OO,{"aria-hidden":"true",className:"pointer-events-none col-start-1 row-start-1 mr-2 size-5 self-center justify-self-end fill-gray-500 dark:fill-gray-400"})]}),O.jsx("div",{className:"hidden sm:block",children:m()})]})}function jS({checked:s,onChange:e,id:t,name:i,disabled:n,required:r,ariaLabel:o,ariaLabelledby:u,ariaDescribedby:c,size:d="default",variant:f="simple",className:m}){const g=b=>{n||e(b.target.checked)},v=Ht("absolute inset-0 size-full appearance-none focus:outline-hidden",n&&"cursor-not-allowed");return d==="short"?O.jsxs("div",{className:Ht("group relative inline-flex h-5 w-10 shrink-0 items-center justify-center rounded-full outline-offset-2 outline-indigo-600 has-focus-visible:outline-2 dark:outline-indigo-500",n&&"opacity-60",m),children:[O.jsx("span",{className:Ht("absolute mx-auto h-4 w-9 rounded-full bg-gray-200 inset-ring inset-ring-gray-900/5 transition-colors duration-200 ease-in-out dark:bg-gray-800/50 dark:inset-ring-white/10",s&&"bg-indigo-600 dark:bg-indigo-500")}),O.jsx("span",{className:Ht("absolute left-0 size-5 rounded-full border border-gray-300 bg-white shadow-xs transition-transform duration-200 ease-in-out dark:shadow-none",s&&"translate-x-5")}),O.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:g,disabled:n,required:r,"aria-label":o,"aria-labelledby":u,"aria-describedby":c,className:v})]}):O.jsxs("div",{className:Ht("group relative inline-flex w-11 shrink-0 rounded-full bg-gray-200 p-0.5 inset-ring inset-ring-gray-900/5 outline-offset-2 outline-indigo-600 transition-colors duration-200 ease-in-out has-focus-visible:outline-2 dark:bg-white/5 dark:inset-ring-white/10 dark:outline-indigo-500",s&&"bg-indigo-600 dark:bg-indigo-500",n&&"opacity-60",m),children:[f==="icon"?O.jsxs("span",{className:Ht("relative size-5 rounded-full bg-white shadow-xs ring-1 ring-gray-900/5 transition-transform duration-200 ease-in-out",s&&"translate-x-5"),children:[O.jsx("span",{"aria-hidden":"true",className:Ht("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-in",s?"opacity-0 duration-100":"opacity-100 duration-200"),children:O.jsx("svg",{fill:"none",viewBox:"0 0 12 12",className:"size-3 text-gray-400 dark:text-gray-600",children:O.jsx("path",{d:"M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})})}),O.jsx("span",{"aria-hidden":"true",className:Ht("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-out",s?"opacity-100 duration-200":"opacity-0 duration-100"),children:O.jsx("svg",{fill:"currentColor",viewBox:"0 0 12 12",className:"size-3 text-indigo-600 dark:text-indigo-500",children:O.jsx("path",{d:"M3.707 5.293a1 1 0 00-1.414 1.414l1.414-1.414zM5 8l-.707.707a1 1 0 001.414 0L5 8zm4.707-3.293a1 1 0 00-1.414-1.414l1.414 1.414zm-7.414 2l2 2 1.414-1.414-2-2-1.414 1.414zm3.414 2l4-4-1.414-1.414-4 4 1.414 1.414z"})})})]}):O.jsx("span",{className:Ht("size-5 rounded-full bg-white shadow-xs ring-1 ring-gray-900/5 transition-transform duration-200 ease-in-out",s&&"translate-x-5")}),O.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:g,disabled:n,required:r,"aria-label":o,"aria-labelledby":u,"aria-describedby":c,className:v})]})}function Hf({label:s,description:e,labelPosition:t="left",id:i,className:n,...r}){const o=j.useId(),u=i??`sw-${o}`,c=`${u}-label`,d=`${u}-desc`;return t==="right"?O.jsxs("div",{className:Ht("flex items-center justify-between gap-3",n),children:[O.jsx(jS,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0}),O.jsxs("div",{className:"text-sm",children:[O.jsx("label",{id:c,htmlFor:u,className:"font-medium text-gray-900 dark:text-white",children:s})," ",e?O.jsx("span",{id:d,className:"text-gray-500 dark:text-gray-400",children:e}):null]})]}):O.jsxs("div",{className:Ht("flex items-center justify-between",n),children:[O.jsxs("span",{className:"flex grow flex-col",children:[O.jsx("label",{id:c,htmlFor:u,className:"text-sm/6 font-medium text-gray-900 dark:text-white",children:s}),e?O.jsx("span",{id:d,className:"text-sm text-gray-500 dark:text-gray-400",children:e}):null]}),O.jsx(jS,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0})]})}const ro={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!0,autoStartAddedDownloads:!0,useChaturbateApi:!1,blurPreviews:!1};function MO(){const[s,e]=j.useState(ro),[t,i]=j.useState(!1),[n,r]=j.useState(null),[o,u]=j.useState(null),[c,d]=j.useState(null);j.useEffect(()=>{let g=!0;return fetch("/api/settings",{cache:"no-store"}).then(async v=>{if(!v.ok)throw new Error(await v.text());return v.json()}).then(v=>{g&&e({recordDir:(v.recordDir||ro.recordDir).toString(),doneDir:(v.doneDir||ro.doneDir).toString(),ffmpegPath:String(v.ffmpegPath??ro.ffmpegPath??""),autoAddToDownloadList:v.autoAddToDownloadList??ro.autoAddToDownloadList,autoStartAddedDownloads:v.autoStartAddedDownloads??ro.autoStartAddedDownloads,useChaturbateApi:v.useChaturbateApi??ro.useChaturbateApi,blurPreviews:v.blurPreviews??ro.blurPreviews})}).catch(()=>{}),()=>{g=!1}},[]);async function f(g){d(null),u(null),r(g);try{window.focus();const v=await fetch(`/api/settings/browse?target=${g}`,{cache:"no-store"});if(v.status===204)return;if(!v.ok){const E=await v.text().catch(()=>"");throw new Error(E||`HTTP ${v.status}`)}const _=((await v.json()).path??"").trim();if(!_)return;e(E=>g==="record"?{...E,recordDir:_}:g==="done"?{...E,doneDir:_}:{...E,ffmpegPath:_})}catch(v){d(v?.message??String(v))}finally{r(null)}}async function m(){d(null),u(null);const g=s.recordDir.trim(),v=s.doneDir.trim(),b=(s.ffmpegPath??"").trim();if(!g||!v){d("Bitte Aufnahme-Ordner und Ziel-Ordner angeben.");return}const _=!!s.autoAddToDownloadList,E=_?!!s.autoStartAddedDownloads:!1,L=!!s.useChaturbateApi,I=!!s.blurPreviews;i(!0);try{const w=await fetch("/api/settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recordDir:g,doneDir:v,ffmpegPath:b,autoAddToDownloadList:_,autoStartAddedDownloads:E,useChaturbateApi:L,blurPreviews:I})});if(!w.ok){const F=await w.text().catch(()=>"");throw new Error(F||`HTTP ${w.status}`)}u("✅ Gespeichert."),window.dispatchEvent(new CustomEvent("recorder-settings-updated"))}catch(w){d(w?.message??String(w))}finally{i(!1)}}return O.jsx(Pn,{header:O.jsxs("div",{className:"flex items-center justify-between gap-4",children:[O.jsx("div",{children:O.jsx("div",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Einstellungen"})}),O.jsx(es,{variant:"primary",onClick:m,disabled:t,children:"Speichern"})]}),grayBody:!0,children:O.jsxs("div",{className:"space-y-4",children:[c&&O.jsx("div",{className:"rounded-md bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-500/10 dark:text-red-200",children:c}),o&&O.jsx("div",{className:"rounded-md bg-green-50 px-3 py-2 text-sm text-green-700 dark:bg-green-500/10 dark:text-green-200",children:o}),O.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-12 sm:items-center",children:[O.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Aufnahme-Ordner"}),O.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[O.jsx("input",{value:s.recordDir,onChange:g=>e(v=>({...v,recordDir:g.target.value})),placeholder:"records (oder absolut: C:\\records / /mnt/data/records)",className:`min-w-0 flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 - dark:bg-white/10 dark:text-white`}),O.jsx(es,{variant:"secondary",onClick:()=>f("record"),disabled:t||n!==null,children:"Durchsuchen..."})]})]}),O.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-12 sm:items-center",children:[O.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Fertige Downloads nach"}),O.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[O.jsx("input",{value:s.doneDir,onChange:g=>e(v=>({...v,doneDir:g.target.value})),placeholder:"records/done",className:`min-w-0 flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 - dark:bg-white/10 dark:text-white`}),O.jsx(es,{variant:"secondary",onClick:()=>f("done"),disabled:t||n!==null,children:"Durchsuchen..."})]})]}),O.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-12 sm:items-center",children:[O.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"ffmpeg.exe"}),O.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[O.jsx("input",{value:s.ffmpegPath??"",onChange:g=>e(v=>({...v,ffmpegPath:g.target.value})),placeholder:"Leer = automatisch (FFMPEG_PATH / ffmpeg im PATH)",className:`min-w-0 flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 - dark:bg-white/10 dark:text-white`}),O.jsx(es,{variant:"secondary",onClick:()=>f("ffmpeg"),disabled:t||n!==null,children:"Durchsuchen..."})]})]}),O.jsx("div",{className:"mt-2 border-t border-gray-200 pt-4 dark:border-white/10",children:O.jsxs("div",{className:"space-y-3",children:[O.jsx(Hf,{checked:!!s.autoAddToDownloadList,onChange:g=>e(v=>({...v,autoAddToDownloadList:g,autoStartAddedDownloads:g?v.autoStartAddedDownloads:!1})),label:"Automatisch zur Downloadliste hinzufügen",description:"Neue Links/Modelle werden automatisch in die Downloadliste übernommen."}),O.jsx(Hf,{checked:!!s.autoStartAddedDownloads,onChange:g=>e(v=>({...v,autoStartAddedDownloads:g})),disabled:!s.autoAddToDownloadList,label:"Hinzugefügte Downloads automatisch starten",description:"Wenn ein Download hinzugefügt wurde, startet er direkt (sofern möglich)."}),O.jsx(Hf,{checked:!!s.useChaturbateApi,onChange:g=>e(v=>({...v,useChaturbateApi:g})),label:"Chaturbate API",description:"Wenn aktiv, pollt das Backend alle paar Sekunden die Online-Rooms API und cached die aktuell online Models."}),O.jsx(Hf,{checked:!!s.blurPreviews,onChange:g=>e(v=>({...v,blurPreviews:g})),label:"Vorschaubilder blurren",description:"Weichzeichnet Vorschaubilder/Teaser (praktisch auf mobilen Geräten oder im öffentlichen Umfeld)."})]})})]})})}function NO({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{fillRule:"evenodd",d:"M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const BO=j.forwardRef(NO);function FO({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{fillRule:"evenodd",d:"M11.78 5.22a.75.75 0 0 1 0 1.06L8.06 10l3.72 3.72a.75.75 0 1 1-1.06 1.06l-4.25-4.25a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0Z",clipRule:"evenodd"}))}const UO=j.forwardRef(FO);function $O({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{fillRule:"evenodd",d:"M8.22 5.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06-1.06L11.94 10 8.22 6.28a.75.75 0 0 1 0-1.06Z",clipRule:"evenodd"}))}const jO=j.forwardRef($O);function Xs(...s){return s.filter(Boolean).join(" ")}function HS(s){return s==="center"?"text-center":s==="right"?"text-right":"text-left"}function HO(s){return s==="center"?"justify-center":s==="right"?"justify-end":"justify-start"}function GS(s){return s==null?{isNull:!0,kind:"string",value:""}:s instanceof Date?{isNull:!1,kind:"number",value:s.getTime()}:typeof s=="number"?{isNull:!1,kind:"number",value:s}:typeof s=="boolean"?{isNull:!1,kind:"number",value:s?1:0}:typeof s=="bigint"?{isNull:!1,kind:"number",value:Number(s)}:{isNull:!1,kind:"string",value:String(s).toLocaleLowerCase()}}function vm({columns:s,rows:e,getRowKey:t,title:i,description:n,actions:r,fullWidth:o=!1,card:u=!0,striped:c=!1,stickyHeader:d=!1,compact:f=!1,isLoading:m=!1,emptyLabel:g="Keine Daten vorhanden.",className:v,rowClassName:b,onRowClick:_,onRowContextMenu:E,sort:L,onSortChange:I,defaultSort:w=null}){const F=f?"py-2":"py-4",U=f?"py-3":"py-3.5",V=L!==void 0,[B,q]=j.useState(w),k=V?L:B,R=j.useCallback(X=>{V||q(X),I?.(X)},[V,I]),K=j.useMemo(()=>{if(!k)return e;const X=s.find(ae=>ae.key===k.key);if(!X)return e;const ee=k.direction==="asc"?1:-1,le=e.map((ae,Y)=>({r:ae,i:Y}));return le.sort((ae,Y)=>{let Q=0;if(X.sortFn)Q=X.sortFn(ae.r,Y.r);else{const te=X.sortValue?X.sortValue(ae.r):ae.r?.[X.key],oe=X.sortValue?X.sortValue(Y.r):Y.r?.[X.key],de=GS(te),$=GS(oe);de.isNull&&!$.isNull?Q=1:!de.isNull&&$.isNull?Q=-1:de.kind==="number"&&$.kind==="number"?Q=de.value<$.value?-1:de.value>$.value?1:0:Q=String(de.value).localeCompare(String($.value),void 0,{numeric:!0})}return Q===0?ae.i-Y.i:Q*ee}),le.map(ae=>ae.r)},[e,s,k]);return O.jsxs("div",{className:Xs(o?"":"px-4 sm:px-6 lg:px-8",v),children:[(i||n||r)&&O.jsxs("div",{className:"sm:flex sm:items-center",children:[O.jsxs("div",{className:"sm:flex-auto",children:[i&&O.jsx("h1",{className:"text-base font-semibold text-gray-900 dark:text-white",children:i}),n&&O.jsx("p",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:n})]}),r&&O.jsx("div",{className:"mt-4 sm:mt-0 sm:ml-16 sm:flex-none",children:r})]}),O.jsx("div",{className:Xs(i||n||r?"mt-8":""),children:O.jsx("div",{className:"flow-root",children:O.jsx("div",{className:"overflow-x-auto",children:O.jsx("div",{className:Xs("inline-block min-w-full py-2 align-middle",o?"":"sm:px-6 lg:px-8"),children:O.jsx("div",{className:Xs(u&&"overflow-hidden shadow-sm outline-1 outline-black/5 sm:rounded-lg dark:shadow-none dark:-outline-offset-1 dark:outline-white/10"),children:O.jsxs("table",{className:"relative min-w-full divide-y divide-gray-200 dark:divide-white/10",children:[O.jsx("thead",{className:Xs(u&&"bg-gray-50/90 dark:bg-gray-800/70",d&&"sticky top-0 z-10 backdrop-blur-sm shadow-sm"),children:O.jsx("tr",{children:s.map(X=>{const ee=!!k&&k.key===X.key,le=ee?k.direction:void 0,ae=X.sortable&&!X.srOnlyHeader?ee?le==="asc"?"ascending":"descending":"none":void 0,Y=()=>{if(!(!X.sortable||X.srOnlyHeader))return R(ee?le==="asc"?{key:X.key,direction:"desc"}:null:{key:X.key,direction:"asc"})};return O.jsx("th",{scope:"col","aria-sort":ae,className:Xs(U,"px-3 text-xs font-semibold tracking-wide text-gray-700 dark:text-gray-200 whitespace-nowrap",HS(X.align),X.widthClassName,X.headerClassName),children:X.srOnlyHeader?O.jsx("span",{className:"sr-only",children:X.header}):X.sortable?O.jsxs("button",{type:"button",onClick:Y,className:Xs("group inline-flex w-full items-center gap-2 select-none rounded-md px-1.5 py-1 -my-1 hover:bg-gray-100/70 dark:hover:bg-white/5",HO(X.align)),children:[O.jsx("span",{children:X.header}),O.jsx("span",{className:Xs("flex-none rounded-sm text-gray-400 dark:text-gray-500",ee?"bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-white":"invisible group-hover:visible group-focus-visible:visible"),children:O.jsx(BO,{"aria-hidden":"true",className:Xs("size-5 transition-transform",ee&&le==="asc"&&"rotate-180")})})]}):X.header},X.key)})})}),O.jsx("tbody",{className:Xs("divide-y divide-gray-200 dark:divide-white/10",u?"bg-white dark:bg-gray-800/50":"bg-white dark:bg-gray-900"),children:m?O.jsx("tr",{children:O.jsx("td",{colSpan:s.length,className:Xs(F,"px-3 text-sm text-gray-500 dark:text-gray-400"),children:"Lädt…"})}):K.length===0?O.jsx("tr",{children:O.jsx("td",{colSpan:s.length,className:Xs(F,"px-3 text-sm text-gray-500 dark:text-gray-400"),children:g})}):K.map((X,ee)=>{const le=t?t(X,ee):String(ee);return O.jsx("tr",{className:Xs(c&&"even:bg-gray-50 dark:even:bg-gray-800/50",_&&"cursor-pointer",_&&"hover:bg-gray-50 dark:hover:bg-white/5 transition-colors",b?.(X,ee)),onClick:()=>_?.(X),onContextMenu:E?ae=>{ae.preventDefault(),E(X,ae)}:void 0,children:s.map(ae=>{const Y=ae.cell?.(X,ee)??ae.accessor?.(X)??X?.[ae.key];return O.jsx("td",{className:Xs(F,"px-3 text-sm whitespace-nowrap",HS(ae.align),ae.className,ae.key===s[0]?.key?"font-medium text-gray-900 dark:text-white":"text-gray-500 dark:text-gray-400"),children:Y},ae.key)})},le)})})]})})})})})})]})}function AA({children:s,content:e}){const t=j.useRef(null),i=j.useRef(null),[n,r]=j.useState(!1),[o,u]=j.useState(null),c=j.useRef(null),d=()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)},f=()=>{d(),c.current=window.setTimeout(()=>{r(!1),c.current=null},150)},m=()=>{d(),r(!0)},g=()=>{f()},v=()=>{d(),r(!1)},b=()=>{const E=t.current,L=i.current;if(!E||!L)return;const I=8,w=8,F=E.getBoundingClientRect(),U=L.getBoundingClientRect();let V=F.bottom+I;if(V+U.height>window.innerHeight-w){const k=F.top-U.height-I;k>=w?V=k:V=Math.max(w,window.innerHeight-U.height-w)}let q=F.left;q+U.width>window.innerWidth-w&&(q=window.innerWidth-U.width-w),q=Math.max(w,q),u({left:q,top:V})};j.useLayoutEffect(()=>{if(!n)return;const E=requestAnimationFrame(()=>b());return()=>cancelAnimationFrame(E)},[n]),j.useEffect(()=>{if(!n)return;const E=()=>requestAnimationFrame(()=>b());return window.addEventListener("resize",E),window.addEventListener("scroll",E,!0),()=>{window.removeEventListener("resize",E),window.removeEventListener("scroll",E,!0)}},[n]),j.useEffect(()=>()=>d(),[]);const _=()=>typeof e=="function"?e(n,{close:v}):e;return O.jsxs(O.Fragment,{children:[O.jsx("div",{ref:t,className:"inline-flex",onMouseEnter:m,onMouseLeave:g,children:s}),n&&sh.createPortal(O.jsx("div",{ref:i,className:"fixed z-50",style:{left:o?.left??-9999,top:o?.top??-9999,visibility:o?"visible":"hidden"},onMouseEnter:m,onMouseLeave:g,children:O.jsx(Pn,{className:"shadow-lg ring-1 ring-black/10 dark:ring-white/10 max-w-[calc(100vw-16px)]",noBodyPadding:!0,children:_()})}),document.body)]})}function X0({job:s,getFileName:e,durationSeconds:t,onDuration:i,animated:n=!1,animatedMode:r="frames",animatedTrigger:o="always",autoTickMs:u=15e3,thumbStepSec:c,thumbSpread:d,thumbSamples:f,clipSeconds:m=1,variant:g="thumb",className:v,showPopover:b=!0,blur:_=!1,inlineVideo:E=!1,inlineNonce:L=0,inlineControls:I=!1,inlineLoop:w=!0}){const F=e(s.output||""),U=_?"blur-md":"",[V,B]=j.useState(!0),[q,k]=j.useState(!0),[R,K]=j.useState(!1),X=j.useRef(null),[ee,le]=j.useState(!1),[ae,Y]=j.useState(0),[Q,te]=j.useState(!1),oe=E===!0||E==="always"?"always":E==="hover"?"hover":"never",de=j.useMemo(()=>{if(!F)return"";const Fe=F.lastIndexOf(".");return Fe>0?F.slice(0,Fe):F},[F]),$=j.useMemo(()=>F?`/api/record/video?file=${encodeURIComponent(F)}`:"",[F]),ie=typeof t=="number"&&Number.isFinite(t)&&t>0,he=g==="fill"?"w-full h-full":"w-20 h-16";j.useEffect(()=>{const Fe=X.current;if(!Fe)return;const ut=new IntersectionObserver(xt=>le(!!xt[0]?.isIntersecting),{threshold:.1});return ut.observe(Fe),()=>ut.disconnect()},[]),j.useEffect(()=>{if(!n||r!=="frames"||!ee||document.hidden)return;const Fe=window.setInterval(()=>Y(ut=>ut+1),u);return()=>window.clearInterval(Fe)},[n,r,ee,u]);const Ce=j.useMemo(()=>{if(!n||r!=="frames"||!ie)return null;const Fe=t,ut=Math.max(.25,c??3);if(d){const _e=Math.max(4,Math.min(f??16,Math.floor(Fe))),$e=ae%_e,He=Math.max(.1,Fe-ut),Xe=Math.min(.25,He*.02),We=$e/_e*He+Xe;return Math.min(Fe-.05,Math.max(.05,We))}const xt=Math.max(Fe-.1,ut),Tt=ae*ut%xt;return Math.min(Fe-.05,Math.max(.05,Tt))},[n,r,ie,t,ae,c,d,f]),be=j.useMemo(()=>de?Ce==null?`/api/record/preview?id=${encodeURIComponent(de)}`:`/api/record/preview?id=${encodeURIComponent(de)}&t=${encodeURIComponent(Ce.toFixed(2))}&v=${encodeURIComponent(String(ae))}`:"",[de,Ce,ae]),Ue=Fe=>{if(K(!0),!i)return;const ut=Fe.currentTarget.duration;Number.isFinite(ut)&&ut>0&&i(s,ut)};if(!$)return O.jsx("div",{className:[he,"rounded bg-gray-100 dark:bg-white/5"].join(" ")});const Ee=oe!=="never"&&ee&&q&&(oe==="always"||oe==="hover"&&Q),je=j.useMemo(()=>{if(!n)return[];if(r!=="clips")return[];if(!ie)return[];const Fe=t,ut=Math.max(.25,m),xt=Math.max(8,Math.min(f??18,Math.floor(Fe))),Tt=Math.max(.1,Fe-ut),_e=Math.min(.25,Tt*.02),$e=[];for(let He=0;Heje.map(Fe=>Fe.toFixed(2)).join(","),[je]),tt=n&&r==="clips"&&ee&&!document.hidden&&q&&je.length>0&&!Ee&&(o==="always"||Q),lt=oe==="hover"||n&&r==="clips"&&o==="hover",Me=j.useRef(null),Je=j.useRef(0),st=j.useRef(0);j.useEffect(()=>{const Fe=Me.current;if(!Fe)return;if(!tt){Fe.pause();return}if(!je.length)return;Je.current=Je.current%je.length,st.current=je[Je.current];const ut=()=>{try{Fe.currentTime=st.current}catch{}const _e=Fe.play();_e&&typeof _e.catch=="function"&&_e.catch(()=>{})},xt=()=>ut(),Tt=()=>{if(je.length&&Fe.currentTime-st.current>=m){Je.current=(Je.current+1)%je.length,st.current=je[Je.current];try{Fe.currentTime=st.current+.01}catch{}}};return Fe.addEventListener("loadedmetadata",xt),Fe.addEventListener("timeupdate",Tt),Fe.readyState>=1&&ut(),()=>{Fe.removeEventListener("loadedmetadata",xt),Fe.removeEventListener("timeupdate",Tt),Fe.pause()}},[tt,Ve,m]);const Ct=O.jsxs("div",{ref:X,className:["rounded bg-gray-100 dark:bg-white/5 overflow-hidden relative",he,v??""].join(" "),onMouseEnter:lt?()=>te(!0):void 0,onMouseLeave:lt?()=>te(!1):void 0,onFocus:lt?()=>te(!0):void 0,onBlur:lt?()=>te(!1):void 0,children:[Ee?O.jsx("video",{src:$,className:["w-full h-full object-cover bg-black",U,I?"pointer-events-auto":"pointer-events-none"].filter(Boolean).join(" "),muted:!0,playsInline:!0,preload:"metadata",autoPlay:!0,controls:I,loop:w,poster:be||void 0,onLoadedMetadata:Ue,onError:()=>k(!1)},`inline-${de}-${L}`):tt?O.jsx("video",{ref:Me,src:$,className:["w-full h-full object-cover bg-black pointer-events-none",U].filter(Boolean).join(" "),muted:!0,playsInline:!0,preload:"metadata",poster:be||void 0,onLoadedMetadata:Ue,onError:()=>k(!1)},`teaser-${de}-${Ve}`):be&&V?O.jsx("img",{src:be,loading:"lazy",alt:F,className:["w-full h-full object-cover",U].filter(Boolean).join(" "),onError:()=>B(!1)}):O.jsx("div",{className:"w-full h-full bg-black"}),ee&&i&&!ie&&!R&&!Ee&&O.jsx("video",{src:$,preload:"metadata",muted:!0,playsInline:!0,className:"hidden",onLoadedMetadata:Ue})]});return b?O.jsx(AA,{content:Fe=>Fe&&O.jsx("div",{className:"w-[420px]",children:O.jsx("div",{className:"aspect-video",children:O.jsx("video",{src:$,className:["w-full h-full bg-black",U].filter(Boolean).join(" "),muted:!0,playsInline:!0,preload:"metadata",controls:!0,autoPlay:!0,loop:!0,onClick:ut=>ut.stopPropagation(),onMouseDown:ut=>ut.stopPropagation()})})}),children:Ct}):Ct}function GO({open:s,x:e,y:t,items:i,onClose:n,className:r}){const o=j.useRef(null),[u,c]=j.useState({left:e,top:t});return j.useLayoutEffect(()=>{if(!s)return;const d=o.current;if(!d)return;const f=8,{innerWidth:m,innerHeight:g}=window,v=d.getBoundingClientRect(),b=Math.min(Math.max(e,f),m-v.width-f),_=Math.min(Math.max(t,f),g-v.height-f);c({left:b,top:_})},[s,e,t,i.length]),j.useEffect(()=>{if(!s)return;const d=m=>m.key==="Escape"&&n(),f=()=>n();return window.addEventListener("keydown",d),window.addEventListener("scroll",f,!0),window.addEventListener("resize",f),()=>{window.removeEventListener("keydown",d),window.removeEventListener("scroll",f,!0),window.removeEventListener("resize",f)}},[s,n]),s?sh.createPortal(O.jsxs(O.Fragment,{children:[O.jsx("div",{className:"fixed inset-0 z-50",onMouseDown:n,onContextMenu:d=>{d.preventDefault(),n()}}),O.jsx("div",{ref:o,className:Ht("fixed z-50 min-w-[220px] overflow-hidden rounded-lg","bg-white dark:bg-gray-800","ring-1 ring-black/10 dark:ring-white/10 shadow-lg",r),style:{left:u.left,top:u.top},role:"menu",onMouseDown:d=>d.stopPropagation(),onContextMenu:d=>d.preventDefault(),children:O.jsx("div",{className:"py-1",children:i.map((d,f)=>O.jsx("button",{type:"button",disabled:d.disabled,onClick:()=>{d.disabled||(d.onClick(),n())},className:Ht("w-full text-left px-3 py-2 text-sm","hover:bg-black/5 dark:hover:bg-white/10","disabled:opacity-50 disabled:cursor-not-allowed",d.danger?"text-red-700 dark:text-red-300":"text-gray-900 dark:text-gray-100"),role:"menuitem",children:d.label},f))})})]}),document.body):null}function VO({job:s,modelName:e,state:t,actions:i}){const c=t.liked;return[{label:"Abspielen",onClick:()=>i.onPlay(s)},{label:"Beobachten",onClick:()=>i.onToggleWatch(s)},{label:c===!0?"Gefällt mir entfernen":"Gefällt mir",onClick:()=>i.onSetLike(s,!0)},{label:c===!1?"Gefällt mir nicht entfernen":"Gefällt mir nicht",onClick:()=>i.onSetLike(s,!1)},{label:"Als Favorit markieren",onClick:()=>i.onToggleFavorite(s)},{label:`Mehr von ${e} anzeigen`,onClick:()=>i.onMoreFromModel(e,s),disabled:!e||e==="—"},{label:"Dateipfad im Explorer öffnen",onClick:()=>i.onRevealInExplorer(s),disabled:!s.output},{label:"Zur Downloadliste hinzufügen",onClick:()=>i.onAddToDownloadList(s)},{label:"Als HOT markieren",onClick:()=>i.onToggleHot(s)},{label:"Behalten",onClick:()=>i.onToggleKeep(s)},{label:"Löschen",onClick:()=>i.onDelete(s),danger:!0,disabled:!1}]}function Q0(...s){return s.filter(Boolean).join(" ")}const qO={sm:{btn:"px-2.5 py-1.5 text-sm",icon:"size-5"},md:{btn:"px-3 py-2 text-sm",icon:"size-5"}};function zO({items:s,value:e,onChange:t,size:i="md",className:n,ariaLabel:r="Optionen"}){const o=qO[i];return O.jsx("span",{className:Q0("isolate inline-flex rounded-md shadow-xs dark:shadow-none",n),role:"group","aria-label":r,children:s.map((u,c)=>{const d=u.id===e,f=c===0,m=c===s.length-1,g=!u.label&&!!u.icon;return O.jsxs("button",{type:"button",disabled:u.disabled,onClick:()=>t(u.id),"aria-pressed":d,className:Q0("relative inline-flex items-center font-semibold focus:z-10",!f&&"-ml-px",f&&"rounded-l-md",m&&"rounded-r-md","bg-white text-gray-900 inset-ring-1 inset-ring-gray-300 hover:bg-gray-50","dark:bg-white/10 dark:text-white dark:inset-ring-gray-700 dark:hover:bg-white/20",d&&"bg-gray-50 dark:bg-white/20","disabled:opacity-50 disabled:cursor-not-allowed",g?"px-2 py-2 text-gray-400 dark:text-gray-300":o.btn),title:typeof u.label=="string"?u.label:u.srLabel,children:[g&&u.srLabel?O.jsx("span",{className:"sr-only",children:u.srLabel}):null,u.icon?O.jsx("span",{className:Q0("shrink-0",g?"":"-ml-0.5 text-gray-400 dark:text-gray-500"),children:u.icon}):null,u.label?O.jsx("span",{className:u.icon?"ml-1.5":"",children:u.label}):null]},u.id)})})}function KO({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 9V4.5M9 9H4.5M9 9 3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5 5.25 5.25"}))}const YO=j.forwardRef(KO);function WO({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15"}))}const XO=j.forwardRef(WO);function QO({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M16.5 3.75V16.5L12 14.25 7.5 16.5V3.75m9 0H18A2.25 2.25 0 0 1 20.25 6v12A2.25 2.25 0 0 1 18 20.25H6A2.25 2.25 0 0 1 3.75 18V6A2.25 2.25 0 0 1 6 3.75h1.5m9 0h-9"}))}const mp=j.forwardRef(QO);function ZO({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 12.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 18.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5Z"}))}const VS=j.forwardRef(ZO);function JO({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.362 5.214A8.252 8.252 0 0 1 12 21 8.25 8.25 0 0 1 6.038 7.047 8.287 8.287 0 0 0 9 9.601a8.983 8.983 0 0 1 3.361-6.867 8.21 8.21 0 0 0 3 2.48Z"}),j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 18a3.75 3.75 0 0 0 .495-7.468 5.99 5.99 0 0 0-1.925 3.547 5.975 5.975 0 0 1-2.133-1.001A3.75 3.75 0 0 0 12 18Z"}))}const CA=j.forwardRef(JO);function eP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z"}))}const DA=j.forwardRef(eP);function tP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 6.878V6a2.25 2.25 0 0 1 2.25-2.25h7.5A2.25 2.25 0 0 1 18 6v.878m-12 0c.235-.083.487-.128.75-.128h10.5c.263 0 .515.045.75.128m-12 0A2.25 2.25 0 0 0 4.5 9v.878m13.5-3A2.25 2.25 0 0 1 19.5 9v.878m0 0a2.246 2.246 0 0 0-.75-.128H5.25c-.263 0-.515.045-.75.128m15 0A2.25 2.25 0 0 1 21 12v6a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 18v-6c0-.98.626-1.813 1.5-2.122"}))}const iP=j.forwardRef(tP);function sP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"}))}const nP=j.forwardRef(sP);function rP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M11.48 3.499a.562.562 0 0 1 1.04 0l2.125 5.111a.563.563 0 0 0 .475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 0 0-.182.557l1.285 5.385a.562.562 0 0 1-.84.61l-4.725-2.885a.562.562 0 0 0-.586 0L6.982 20.54a.562.562 0 0 1-.84-.61l1.285-5.386a.562.562 0 0 0-.182-.557l-4.204-3.602a.562.562 0 0 1 .321-.988l5.518-.442a.563.563 0 0 0 .475-.345L11.48 3.5Z"}))}const wA=j.forwardRef(rP);function aP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.375 19.5h17.25m-17.25 0a1.125 1.125 0 0 1-1.125-1.125M3.375 19.5h7.5c.621 0 1.125-.504 1.125-1.125m-9.75 0V5.625m0 12.75v-1.5c0-.621.504-1.125 1.125-1.125m18.375 2.625V5.625m0 12.75c0 .621-.504 1.125-1.125 1.125m1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125m0 3.75h-7.5A1.125 1.125 0 0 1 12 18.375m9.75-12.75c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125m19.5 0v1.5c0 .621-.504 1.125-1.125 1.125M2.25 5.625v1.5c0 .621.504 1.125 1.125 1.125m0 0h17.25m-17.25 0h7.5c.621 0 1.125.504 1.125 1.125M3.375 8.25c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125m17.25-3.75h-7.5c-.621 0-1.125.504-1.125 1.125m8.625-1.125c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125M12 10.875v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 10.875c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125M13.125 12h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125M20.625 12c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5M12 14.625v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 14.625c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125m0 1.5v-1.5m0 0c0-.621.504-1.125 1.125-1.125m0 0h7.5"}))}const oP=j.forwardRef(aP);function lP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"}))}const Md=j.forwardRef(lP);function uP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const LA=j.forwardRef(uP);function cP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{d:"m11.645 20.91-.007-.003-.022-.012a15.247 15.247 0 0 1-.383-.218 25.18 25.18 0 0 1-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0 1 12 5.052 5.5 5.5 0 0 1 16.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 0 1-4.244 3.17 15.247 15.247 0 0 1-.383.219l-.022.012-.007.004-.003.001a.752.752 0 0 1-.704 0l-.003-.001Z"}))}const IA=j.forwardRef(cP);function dP({title:s,titleId:e,...t},i){return j.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:i,"aria-labelledby":e},t),s?j.createElement("title",{id:e},s):null,j.createElement("path",{fillRule:"evenodd",d:"M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.006 5.404.434c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.434 2.082-5.005Z",clipRule:"evenodd"}))}const kA=j.forwardRef(dP);function Gf(...s){return s.filter(Boolean).join(" ")}const hP=j.forwardRef(function({children:e,enabled:t=!0,disabled:i=!1,onTap:n,onSwipeLeft:r,onSwipeRight:o,className:u,leftAction:c={label:O.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[O.jsx(mp,{className:"h-6 w-6","aria-hidden":"true"}),O.jsx("span",{children:"Behalten"})]}),className:"bg-emerald-500/20 text-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-300"},rightAction:d={label:O.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[O.jsx(Md,{className:"h-6 w-6","aria-hidden":"true"}),O.jsx("span",{children:"Löschen"})]}),className:"bg-red-500/20 text-red-800 dark:bg-red-500/15 dark:text-red-300"},thresholdPx:f=120,thresholdRatio:m=.35,ignoreFromBottomPx:g=72,ignoreSelector:v="[data-swipe-ignore]",snapMs:b=180,commitMs:_=180},E){const L=j.useRef(null),I=j.useRef({id:null,x:0,y:0,dragging:!1,captured:!1}),[w,F]=j.useState(0),[U,V]=j.useState(null),[B,q]=j.useState(0),k=j.useCallback(()=>{q(b),F(0),V(null),window.setTimeout(()=>q(0),b)},[b]),R=j.useCallback(async(K,X)=>{const le=L.current?.offsetWidth||360;q(_),V(K==="right"?"right":"left"),F(K==="right"?le+40:-(le+40));let ae=!0;if(X)try{ae=K==="right"?await o():await r()}catch{ae=!1}return ae===!1?(q(b),V(null),F(0),window.setTimeout(()=>q(0),b),!1):!0},[_,r,o,b]);return j.useImperativeHandle(E,()=>({swipeLeft:K=>R("left",K?.runAction??!0),swipeRight:K=>R("right",K?.runAction??!0),reset:()=>k()}),[R,k]),O.jsxs("div",{className:Gf("relative overflow-hidden rounded-lg",u),children:[O.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-lg",children:[O.jsx("div",{className:Gf("absolute inset-0 transition-opacity duration-200 ease-out",w===0?"opacity-0":"opacity-100",w>0?c.className:d.className)}),O.jsx("div",{className:Gf("absolute inset-0 flex items-center transition-all duration-200 ease-out"),style:{transform:`translateX(${Math.max(-24,Math.min(24,w/8))}px)`,opacity:w===0?0:1,justifyContent:w>0?"flex-start":"flex-end",paddingLeft:w>0?16:0,paddingRight:w>0?0:16},children:w>0?c.label:d.label})]}),O.jsx("div",{ref:L,className:"relative",style:{transform:`translateX(${w}px)`,transition:B?`transform ${B}ms ease`:void 0,touchAction:"pan-y"},onPointerDown:K=>{if(!t||i)return;const X=K.target;if(v&&X?.closest?.(v))return;const le=K.currentTarget.getBoundingClientRect().bottom-K.clientY;g&&le<=g||(I.current={id:K.pointerId,x:K.clientX,y:K.clientY,dragging:!1,captured:!1})},onPointerMove:K=>{if(!t||i||I.current.id!==K.pointerId)return;const X=K.clientX-I.current.x,ee=K.clientY-I.current.y;if(!I.current.dragging){if(Math.abs(ee)>Math.abs(X)&&Math.abs(ee)>8){I.current.id=null;return}if(Math.abs(X)<12)return;I.current.dragging=!0;try{K.currentTarget.setPointerCapture(K.pointerId),I.current.captured=!0}catch{I.current.captured=!1}}q(0),F(X);const ae=L.current?.offsetWidth||360,Y=Math.min(f,ae*m);V(X>Y?"right":X<-Y?"left":null)},onPointerUp:K=>{if(!t||i||I.current.id!==K.pointerId)return;const ee=L.current?.offsetWidth||360,le=Math.min(f,ee*m),ae=I.current.dragging,Y=I.current.captured;if(I.current.id=null,I.current.dragging=!1,I.current.captured=!1,Y)try{K.currentTarget.releasePointerCapture(K.pointerId)}catch{}if(!ae){k(),n?.();return}w>le?R("right",!0):w<-le?R("left",!0):k()},onPointerCancel:K=>{if(!(!t||i)){if(I.current.captured&&I.current.id!=null)try{K.currentTarget.releasePointerCapture(I.current.id)}catch{}I.current={id:null,x:0,y:0,dragging:!1,captured:!1},k()}},children:O.jsxs("div",{className:"relative",children:[O.jsx("div",{className:"relative z-10",children:e}),O.jsx("div",{className:Gf("absolute inset-0 z-20 pointer-events-none transition-opacity duration-150 rounded-lg",U==="right"&&"bg-emerald-500/20 opacity-100",U==="left"&&"bg-red-500/20 opacity-100",U===null&&"opacity-0")})]})})]})}),pv=s=>(s||"").replaceAll("\\","/").trim(),Zs=s=>{const t=pv(s).split("/");return t[t.length-1]||""},os=s=>Zs(s.output||"")||s.id;function Z0(...s){return s.filter(Boolean).join(" ")}function qS(s){if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`}function J0(s){if(typeof s!="number"||!Number.isFinite(s)||s<=0)return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=100?0:t>=10?1:2;return`${t.toFixed(n)} ${e[i]}`}function fP(s){const[e,t]=j.useState(!1);return j.useEffect(()=>{const i=window.matchMedia(s),n=()=>t(i.matches);return n(),i.addEventListener?i.addEventListener("change",n):i.addListener(n),()=>{i.removeEventListener?i.removeEventListener("change",n):i.removeListener(n)}},[s]),e}const yd=s=>{const e=(s??"").match(/\bHTTP\s+(\d{3})\b/i);return e?`HTTP ${e[1]}`:null},wu=s=>s.startsWith("HOT ")?s.slice(4):s,sl=s=>{const e=Zs(s||""),t=wu(e);if(!t)return"—";const i=t.replace(/\.[^.]+$/,""),n=i.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(n?.[1])return n[1];const r=i.lastIndexOf("_");return r>0?i.slice(0,r):i},zS=s=>(s||"").trim().toLowerCase(),vd=s=>{const e=s,t=e.sizeBytes??e.fileSizeBytes??e.bytes??e.size??null;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null};function pP({jobs:s,doneJobs:e,blurPreviews:t,onOpenPlayer:i,onDeleteJob:n,onToggleHot:r,onToggleFavorite:o,onToggleLike:u}){const[d,f]=j.useState(50),[m,g]=j.useState(null),v=j.useRef(new Map),[b,_]=j.useState(null),[E,L]=j.useState(()=>new Set),[I,w]=j.useState(()=>new Set),[F,U]=j.useState(null),V="finishedDownloads_view",B="finishedDownloads_sort",[q,k]=j.useState("completed_desc");j.useEffect(()=>{try{const ce=window.localStorage.getItem(B);ce&&k(ce)}catch{}},[]),j.useEffect(()=>{try{window.localStorage.setItem(B,q)}catch{}},[q]);const[R,K]=j.useState("table"),X=j.useRef(new Map),[ee,le]=j.useState({}),ae=j.useCallback(async()=>{try{const ce=await fetch("/api/models/list",{cache:"no-store"});if(!ce.ok)return;const ye=await ce.json(),Ae={};for(const ze of Array.isArray(ye)?ye:[]){const ht=zS(String(ze?.modelKey??""));if(!ht)continue;const bi=Ae[ht];if(!bi){Ae[ht]=ze;continue}const Wi=H=>(H.favorite?2:0)+(H.liked===!0?1:0);Wi(ze)>Wi(bi)&&(Ae[ht]=ze)}le(Ae)}catch{}},[]);j.useEffect(()=>{ae()},[ae]),j.useEffect(()=>{const ce=()=>{ae()};return window.addEventListener("models-changed",ce),()=>window.removeEventListener("models-changed",ce)},[ae]),j.useEffect(()=>{try{const ce=localStorage.getItem(V);K(ce==="table"||ce==="cards"||ce==="gallery"?ce:window.matchMedia("(max-width: 639px)").matches?"cards":"table")}catch{K("table")}},[]),j.useEffect(()=>{try{localStorage.setItem(V,R)}catch{}},[R]);const[Y,Q]=j.useState({}),[te,oe]=j.useState(null),de=j.useCallback(ce=>{const Ae=document.getElementById(ce)?.querySelector("video");if(!Ae)return!1;Ae.muted=!0,Ae.playsInline=!0,Ae.setAttribute("playsinline","true");const ze=Ae.play?.();return ze&&typeof ze.catch=="function"&&ze.catch(()=>{}),!0},[]),$=j.useCallback(ce=>{oe(ye=>ye?.key===ce?{key:ce,nonce:ye.nonce+1}:{key:ce,nonce:1})},[]),ie=j.useCallback(ce=>{oe(null),i(ce)},[i]),he=(ce,ye)=>{ye.preventDefault(),ye.stopPropagation(),g({x:ye.clientX,y:ye.clientY,job:ce})},Ce=(ce,ye,Ae)=>{g({x:ye,y:Ae,job:ce})},be=j.useCallback((ce,ye)=>{w(Ae=>{const ze=new Set(Ae);return ye?ze.add(ce):ze.delete(ce),ze})},[]),Ue=j.useCallback(ce=>{L(ye=>{const Ae=new Set(ye);return Ae.add(ce),Ae})},[]),[Ee,je]=j.useState(()=>new Set),Ve=j.useCallback((ce,ye)=>{je(Ae=>{const ze=new Set(Ae);return ye?ze.add(ce):ze.delete(ce),ze})},[]),[tt,lt]=j.useState(()=>new Set),Me=j.useCallback((ce,ye)=>{lt(Ae=>{const ze=new Set(Ae);return ye?ze.add(ce):ze.delete(ce),ze})},[]),Je=j.useCallback(ce=>{Me(ce,!0),window.setTimeout(()=>{Ue(ce),Me(ce,!1)},320)},[Ue,Me]),st=j.useCallback(async(ce,ye)=>{window.dispatchEvent(new CustomEvent("player:release",{detail:{file:ce}})),ye?.close&&window.dispatchEvent(new CustomEvent("player:close",{detail:{file:ce}})),await new Promise(Ae=>window.setTimeout(Ae,250))},[]),Ct=j.useCallback(async ce=>{const ye=Zs(ce.output||""),Ae=os(ce);if(!ye)return window.alert("Kein Dateiname gefunden – kann nicht löschen."),!1;if(I.has(Ae))return!1;be(Ae,!0);try{if(await st(ye,{close:!0}),n)return await n(ce),Je(Ae),!0;const ze=await fetch(`/api/record/delete?file=${encodeURIComponent(ye)}`,{method:"POST"});if(!ze.ok){const ht=await ze.text().catch(()=>"");throw new Error(ht||`HTTP ${ze.status}`)}return Je(Ae),!0}catch(ze){return window.alert(`Löschen fehlgeschlagen: ${String(ze?.message||ze)}`),!1}finally{be(Ae,!1)}},[I,be,st,n,Je]),Fe=j.useCallback(async ce=>{const ye=Zs(ce.output||""),Ae=os(ce);if(!ye)return window.alert("Kein Dateiname gefunden – kann nicht behalten."),!1;if(Ee.has(Ae)||I.has(Ae))return!1;Ve(Ae,!0);try{await st(ye,{close:!0});const ze=await fetch(`/api/record/keep?file=${encodeURIComponent(ye)}`,{method:"POST"});if(!ze.ok){const ht=await ze.text().catch(()=>"");throw new Error(ht||`HTTP ${ze.status}`)}return Je(Ae),!0}catch(ze){return window.alert(`Behalten fehlgeschlagen: ${String(ze?.message||ze)}`),!1}finally{Ve(Ae,!1)}},[Ee,I,Ve,st,Je]),ut=j.useMemo(()=>{if(!m)return[];const ce=m.job,ye=sl(ce.output);return VO({job:ce,modelName:ye,state:{liked:null},actions:{onPlay:i,onToggleWatch:Ae=>console.log("toggle watch",Ae.id),onSetLike:(Ae,ze)=>console.log("set like",Ae.id,ze),onToggleFavorite:Ae=>console.log("toggle favorite",Ae.id),onMoreFromModel:Ae=>console.log("more from",Ae),onRevealInExplorer:Ae=>console.log("reveal in explorer",Ae.output),onAddToDownloadList:Ae=>console.log("add to download list",Ae.id),onToggleHot:Ae=>console.log("toggle hot",Ae.id),onToggleKeep:Ae=>console.log("toggle keep",Ae.id),onDelete:Ae=>{g(null),Ct(Ae)}}})},[m,Ct,i]),xt=j.useCallback(ce=>{const ye=Date.parse(String(ce.startedAt||"")),Ae=Date.parse(String(ce.endedAt||""));if(Number.isFinite(ye)&&Number.isFinite(Ae)&&Ae>ye)return(Ae-ye)/1e3;const ze=ce?.durationSeconds;return typeof ze=="number"&&ze>0?ze:Number.POSITIVE_INFINITY},[]),Tt=j.useMemo(()=>{const ce=new Map;for(const Ae of e)ce.set(os(Ae),Ae);for(const Ae of s){const ze=os(Ae);ce.has(ze)&&ce.set(ze,{...ce.get(ze),...Ae})}const ye=Array.from(ce.values()).filter(Ae=>E.has(os(Ae))?!1:Ae.status==="finished"||Ae.status==="failed"||Ae.status==="stopped");return ye.sort((Ae,ze)=>pv(ze.endedAt||"").localeCompare(pv(Ae.endedAt||""))),ye},[s,e,E]),_e=ce=>ce.endedAt?new Date(ce.endedAt).getTime():0,$e=ce=>sl(ce.output||"").toLowerCase(),He=ce=>{const ye=Zs(ce.output||"").toLowerCase();return wu(ye)},Xe=ce=>{const ye=os(ce),Ae=typeof ce.durationSeconds=="number"&&ce.durationSeconds>0?ce.durationSeconds:Y[ye];return typeof Ae=="number"&&Number.isFinite(Ae)&&Ae>0?Ae:NaN},We=ce=>{const ye=vd(ce);return typeof ye=="number"?ye:NaN},pt=(ce,ye)=>ce.localeCompare(ye,void 0,{numeric:!0,sensitivity:"base"}),mt=(ce,ye)=>ce-ye,jt=(ce,ye,Ae)=>{const ze=Number.isFinite(ce),ht=Number.isFinite(ye);return!ze&&!ht?0:ze?ht?Ae*mt(ce,ye):-1:1},fi=j.useMemo(()=>{const ce=[...Tt];return ce.sort((ye,Ae)=>{switch(q){case"completed_asc":return mt(_e(ye),_e(Ae))||pt(os(ye),os(Ae));case"completed_desc":return mt(_e(Ae),_e(ye))||pt(os(ye),os(Ae));case"model_asc":return pt($e(ye),$e(Ae))||mt(_e(Ae),_e(ye));case"model_desc":return pt($e(Ae),$e(ye))||mt(_e(Ae),_e(ye));case"file_asc":return pt(He(ye),He(Ae))||mt(_e(Ae),_e(ye));case"file_desc":return pt(He(Ae),He(ye))||mt(_e(Ae),_e(ye));case"duration_asc":return jt(Xe(ye),Xe(Ae),1)||mt(_e(Ae),_e(ye));case"duration_desc":return jt(Xe(ye),Xe(Ae),-1)||mt(_e(Ae),_e(ye));case"size_asc":return jt(We(ye),We(Ae),1)||mt(_e(Ae),_e(ye));case"size_desc":return jt(We(ye),We(Ae),-1)||mt(_e(Ae),_e(ye));default:return mt(_e(Ae),_e(ye))}}),ce},[Tt,q,Y]);j.useEffect(()=>{f(50)},[Tt.length]),j.useEffect(()=>{const ce=ye=>{const Ae=ye.detail;if(!Ae?.file)return;const ze=Ae.file;Ae.phase==="start"?(be(ze,!0),R==="cards"&&X.current.get(ze)?.swipeLeft({runAction:!1})):Ae.phase==="success"?(be(ze,!1),R==="cards"?window.setTimeout(()=>Ue(ze),320):Je(ze)):Ae.phase==="error"&&(be(ze,!1),R==="cards"&&X.current.get(ze)?.reset())};return window.addEventListener("finished-downloads:delete",ce),()=>window.removeEventListener("finished-downloads:delete",ce)},[Je,be,Ue,R]);const Yi=(R==="table"?Tt:fi).filter(ce=>!E.has(os(ce))).slice(0,d);j.useEffect(()=>{if(!(R==="cards"||R==="gallery")){_(null);return}if(R==="cards"&&te?.key){_(te.key);return}let ye=0;const Ae=()=>{ye||(ye=requestAnimationFrame(()=>{ye=0;const ze=window.innerWidth/2,ht=window.innerHeight/2;let bi=null,Wi=Number.POSITIVE_INFINITY;for(const[H,G]of v.current){const re=G.getBoundingClientRect();if(re.bottom<=0||re.top>=window.innerHeight)continue;const we=re.left+re.width/2,Ge=re.top+re.height/2,Ye=Math.hypot(we-ze,Ge-ht);YeH===bi?H:bi)}))};return Ae(),window.addEventListener("scroll",Ae,{passive:!0}),window.addEventListener("resize",Ae),()=>{ye&&cancelAnimationFrame(ye),window.removeEventListener("scroll",Ae),window.removeEventListener("resize",Ae)}},[R,Yi.length,te?.key]);const ts=ce=>{const ye=Date.parse(String(ce.startedAt||"")),Ae=Date.parse(String(ce.endedAt||""));if(Number.isFinite(ye)&&Number.isFinite(Ae)&&Ae>ye)return qS(Ae-ye);const ze=ce?.durationSeconds;return typeof ze=="number"&&Number.isFinite(ze)&&ze>0?qS(ze*1e3):"—"},$t=j.useCallback(ce=>ye=>{ye?v.current.set(ce,ye):v.current.delete(ce)},[]),Ls=j.useCallback((ce,ye)=>{if(!Number.isFinite(ye)||ye<=0)return;const Ae=os(ce);Q(ze=>{const ht=ze[Ae];return typeof ht=="number"&&Math.abs(ht-ye)<.5?ze:{...ze,[Ae]:ye}})},[]),Ti=[{key:"preview",header:"Vorschau",srOnlyHeader:!0,widthClassName:"w-[140px]",cell:ce=>{const ye=os(ce);return O.jsx("div",{className:"py-1",onClick:Ae=>Ae.stopPropagation(),onMouseDown:Ae=>Ae.stopPropagation(),onContextMenu:Ae=>{Ae.preventDefault(),Ae.stopPropagation(),he(ce,Ae)},children:O.jsx(X0,{job:ce,getFileName:Zs,durationSeconds:Y[ye],onDuration:Ls,className:"w-28 h-16 rounded-md ring-1 ring-black/5 dark:ring-white/10",showPopover:!1,blur:t})})}},{key:"video",header:"Video",sortable:!0,sortValue:ce=>{const ye=Zs(ce.output||""),Ae=ye.startsWith("HOT "),ze=sl(ce.output),ht=wu(ye);return`${ze} ${Ae?"HOT":""} ${ht}`.trim()},cell:ce=>{const ye=Zs(ce.output||""),Ae=ye.startsWith("HOT "),ze=sl(ce.output),ht=wu(ye);return O.jsxs("div",{className:"min-w-0",children:[O.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[O.jsx("div",{className:"truncate font-medium text-gray-900 dark:text-white",title:ze,children:ze}),Ae?O.jsx("span",{className:"shrink-0 rounded-md bg-amber-500/15 px-1.5 py-0.5 text-[11px] font-semibold text-amber-800 dark:text-amber-300",children:"HOT"}):null]}),O.jsx("div",{className:"truncate text-xs text-gray-500 dark:text-gray-400",title:ht,children:ht||"—"})]})}},{key:"status",header:"Status",sortable:!0,sortValue:ce=>ce.status==="finished"?0:ce.status==="stopped"?1:ce.status==="failed"?2:9,cell:ce=>{const ye="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold ring-1 ring-inset";if(ce.status==="failed"){const Ae=yd(ce.error),ze=Ae?`failed (${Ae})`:"failed";return O.jsx("span",{className:`${ye} bg-red-50 text-red-700 ring-red-200 dark:bg-red-500/10 dark:text-red-300 dark:ring-red-500/30`,title:ce.error||"",children:ze})}return ce.status==="finished"?O.jsx("span",{className:`${ye} bg-emerald-50 text-emerald-800 ring-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-300 dark:ring-emerald-500/30`,children:"finished"}):ce.status==="stopped"?O.jsx("span",{className:`${ye} bg-amber-50 text-amber-800 ring-amber-200 dark:bg-amber-500/10 dark:text-amber-300 dark:ring-amber-500/30`,children:"stopped"}):O.jsx("span",{className:`${ye} bg-gray-50 text-gray-700 ring-gray-200 dark:bg-white/5 dark:text-gray-300 dark:ring-white/10`,children:ce.status})}},{key:"runtime",header:"Dauer",align:"right",sortable:!0,sortValue:ce=>xt(ce),cell:ce=>O.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:ts(ce)})},{key:"size",header:"Größe",align:"right",sortable:!0,sortValue:ce=>{const ye=vd(ce);return typeof ye=="number"?ye:Number.NEGATIVE_INFINITY},cell:ce=>O.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:J0(vd(ce))})},{key:"actions",header:"Aktionen",align:"right",srOnlyHeader:!0,cell:ce=>{const ye=os(ce),Ae=I.has(ye)||Ee.has(ye),ze="inline-flex items-center justify-center rounded-md p-1.5 hover:bg-gray-100/70 dark:hover:bg-white/5 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500";return O.jsxs("div",{className:"flex items-center justify-end gap-1",children:[O.jsx("button",{type:"button",className:ze,title:"Behalten (nach keep verschieben)","aria-label":"Behalten",disabled:Ae,onClick:ht=>{ht.preventDefault(),ht.stopPropagation(),Fe(ce)},children:O.jsx(mp,{className:"size-5 text-emerald-600 dark:text-emerald-300"})}),O.jsx("button",{type:"button",className:ze,title:"Löschen","aria-label":"Löschen",disabled:Ae,onClick:ht=>{ht.preventDefault(),ht.stopPropagation(),Ct(ce)},children:O.jsx(Md,{className:"size-5 text-red-600 dark:text-red-300"})}),O.jsx("button",{type:"button",className:ze,title:"Mehr Aktionen","aria-label":"Mehr Aktionen",onClick:ht=>{ht.preventDefault(),ht.stopPropagation();const bi=ht.currentTarget.getBoundingClientRect();Ce(ce,bi.left,bi.bottom+6)},children:O.jsx(VS,{className:"size-5 text-gray-500 dark:text-gray-300"})})]})}}],Ri=fP("(max-width: 639px)");return j.useEffect(()=>{Ri||(X.current=new Map)},[Ri]),Tt.length===0?O.jsx(Pn,{grayBody:!0,children:O.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine abgeschlossenen Downloads im Zielordner vorhanden."})}):O.jsxs(O.Fragment,{children:[O.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[O.jsx("div",{className:"sm:hidden min-w-0",children:O.jsxs("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:["Abgeschlossene Downloads ",O.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",Tt.length,")"]})]})}),O.jsx("div",{className:"shrink-0",children:O.jsx(zO,{value:R,onChange:ce=>K(ce),size:"sm",ariaLabel:"Ansicht",items:[{id:"table",icon:O.jsx(oP,{className:"size-5"}),label:O.jsx("span",{className:"hidden sm:inline",children:"Tabelle"}),srLabel:"Tabelle"},{id:"cards",icon:O.jsx(iP,{className:"size-5"}),label:O.jsx("span",{className:"hidden sm:inline",children:"Cards"}),srLabel:"Cards"},{id:"gallery",icon:O.jsx(nP,{className:"size-5"}),label:O.jsx("span",{className:"hidden sm:inline",children:"Galerie"}),srLabel:"Galerie"}]})})]}),R!=="table"&&O.jsxs("div",{className:"ml-2",children:[O.jsx("label",{className:"sr-only",htmlFor:"finished-sort",children:"Sortierung"}),O.jsxs("select",{id:"finished-sort",value:q,onChange:ce=>k(ce.target.value),className:`h-9 rounded-md border border-gray-200 bg-white px-2 text-sm text-gray-900 shadow-sm - dark:border-white/10 dark:bg-white/5 dark:text-white`,children:[O.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),O.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),O.jsx("option",{value:"model_asc",children:"Modelname A→Z"}),O.jsx("option",{value:"model_desc",children:"Modelname Z→A"}),O.jsx("option",{value:"file_asc",children:"Dateiname A→Z"}),O.jsx("option",{value:"file_desc",children:"Dateiname Z→A"}),O.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),O.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),O.jsx("option",{value:"size_desc",children:"Größe ↓"}),O.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}),R==="cards"&&O.jsx("div",{className:"space-y-3",children:Yi.map(ce=>{const ye=os(ce),Ae=te?.key===ye,ze=Ae?te?.nonce??0:0,ht=I.has(ye)||Ee.has(ye)||tt.has(ye),bi=sl(ce.output),Wi=Zs(ce.output||""),H=ts(ce),G=J0(vd(ce)),re=ce.status==="failed"?O.jsxs("span",{className:"text-red-700 dark:text-red-300",title:ce.error||"",children:["failed",yd(ce.error)?` (${yd(ce.error)})`:""]}):O.jsx("span",{className:"font-medium",children:ce.status}),we=`inline-prev-${encodeURIComponent(ye)}`,Ge=O.jsx("div",{role:"button",tabIndex:0,className:["transition-all duration-300 ease-in-out",ht&&"pointer-events-none",I.has(ye)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30 animate-pulse",Ee.has(ye)&&"ring-1 ring-emerald-300 bg-emerald-50/60 dark:bg-emerald-500/10 dark:ring-emerald-500/30 animate-pulse",tt.has(ye)&&"opacity-0 translate-y-2 scale-[0.98]"].filter(Boolean).join(" "),onClick:Ri?void 0:()=>ie(ce),onKeyDown:Ye=>{(Ye.key==="Enter"||Ye.key===" ")&&i(ce)},onContextMenu:Ye=>he(ce,Ye),children:O.jsxs(Pn,{noBodyPadding:!0,className:"overflow-hidden",children:[O.jsxs("div",{id:we,ref:$t(ye),className:"relative aspect-video bg-black/5 dark:bg-white/5",onClick:Ye=>{Ye.preventDefault(),Ye.stopPropagation(),!Ri&&$(ye)},children:[O.jsx(X0,{job:ce,getFileName:Zs,durationSeconds:Y[ye],onDuration:Ls,className:"w-full h-full",showPopover:!1,blur:t,animated:b===ye&&!Ae,animatedMode:"clips",animatedTrigger:"always",clipSeconds:1,thumbSamples:18,inlineVideo:Ae?"always":!1,inlineNonce:ze,inlineControls:Ae,inlineLoop:!1}),O.jsx("div",{className:["pointer-events-none absolute inset-x-0 bottom-0 h-20 bg-gradient-to-t from-black/70 to-transparent","transition-opacity duration-150",Ae?"opacity-0":"opacity-100"].join(" ")}),O.jsxs("div",{className:["pointer-events-none absolute inset-x-3 bottom-3 flex items-end justify-between gap-3","transition-opacity duration-150",Ae?"opacity-0":"opacity-100"].join(" "),children:[O.jsxs("div",{className:"min-w-0",children:[O.jsx("div",{className:"truncate text-sm font-semibold text-white",children:bi}),O.jsx("div",{className:"truncate text-[11px] text-white/80",children:wu(Wi)||"—"})]}),O.jsx("div",{className:"shrink-0 flex items-center gap-2",children:Wi.startsWith("HOT ")?O.jsx("span",{className:"rounded-md bg-amber-500/25 px-2 py-1 text-[11px] font-semibold text-white",children:"HOT"}):null})]}),!Ri&&te?.key===ye&&O.jsx("button",{type:"button",className:"absolute left-2 top-2 z-10 rounded-md bg-black/40 px-2 py-1 text-xs font-semibold text-white backdrop-blur hover:bg-black/60",onClick:Ye=>{Ye.preventDefault(),Ye.stopPropagation(),oe(wt=>({key:ye,nonce:wt?.key===ye?wt.nonce+1:1}))},title:"Von vorne starten","aria-label":"Von vorne starten",children:"↻"}),O.jsx("div",{className:"absolute right-2 top-2 flex items-center gap-2",children:(()=>{const Ye="inline-flex items-center justify-center rounded-md bg-black/40 p-2 text-white backdrop-blur hover:bg-black/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500",wt=Zs(ce.output||""),Ci=wt.startsWith("HOT "),is=sl(ce.output),ji=ee[zS(is)],Oi=!!ji?.favorite,Pi=ji?.liked===!0;return O.jsxs(O.Fragment,{children:[!Ri&&O.jsxs(O.Fragment,{children:[O.jsx("button",{type:"button",className:Ye,title:"Behalten (nach keep verschieben)","aria-label":"Behalten",disabled:ht,onPointerDown:rt=>rt.stopPropagation(),onClick:rt=>{rt.preventDefault(),rt.stopPropagation(),Fe(ce)},children:O.jsx(mp,{className:"size-5 text-emerald-300"})}),O.jsx("button",{type:"button",className:Ye,title:"Löschen","aria-label":"Löschen",disabled:ht,onPointerDown:rt=>rt.stopPropagation(),onClick:rt=>{rt.preventDefault(),rt.stopPropagation(),Ct(ce)},children:O.jsx(Md,{className:"size-5 text-red-300"})})]}),O.jsx("button",{type:"button",className:Ye,title:Ci?"HOT entfernen":"Als HOT markieren","aria-label":Ci?"HOT entfernen":"Als HOT markieren",disabled:ht||!r,onPointerDown:rt=>rt.stopPropagation(),onClick:async rt=>{rt.preventDefault(),rt.stopPropagation(),st(wt,{close:!0}),await new Promise(hs=>setTimeout(hs,150)),await r?.(ce)},children:O.jsx(CA,{className:Z0("size-5",Ci?"text-amber-300":"text-white/90")})}),O.jsx("button",{type:"button",className:Ye,title:Oi?"Favorit entfernen":"Als Favorit markieren","aria-label":Oi?"Favorit entfernen":"Als Favorit markieren",disabled:ht||!o,onPointerDown:rt=>rt.stopPropagation(),onClick:async rt=>{rt.preventDefault(),rt.stopPropagation(),await o?.(ce)},children:(()=>{const rt=Oi?kA:wA;return O.jsx(rt,{className:Z0("size-5",Oi?"text-amber-300":"text-white/90")})})()}),O.jsx("button",{type:"button",className:Ye,title:Pi?"Gefällt mir entfernen":"Als Gefällt mir markieren","aria-label":Pi?"Gefällt mir entfernen":"Als Gefällt mir markieren",disabled:ht||!u,onPointerDown:rt=>rt.stopPropagation(),onClick:async rt=>{rt.preventDefault(),rt.stopPropagation(),await u?.(ce)},children:(()=>{const rt=Pi?IA:DA;return O.jsx(rt,{className:Z0("size-5",Pi?"text-rose-300":"text-white/90")})})()}),O.jsx("button",{type:"button",className:Ye,title:"Aktionen","aria-label":"Aktionen",onPointerDown:rt=>rt.stopPropagation(),onClick:rt=>{rt.preventDefault(),rt.stopPropagation();const hs=rt.currentTarget.getBoundingClientRect();Ce(ce,hs.left,hs.bottom+6)},children:O.jsx(VS,{className:"size-5"})})]})})()})]}),O.jsxs("div",{className:"px-4 py-3",children:[O.jsx("div",{className:"flex items-center justify-between gap-3 text-xs text-gray-600 dark:text-gray-300",children:O.jsxs("div",{className:"min-w-0 truncate",children:["Status: ",re,O.jsx("span",{className:"mx-2 opacity-60",children:"•"}),"Dauer: ",O.jsx("span",{className:"font-medium",children:H}),O.jsx("span",{className:"mx-2 opacity-60",children:"•"}),"Größe: ",O.jsx("span",{className:"font-medium",children:G})]})}),ce.output?O.jsx("div",{className:"mt-1 truncate text-xs text-gray-500 dark:text-gray-400",title:ce.output,children:ce.output}):null]})]})});return Ri?O.jsx(hP,{ref:Ye=>{Ye?X.current.set(ye,Ye):X.current.delete(ye)},enabled:!0,disabled:ht,ignoreFromBottomPx:110,onTap:()=>{const Ye=`inline-prev-${encodeURIComponent(ye)}`;sh.flushSync(()=>$(ye)),de(Ye)||requestAnimationFrame(()=>de(Ye))},onSwipeLeft:()=>Ct(ce),onSwipeRight:()=>Fe(ce),children:Ge},ye):O.jsx(j.Fragment,{children:Ge},ye)})}),R==="table"&&O.jsx(vm,{rows:Yi,columns:Ti,getRowKey:ce=>os(ce),striped:!0,fullWidth:!0,stickyHeader:!0,compact:!0,sort:F,onSortChange:U,onRowClick:i,onRowContextMenu:(ce,ye)=>he(ce,ye),rowClassName:ce=>{const ye=os(ce);return["transition-all duration-300",(I.has(ye)||tt.has(ye))&&"bg-red-50/60 dark:bg-red-500/10 pointer-events-none",I.has(ye)&&"animate-pulse",(Ee.has(ye)||tt.has(ye))&&"pointer-events-none",Ee.has(ye)&&"bg-emerald-50/60 dark:bg-emerald-500/10 animate-pulse",tt.has(ye)&&"opacity-0"].filter(Boolean).join(" ")}}),R==="gallery"&&O.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4",children:Yi.map(ce=>{const ye=os(ce),Ae=sl(ce.output),ze=Zs(ce.output||""),ht=ts(ce),bi=J0(vd(ce)),Wi=I.has(ye)||Ee.has(ye)||tt.has(ye),H=E.has(ye);return O.jsxs("div",{role:"button",tabIndex:0,className:["group relative overflow-hidden rounded-lg outline-1 outline-black/5 dark:-outline-offset-1 dark:outline-white/10","bg-white dark:bg-gray-900/40","transition-all duration-200","hover:-translate-y-0.5 hover:shadow-md dark:hover:shadow-none","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500",Wi&&"pointer-events-none opacity-70",I.has(ye)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30",tt.has(ye)&&"opacity-0 translate-y-2 scale-[0.98]",H&&"hidden"].filter(Boolean).join(" "),onClick:()=>i(ce),onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&i(ce)},onContextMenu:G=>he(ce,G),children:[O.jsxs("div",{className:"group relative aspect-video bg-black/5 dark:bg-white/5",ref:$t(ye),onContextMenu:G=>{G.preventDefault(),G.stopPropagation(),he(ce,G)},children:[O.jsx(X0,{job:ce,getFileName:Zs,durationSeconds:Y[ye],onDuration:Ls,variant:"fill",showPopover:!1,blur:t,animated:b===ye,animatedMode:"clips",animatedTrigger:"always",clipSeconds:1,thumbSamples:18}),O.jsx("div",{className:` - pointer-events-none absolute inset-x-0 bottom-0 h-16 - bg-gradient-to-t from-black/65 to-transparent - transition-opacity duration-150 - group-hover:opacity-0 group-focus-within:opacity-0 - `}),O.jsxs("div",{className:` - pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white - transition-opacity duration-150 - group-hover:opacity-0 group-focus-within:opacity-0 - `,children:[O.jsx("div",{className:"truncate text-xs font-semibold",children:Ae}),O.jsxs("div",{className:"mt-0.5 flex items-center justify-between gap-2 text-[11px] opacity-90",children:[O.jsx("span",{className:"truncate",children:wu(ze)||"—"}),O.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[O.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:ht}),O.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:bi})]})]})]}),O.jsx("button",{type:"button",className:["absolute right-12 top-2 z-10 rounded-md px-2 py-1 text-xs font-semibold","bg-black/55 text-white hover:bg-black/70","opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity"].join(" "),"aria-label":"Behalten",title:"Behalten (nach keep verschieben)",disabled:Wi,onClick:G=>{G.preventDefault(),G.stopPropagation(),Fe(ce)},children:O.jsx(mp,{className:"size-5 text-emerald-600 dark:text-emerald-300"})}),O.jsx("button",{type:"button",className:["absolute right-2 top-2 z-10 rounded-md px-2 py-1 text-xs font-semibold","bg-black/55 text-white hover:bg-black/70","opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity"].join(" "),"aria-label":"Video löschen",title:"Video löschen",onClick:G=>{G.preventDefault(),G.stopPropagation(),Ct(ce)},children:O.jsx(Md,{className:"size-5 text-red-600 dark:text-red-300"})}),O.jsx("button",{type:"button",className:["absolute left-2 top-2 z-10 rounded-md px-2 py-1 text-xs font-semibold","bg-black/55 text-white hover:bg-black/70","opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity"].join(" "),"aria-label":"Aktionen",title:"Aktionen",onClick:G=>{G.preventDefault(),G.stopPropagation();const re=G.currentTarget.getBoundingClientRect();Ce(ce,re.left,re.bottom+6)},children:"⋯"})]}),O.jsx("div",{className:"px-3 py-2",children:O.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs text-gray-600 dark:text-gray-300",children:[O.jsxs("span",{className:"truncate",children:["Status:"," ",ce.status==="failed"?O.jsxs("span",{className:"text-red-700 dark:text-red-300",title:ce.error||"",children:["failed",yd(ce.error)?` (${yd(ce.error)})`:""]}):O.jsx("span",{className:"font-medium",children:ce.status})]}),Zs(ce.output||"").startsWith("HOT ")?O.jsx("span",{className:"shrink-0 rounded bg-amber-100 px-2 py-0.5 text-[11px] font-semibold text-amber-800 dark:bg-amber-500/15 dark:text-amber-200",children:"HOT"}):null]})})]},ye)})}),O.jsx(GO,{open:!!m,x:m?.x??0,y:m?.y??0,items:ut,onClose:()=>g(null)}),Tt.length>d?O.jsx("div",{className:"mt-3 flex justify-center",children:O.jsxs(es,{className:"rounded-md bg-black/5 px-3 py-2 text-sm font-medium hover:bg-black/10 dark:bg-white/10 dark:hover:bg-white/15",onClick:()=>f(ce=>Math.min(Tt.length,ce+50)),children:["Mehr laden (",Math.min(50,Tt.length-d)," von ",Tt.length-d,")"]})}):null]})}var ey,KS;function Tm(){if(KS)return ey;KS=1;var s;return typeof window<"u"?s=window:typeof Dp<"u"?s=Dp:typeof self<"u"?s=self:s={},ey=s,ey}var mP=Tm();const se=oc(mP),gP={},yP=Object.freeze(Object.defineProperty({__proto__:null,default:gP},Symbol.toStringTag,{value:"Module"})),vP=uk(yP);var ty,YS;function RA(){if(YS)return ty;YS=1;var s=typeof Dp<"u"?Dp:typeof window<"u"?window:{},e=vP,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),ty=t,ty}var TP=RA();const qe=oc(TP);var Vf={exports:{}},iy={exports:{}},WS;function bP(){return WS||(WS=1,(function(s){function e(){return s.exports=e=Object.assign?Object.assign.bind():function(t){for(var i=1;i=n.length?{done:!0}:{done:!1,value:n[u++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function e(n,r){if(n){if(typeof n=="string")return t(n,r);var o=Object.prototype.toString.call(n).slice(8,-1);if(o==="Object"&&n.constructor&&(o=n.constructor.name),o==="Map"||o==="Set")return Array.from(n);if(o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o))return t(n,r)}}function t(n,r){(r==null||r>n.length)&&(r=n.length);for(var o=0,u=new Array(r);o=400&&u.statusCode<=599){var d=c;if(r)if(s.TextDecoder){var f=t(u.headers&&u.headers["content-type"]);try{d=new TextDecoder(f).decode(c)}catch{}}else d=String.fromCharCode.apply(null,new Uint8Array(c));n({cause:d});return}n(null,c)}};function t(i){return i===void 0&&(i=""),i.toLowerCase().split(";").reduce(function(n,r){var o=r.split("="),u=o[0],c=o[1];return u.trim()==="charset"?c.trim():n},"utf-8")}return ay=e,ay}var eE;function AP(){if(eE)return Vf.exports;eE=1;var s=Tm(),e=bP(),t=_P(),i=xP(),n=SP();d.httpHandler=EP(),d.requestInterceptorsStorage=new i,d.responseInterceptorsStorage=new i,d.retryManager=new n;var r=function(b){var _={};return b&&b.trim().split(` -`).forEach(function(E){var L=E.indexOf(":"),I=E.slice(0,L).trim().toLowerCase(),w=E.slice(L+1).trim();typeof _[I]>"u"?_[I]=w:Array.isArray(_[I])?_[I].push(w):_[I]=[_[I],w]}),_};Vf.exports=d,Vf.exports.default=d,d.XMLHttpRequest=s.XMLHttpRequest||g,d.XDomainRequest="withCredentials"in new d.XMLHttpRequest?d.XMLHttpRequest:s.XDomainRequest,o(["get","put","post","patch","head","delete"],function(v){d[v==="delete"?"del":v]=function(b,_,E){return _=c(b,_,E),_.method=v.toUpperCase(),f(_)}});function o(v,b){for(var _=0;_"u")throw new Error("callback argument missing");if(v.requestType&&d.requestInterceptorsStorage.getIsEnabled()){var b={uri:v.uri||v.url,headers:v.headers||{},body:v.body,metadata:v.metadata||{},retry:v.retry,timeout:v.timeout},_=d.requestInterceptorsStorage.execute(v.requestType,b);v.uri=_.uri,v.headers=_.headers,v.body=_.body,v.metadata=_.metadata,v.retry=_.retry,v.timeout=_.timeout}var E=!1,L=function(te,oe,de){E||(E=!0,v.callback(te,oe,de))};function I(){V.readyState===4&&!d.responseInterceptorsStorage.getIsEnabled()&&setTimeout(U,0)}function w(){var Q=void 0;if(V.response?Q=V.response:Q=V.responseText||m(V),le)try{Q=JSON.parse(Q)}catch{}return Q}function F(Q){if(clearTimeout(ae),clearTimeout(v.retryTimeout),Q instanceof Error||(Q=new Error(""+(Q||"Unknown XMLHttpRequest Error"))),Q.statusCode=0,!q&&d.retryManager.getIsEnabled()&&v.retry&&v.retry.shouldRetry()){v.retryTimeout=setTimeout(function(){v.retry.moveToNextAttempt(),v.xhr=V,f(v)},v.retry.getCurrentFuzzedDelay());return}if(v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var te={headers:Y.headers||{},body:Y.body,responseUrl:V.responseURL,responseType:V.responseType},oe=d.responseInterceptorsStorage.execute(v.requestType,te);Y.body=oe.body,Y.headers=oe.headers}return L(Q,Y)}function U(){if(!q){var Q;clearTimeout(ae),clearTimeout(v.retryTimeout),v.useXDR&&V.status===void 0?Q=200:Q=V.status===1223?204:V.status;var te=Y,oe=null;if(Q!==0?(te={body:w(),statusCode:Q,method:R,headers:{},url:k,rawRequest:V},V.getAllResponseHeaders&&(te.headers=r(V.getAllResponseHeaders()))):oe=new Error("Internal XMLHttpRequest Error"),v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var de={headers:te.headers||{},body:te.body,responseUrl:V.responseURL,responseType:V.responseType},$=d.responseInterceptorsStorage.execute(v.requestType,de);te.body=$.body,te.headers=$.headers}return L(oe,te,te.body)}}var V=v.xhr||null;V||(v.cors||v.useXDR?V=new d.XDomainRequest:V=new d.XMLHttpRequest);var B,q,k=V.url=v.uri||v.url,R=V.method=v.method||"GET",K=v.body||v.data,X=V.headers=v.headers||{},ee=!!v.sync,le=!1,ae,Y={body:void 0,headers:{},statusCode:0,method:R,url:k,rawRequest:V};if("json"in v&&v.json!==!1&&(le=!0,X.accept||X.Accept||(X.Accept="application/json"),R!=="GET"&&R!=="HEAD"&&(X["content-type"]||X["Content-Type"]||(X["Content-Type"]="application/json"),K=JSON.stringify(v.json===!0?K:v.json))),V.onreadystatechange=I,V.onload=U,V.onerror=F,V.onprogress=function(){},V.onabort=function(){q=!0,clearTimeout(v.retryTimeout)},V.ontimeout=F,V.open(R,k,!ee,v.username,v.password),ee||(V.withCredentials=!!v.withCredentials),!ee&&v.timeout>0&&(ae=setTimeout(function(){if(!q){q=!0,V.abort("timeout");var Q=new Error("XMLHttpRequest timeout");Q.code="ETIMEDOUT",F(Q)}},v.timeout)),V.setRequestHeader)for(B in X)X.hasOwnProperty(B)&&V.setRequestHeader(B,X[B]);else if(v.headers&&!u(v.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in v&&(V.responseType=v.responseType),"beforeSend"in v&&typeof v.beforeSend=="function"&&v.beforeSend(V),V.send(K||null),V}function m(v){try{if(v.responseType==="document")return v.responseXML;var b=v.responseXML&&v.responseXML.documentElement.nodeName==="parsererror";if(v.responseType===""&&!b)return v.responseXML}catch{}return null}function g(){}return Vf.exports}var CP=AP();const OA=oc(CP);var oy={exports:{}},ly,tE;function DP(){if(tE)return ly;tE=1;var s=RA(),e=Object.create||(function(){function k(){}return function(R){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return k.prototype=R,new k}})();function t(k,R){this.name="ParsingError",this.code=k.code,this.message=R||k.message}t.prototype=e(Error.prototype),t.prototype.constructor=t,t.Errors={BadSignature:{code:0,message:"Malformed WebVTT signature."},BadTimeStamp:{code:1,message:"Malformed time stamp."}};function i(k){function R(X,ee,le,ae){return(X|0)*3600+(ee|0)*60+(le|0)+(ae|0)/1e3}var K=k.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return K?K[3]?R(K[1],K[2],K[3].replace(":",""),K[4]):K[1]>59?R(K[1],K[2],0,K[4]):R(0,K[1],K[2],K[4]):null}function n(){this.values=e(null)}n.prototype={set:function(k,R){!this.get(k)&&R!==""&&(this.values[k]=R)},get:function(k,R,K){return K?this.has(k)?this.values[k]:R[K]:this.has(k)?this.values[k]:R},has:function(k){return k in this.values},alt:function(k,R,K){for(var X=0;X=0&&R<=100)?(this.set(k,R),!0):!1}};function r(k,R,K,X){var ee=X?k.split(X):[k];for(var le in ee)if(typeof ee[le]=="string"){var ae=ee[le].split(K);if(ae.length===2){var Y=ae[0].trim(),Q=ae[1].trim();R(Y,Q)}}}function o(k,R,K){var X=k;function ee(){var Y=i(k);if(Y===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+X);return k=k.replace(/^[^\sa-zA-Z-]+/,""),Y}function le(Y,Q){var te=new n;r(Y,function(oe,de){switch(oe){case"region":for(var $=K.length-1;$>=0;$--)if(K[$].id===de){te.set(oe,K[$].region);break}break;case"vertical":te.alt(oe,de,["rl","lr"]);break;case"line":var ie=de.split(","),he=ie[0];te.integer(oe,he),te.percent(oe,he)&&te.set("snapToLines",!1),te.alt(oe,he,["auto"]),ie.length===2&&te.alt("lineAlign",ie[1],["start","center","end"]);break;case"position":ie=de.split(","),te.percent(oe,ie[0]),ie.length===2&&te.alt("positionAlign",ie[1],["start","center","end"]);break;case"size":te.percent(oe,de);break;case"align":te.alt(oe,de,["start","center","end","left","right"]);break}},/:/,/\s/),Q.region=te.get("region",null),Q.vertical=te.get("vertical","");try{Q.line=te.get("line","auto")}catch{}Q.lineAlign=te.get("lineAlign","start"),Q.snapToLines=te.get("snapToLines",!0),Q.size=te.get("size",100);try{Q.align=te.get("align","center")}catch{Q.align=te.get("align","middle")}try{Q.position=te.get("position","auto")}catch{Q.position=te.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},Q.align)}Q.positionAlign=te.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},Q.align)}function ae(){k=k.replace(/^\s+/,"")}if(ae(),R.startTime=ee(),ae(),k.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+X);k=k.substr(3),ae(),R.endTime=ee(),ae(),le(k,R)}var u=s.createElement&&s.createElement("textarea"),c={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},d={white:"rgba(255,255,255,1)",lime:"rgba(0,255,0,1)",cyan:"rgba(0,255,255,1)",red:"rgba(255,0,0,1)",yellow:"rgba(255,255,0,1)",magenta:"rgba(255,0,255,1)",blue:"rgba(0,0,255,1)",black:"rgba(0,0,0,1)"},f={v:"title",lang:"lang"},m={rt:"ruby"};function g(k,R){function K(){if(!R)return null;function he(be){return R=R.substr(be.length),be}var Ce=R.match(/^([^<]*)(<[^>]*>?)?/);return he(Ce[1]?Ce[1]:Ce[2])}function X(he){return u.innerHTML=he,he=u.textContent,u.textContent="",he}function ee(he,Ce){return!m[Ce.localName]||m[Ce.localName]===he.localName}function le(he,Ce){var be=c[he];if(!be)return null;var Ue=k.document.createElement(be),Ee=f[he];return Ee&&Ce&&(Ue[Ee]=Ce.trim()),Ue}for(var ae=k.document.createElement("div"),Y=ae,Q,te=[];(Q=K())!==null;){if(Q[0]==="<"){if(Q[1]==="/"){te.length&&te[te.length-1]===Q.substr(2).replace(">","")&&(te.pop(),Y=Y.parentNode);continue}var oe=i(Q.substr(1,Q.length-2)),de;if(oe){de=k.document.createProcessingInstruction("timestamp",oe),Y.appendChild(de);continue}var $=Q.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!$||(de=le($[1],$[3]),!de)||!ee(Y,de))continue;if($[2]){var ie=$[2].split(".");ie.forEach(function(he){var Ce=/^bg_/.test(he),be=Ce?he.slice(3):he;if(d.hasOwnProperty(be)){var Ue=Ce?"background-color":"color",Ee=d[be];de.style[Ue]=Ee}}),de.className=ie.join(" ")}te.push($[1]),Y.appendChild(de),Y=de;continue}Y.appendChild(k.document.createTextNode(X(Q)))}return ae}var v=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[2084,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578],[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];function b(k){for(var R=0;R=K[0]&&k<=K[1])return!0}return!1}function _(k){var R=[],K="",X;if(!k||!k.childNodes)return"ltr";function ee(Y,Q){for(var te=Q.childNodes.length-1;te>=0;te--)Y.push(Q.childNodes[te])}function le(Y){if(!Y||!Y.length)return null;var Q=Y.pop(),te=Q.textContent||Q.innerText;if(te){var oe=te.match(/^.*(\n|\r)/);return oe?(Y.length=0,oe[0]):te}if(Q.tagName==="ruby")return le(Y);if(Q.childNodes)return ee(Y,Q),le(Y)}for(ee(R,k);K=le(R);)for(var ae=0;ae=0&&k.line<=100))return k.line;if(!k.track||!k.track.textTrackList||!k.track.textTrackList.mediaElement)return-1;for(var R=k.track,K=R.textTrackList,X=0,ee=0;eek.left&&this.topk.top},w.prototype.overlapsAny=function(k){for(var R=0;R=k.top&&this.bottom<=k.bottom&&this.left>=k.left&&this.right<=k.right},w.prototype.overlapsOppositeAxis=function(k,R){switch(R){case"+x":return this.leftk.right;case"+y":return this.topk.bottom}},w.prototype.intersectPercentage=function(k){var R=Math.max(0,Math.min(this.right,k.right)-Math.max(this.left,k.left)),K=Math.max(0,Math.min(this.bottom,k.bottom)-Math.max(this.top,k.top)),X=R*K;return X/(this.height*this.width)},w.prototype.toCSSCompatValues=function(k){return{top:this.top-k.top,bottom:k.bottom-this.bottom,left:this.left-k.left,right:k.right-this.right,height:this.height,width:this.width}},w.getSimpleBoxPosition=function(k){var R=k.div?k.div.offsetHeight:k.tagName?k.offsetHeight:0,K=k.div?k.div.offsetWidth:k.tagName?k.offsetWidth:0,X=k.div?k.div.offsetTop:k.tagName?k.offsetTop:0;k=k.div?k.div.getBoundingClientRect():k.tagName?k.getBoundingClientRect():k;var ee={left:k.left,right:k.right,top:k.top||X,height:k.height||R,bottom:k.bottom||X+(k.height||R),width:k.width||K};return ee};function F(k,R,K,X){function ee(be,Ue){for(var Ee,je=new w(be),Ve=1,tt=0;ttlt&&(Ee=new w(be),Ve=lt),be=new w(je)}return Ee||je}var le=new w(R),ae=R.cue,Y=E(ae),Q=[];if(ae.snapToLines){var te;switch(ae.vertical){case"":Q=["+y","-y"],te="height";break;case"rl":Q=["+x","-x"],te="width";break;case"lr":Q=["-x","+x"],te="width";break}var oe=le.lineHeight,de=oe*Math.round(Y),$=K[te]+oe,ie=Q[0];Math.abs(de)>$&&(de=de<0?-1:1,de*=Math.ceil($/oe)*oe),Y<0&&(de+=ae.vertical===""?K.height:K.width,Q=Q.reverse()),le.move(ie,de)}else{var he=le.lineHeight/K.height*100;switch(ae.lineAlign){case"center":Y-=he/2;break;case"end":Y-=he;break}switch(ae.vertical){case"":R.applyStyles({top:R.formatStyle(Y,"%")});break;case"rl":R.applyStyles({left:R.formatStyle(Y,"%")});break;case"lr":R.applyStyles({right:R.formatStyle(Y,"%")});break}Q=["+y","-x","+x","-y"],le=new w(R)}var Ce=ee(le,Q);R.move(Ce.toCSSCompatValues(K))}function U(){}U.StringDecoder=function(){return{decode:function(k){if(!k)return"";if(typeof k!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(k))}}},U.convertCueToDOMTree=function(k,R){return!k||!R?null:g(k,R)};var V=.05,B="sans-serif",q="1.5%";return U.processCues=function(k,R,K){if(!k||!R||!K)return null;for(;K.firstChild;)K.removeChild(K.firstChild);var X=k.document.createElement("div");X.style.position="absolute",X.style.left="0",X.style.right="0",X.style.top="0",X.style.bottom="0",X.style.margin=q,K.appendChild(X);function ee(oe){for(var de=0;de")===-1){R.cue.id=ae;continue}case"CUE":try{o(ae,R.cue,R.regionList)}catch(oe){R.reportOrThrowError(oe),R.cue=null,R.state="BADCUE";continue}R.state="CUETEXT";continue;case"CUETEXT":var te=ae.indexOf("-->")!==-1;if(!ae||te&&(Q=!0)){R.oncue&&R.oncue(R.cue),R.cue=null,R.state="ID";continue}R.cue.text&&(R.cue.text+=` -`),R.cue.text+=ae.replace(/\u2028/g,` -`).replace(/u2029/g,` -`);continue;case"BADCUE":ae||(R.state="ID");continue}}}catch(oe){R.reportOrThrowError(oe),R.state==="CUETEXT"&&R.cue&&R.oncue&&R.oncue(R.cue),R.cue=null,R.state=R.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var k=this;try{if(k.buffer+=k.decoder.decode(),(k.cue||k.state==="HEADER")&&(k.buffer+=` - -`,k.parse()),k.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(R){k.reportOrThrowError(R)}return k.onflush&&k.onflush(),this}},ly=U,ly}var uy,iE;function wP(){if(iE)return uy;iE=1;var s="auto",e={"":1,lr:1,rl:1},t={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function i(o){if(typeof o!="string")return!1;var u=e[o.toLowerCase()];return u?o.toLowerCase():!1}function n(o){if(typeof o!="string")return!1;var u=t[o.toLowerCase()];return u?o.toLowerCase():!1}function r(o,u,c){this.hasBeenReset=!1;var d="",f=!1,m=o,g=u,v=c,b=null,_="",E=!0,L="auto",I="start",w="auto",F="auto",U=100,V="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return d},set:function(B){d=""+B}},pauseOnExit:{enumerable:!0,get:function(){return f},set:function(B){f=!!B}},startTime:{enumerable:!0,get:function(){return m},set:function(B){if(typeof B!="number")throw new TypeError("Start time must be set to a number.");m=B,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return g},set:function(B){if(typeof B!="number")throw new TypeError("End time must be set to a number.");g=B,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return v},set:function(B){v=""+B,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return b},set:function(B){b=B,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return _},set:function(B){var q=i(B);if(q===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");_=q,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return E},set:function(B){E=!!B,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return L},set:function(B){if(typeof B!="number"&&B!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");L=B,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return I},set:function(B){var q=n(B);q?(I=q,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return w},set:function(B){if(B<0||B>100)throw new Error("Position must be between 0 and 100.");w=B,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return F},set:function(B){var q=n(B);q?(F=q,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return U},set:function(B){if(B<0||B>100)throw new Error("Size must be between 0 and 100.");U=B,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return V},set:function(B){var q=n(B);if(!q)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");V=q,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},uy=r,uy}var cy,sE;function LP(){if(sE)return cy;sE=1;var s={"":!0,up:!0};function e(n){if(typeof n!="string")return!1;var r=s[n.toLowerCase()];return r?n.toLowerCase():!1}function t(n){return typeof n=="number"&&n>=0&&n<=100}function i(){var n=100,r=3,o=0,u=100,c=0,d=100,f="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return n},set:function(m){if(!t(m))throw new Error("Width must be between 0 and 100.");n=m}},lines:{enumerable:!0,get:function(){return r},set:function(m){if(typeof m!="number")throw new TypeError("Lines must be set to a number.");r=m}},regionAnchorY:{enumerable:!0,get:function(){return u},set:function(m){if(!t(m))throw new Error("RegionAnchorX must be between 0 and 100.");u=m}},regionAnchorX:{enumerable:!0,get:function(){return o},set:function(m){if(!t(m))throw new Error("RegionAnchorY must be between 0 and 100.");o=m}},viewportAnchorY:{enumerable:!0,get:function(){return d},set:function(m){if(!t(m))throw new Error("ViewportAnchorY must be between 0 and 100.");d=m}},viewportAnchorX:{enumerable:!0,get:function(){return c},set:function(m){if(!t(m))throw new Error("ViewportAnchorX must be between 0 and 100.");c=m}},scroll:{enumerable:!0,get:function(){return f},set:function(m){var g=e(m);g===!1?console.warn("Scroll: an invalid or illegal string was specified."):f=g}}})}return cy=i,cy}var nE;function IP(){if(nE)return oy.exports;nE=1;var s=Tm(),e=oy.exports={WebVTT:DP(),VTTCue:wP(),VTTRegion:LP()};s.vttjs=e,s.WebVTT=e.WebVTT;var t=e.VTTCue,i=e.VTTRegion,n=s.VTTCue,r=s.VTTRegion;return e.shim=function(){s.VTTCue=t,s.VTTRegion=i},e.restore=function(){s.VTTCue=n,s.VTTRegion=r},s.VTTCue||e.shim(),oy.exports}var kP=IP();const rE=oc(kP);function $i(){return $i=Object.assign?Object.assign.bind():function(s){for(var e=1;e-1},e.trigger=function(i){var n=this.listeners[i];if(n)if(arguments.length===2)for(var r=n.length,o=0;o-1;t=this.buffer.indexOf(` -`))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const PP=" ",dy=function(s){const e=/([0-9.]*)?@?([0-9.]*)?/.exec(s||""),t={};return e[1]&&(t.length=parseInt(e[1],10)),e[2]&&(t.offset=parseInt(e[2],10)),t},MP=function(){const t="(?:"+"[^=]*"+")=(?:"+'"[^"]*"|[^,]*'+")";return new RegExp("(?:^|,)("+t+")")},Ps=function(s){const e={};if(!s)return e;const t=s.split(MP());let i=t.length,n;for(;i--;)t[i]!==""&&(n=/([^=]*)=(.*)/.exec(t[i]).slice(1),n[0]=n[0].replace(/^\s+|\s+$/g,""),n[1]=n[1].replace(/^\s+|\s+$/g,""),n[1]=n[1].replace(/^['"](.*)['"]$/g,"$1"),e[n[0]]=n[1]);return e},oE=s=>{const e=s.split("x"),t={};return e[0]&&(t.width=parseInt(e[0],10)),e[1]&&(t.height=parseInt(e[1],10)),t};class NP extends pT{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,i;if(e=e.trim(),e.length===0)return;if(e[0]!=="#"){this.trigger("data",{type:"uri",uri:e});return}this.tagMappers.reduce((r,o)=>{const u=o(e);return u===e?r:r.concat([u])},[e]).forEach(r=>{for(let o=0;or),this.customParsers.push(r=>{if(e.exec(r))return this.trigger("data",{type:"custom",data:i(r),customType:t,segment:n}),!0})}addTagMapper({expression:e,map:t}){const i=n=>e.test(n)?t(n):n;this.tagMappers.push(i)}}const BP=s=>s.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),ao=function(s){const e={};return Object.keys(s).forEach(function(t){e[BP(t)]=s[t]}),e},hy=function(s){const{serverControl:e,targetDuration:t,partTargetDuration:i}=s;if(!e)return;const n="#EXT-X-SERVER-CONTROL",r="holdBack",o="partHoldBack",u=t&&t*3,c=i&&i*2;t&&!e.hasOwnProperty(r)&&(e[r]=u,this.trigger("info",{message:`${n} defaulting HOLD-BACK to targetDuration * 3 (${u}).`})),u&&e[r]{n.uri||!n.parts&&!n.preloadHints||(!n.map&&r&&(n.map=r),!n.key&&o&&(n.key=o),!n.timeline&&typeof m=="number"&&(n.timeline=m),this.manifest.preloadSegment=n)}),this.parseStream.on("data",function(_){let E,L;if(t.manifest.definitions){for(const I in t.manifest.definitions)if(_.uri&&(_.uri=_.uri.replace(`{$${I}}`,t.manifest.definitions[I])),_.attributes)for(const w in _.attributes)typeof _.attributes[w]=="string"&&(_.attributes[w]=_.attributes[w].replace(`{$${I}}`,t.manifest.definitions[I]))}({tag(){({version(){_.version&&(this.manifest.version=_.version)},"allow-cache"(){this.manifest.allowCache=_.allowed,"allowed"in _||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const I={};"length"in _&&(n.byterange=I,I.length=_.length,"offset"in _||(_.offset=g)),"offset"in _&&(n.byterange=I,I.offset=_.offset),g=I.offset+I.length},endlist(){this.manifest.endList=!0},inf(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),"discontinuitySequence"in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger("info",{message:"defaulting discontinuity sequence to zero"})),_.title&&(n.title=_.title),_.duration>0&&(n.duration=_.duration),_.duration===0&&(n.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=i},key(){if(!_.attributes){this.trigger("warn",{message:"ignoring key declaration without attribute list"});return}if(_.attributes.METHOD==="NONE"){o=null;return}if(!_.attributes.URI){this.trigger("warn",{message:"ignoring key declaration without URI"});return}if(_.attributes.KEYFORMAT==="com.apple.streamingkeydelivery"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:_.attributes};return}if(_.attributes.KEYFORMAT==="com.microsoft.playready"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.microsoft.playready"]={uri:_.attributes.URI};return}if(_.attributes.KEYFORMAT===f){if(["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(_.attributes.METHOD)===-1){this.trigger("warn",{message:"invalid key method provided for Widevine"});return}if(_.attributes.METHOD==="SAMPLE-AES-CENC"&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),_.attributes.URI.substring(0,23)!=="data:text/plain;base64,"){this.trigger("warn",{message:"invalid key URI provided for Widevine"});return}if(!(_.attributes.KEYID&&_.attributes.KEYID.substring(0,2)==="0x")){this.trigger("warn",{message:"invalid key ID provided for Widevine"});return}this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:_.attributes.KEYFORMAT,keyId:_.attributes.KEYID.substring(2)},pssh:PA(_.attributes.URI.split(",")[1])};return}_.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),o={method:_.attributes.METHOD||"AES-128",uri:_.attributes.URI},typeof _.attributes.IV<"u"&&(o.iv=_.attributes.IV)},"media-sequence"(){if(!isFinite(_.number)){this.trigger("warn",{message:"ignoring invalid media sequence: "+_.number});return}this.manifest.mediaSequence=_.number},"discontinuity-sequence"(){if(!isFinite(_.number)){this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+_.number});return}this.manifest.discontinuitySequence=_.number,m=_.number},"playlist-type"(){if(!/VOD|EVENT/.test(_.playlistType)){this.trigger("warn",{message:"ignoring unknown playlist type: "+_.playlist});return}this.manifest.playlistType=_.playlistType},map(){r={},_.uri&&(r.uri=_.uri),_.byterange&&(r.byterange=_.byterange),o&&(r.key=o)},"stream-inf"(){if(this.manifest.playlists=i,this.manifest.mediaGroups=this.manifest.mediaGroups||d,!_.attributes){this.trigger("warn",{message:"ignoring empty stream-inf attributes"});return}n.attributes||(n.attributes={}),$i(n.attributes,_.attributes)},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||d,!(_.attributes&&_.attributes.TYPE&&_.attributes["GROUP-ID"]&&_.attributes.NAME)){this.trigger("warn",{message:"ignoring incomplete or missing media group"});return}const I=this.manifest.mediaGroups[_.attributes.TYPE];I[_.attributes["GROUP-ID"]]=I[_.attributes["GROUP-ID"]]||{},E=I[_.attributes["GROUP-ID"]],L={default:/yes/i.test(_.attributes.DEFAULT)},L.default?L.autoselect=!0:L.autoselect=/yes/i.test(_.attributes.AUTOSELECT),_.attributes.LANGUAGE&&(L.language=_.attributes.LANGUAGE),_.attributes.URI&&(L.uri=_.attributes.URI),_.attributes["INSTREAM-ID"]&&(L.instreamId=_.attributes["INSTREAM-ID"]),_.attributes.CHARACTERISTICS&&(L.characteristics=_.attributes.CHARACTERISTICS),_.attributes.FORCED&&(L.forced=/yes/i.test(_.attributes.FORCED)),E[_.attributes.NAME]=L},discontinuity(){m+=1,n.discontinuity=!0,this.manifest.discontinuityStarts.push(i.length)},"program-date-time"(){typeof this.manifest.dateTimeString>"u"&&(this.manifest.dateTimeString=_.dateTimeString,this.manifest.dateTimeObject=_.dateTimeObject),n.dateTimeString=_.dateTimeString,n.dateTimeObject=_.dateTimeObject;const{lastProgramDateTime:I}=this;this.lastProgramDateTime=new Date(_.dateTimeString).getTime(),I===null&&this.manifest.segments.reduceRight((w,F)=>(F.programDateTime=w-F.duration*1e3,F.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(_.duration)||_.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+_.duration});return}this.manifest.targetDuration=_.duration,hy.call(this,this.manifest)},start(){if(!_.attributes||isNaN(_.attributes["TIME-OFFSET"])){this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"});return}this.manifest.start={timeOffset:_.attributes["TIME-OFFSET"],precise:_.attributes.PRECISE}},"cue-out"(){n.cueOut=_.data},"cue-out-cont"(){n.cueOutCont=_.data},"cue-in"(){n.cueIn=_.data},skip(){this.manifest.skip=ao(_.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",_.attributes,["SKIPPED-SEGMENTS"])},part(){u=!0;const I=this.manifest.segments.length,w=ao(_.attributes);n.parts=n.parts||[],n.parts.push(w),w.byterange&&(w.byterange.hasOwnProperty("offset")||(w.byterange.offset=v),v=w.byterange.offset+w.byterange.length);const F=n.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${F} for segment #${I}`,_.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((U,V)=>{U.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${V} lacks required attribute(s): LAST-PART`})})},"server-control"(){const I=this.manifest.serverControl=ao(_.attributes);I.hasOwnProperty("canBlockReload")||(I.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),hy.call(this,this.manifest),I.canSkipDateranges&&!I.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint"(){const I=this.manifest.segments.length,w=ao(_.attributes),F=w.type&&w.type==="PART";n.preloadHints=n.preloadHints||[],n.preloadHints.push(w),w.byterange&&(w.byterange.hasOwnProperty("offset")||(w.byterange.offset=F?v:0,F&&(v=w.byterange.offset+w.byterange.length)));const U=n.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${U} for segment #${I}`,_.attributes,["TYPE","URI"]),!!w.type)for(let V=0;VV.id===w.id);this.manifest.dateRanges[U]=$i(this.manifest.dateRanges[U],w),b[w.id]=$i(b[w.id],w),this.manifest.dateRanges.pop()}},"independent-segments"(){this.manifest.independentSegments=!0},"i-frames-only"(){this.manifest.iFramesOnly=!0,this.requiredCompatibilityversion(this.manifest.version,4)},"content-steering"(){this.manifest.contentSteering=ao(_.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",_.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const I=(w,F)=>{if(w in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${w}`});return}this.manifest.definitions[w]=F};if("QUERYPARAM"in _.attributes){if("NAME"in _.attributes||"IMPORT"in _.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}const w=this.params.get(_.attributes.QUERYPARAM);if(!w){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${_.attributes.QUERYPARAM}`});return}I(_.attributes.QUERYPARAM,decodeURIComponent(w));return}if("NAME"in _.attributes){if("IMPORT"in _.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}if(!("VALUE"in _.attributes)||typeof _.attributes.VALUE!="string"){this.trigger("error",{message:`EXT-X-DEFINE: No value for ${_.attributes.NAME}`});return}I(_.attributes.NAME,_.attributes.VALUE);return}if("IMPORT"in _.attributes){if(!this.mainDefinitions[_.attributes.IMPORT]){this.trigger("error",{message:`EXT-X-DEFINE: No value ${_.attributes.IMPORT} to import, or IMPORT used on main playlist`});return}I(_.attributes.IMPORT,this.mainDefinitions[_.attributes.IMPORT]);return}this.trigger("error",{message:"EXT-X-DEFINE: No attribute"})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:_.attributes,uri:_.uri,timeline:m}),this.warnOnMissingAttributes_("#EXT-X-I-FRAME-STREAM-INF",_.attributes,["BANDWIDTH","URI"])}}[_.tagType]||c).call(t)},uri(){n.uri=_.uri,i.push(n),this.manifest.targetDuration&&!("duration"in n)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),n.duration=this.manifest.targetDuration),o&&(n.key=o),n.timeline=m,r&&(n.map=r),v=0,this.lastProgramDateTime!==null&&(n.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=n.duration*1e3),n={}},comment(){},custom(){_.segment?(n.custom=n.custom||{},n.custom[_.customType]=_.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[_.customType]=_.data)}})[_.type].call(t)})}requiredCompatibilityversion(e,t){(em&&(f-=m,f-=m,f-=vs(2))}return Number(f)},WP=function(e,t){var i={},n=i.le,r=n===void 0?!1:n;(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&e!==e)&&(e=0),e=vs(e);for(var o=zP(e),u=new Uint8Array(new ArrayBuffer(o)),c=0;c=t.length&&d.call(t,function(f,m){var g=c[m]?c[m]&e[o+m]:e[o+m];return f===g})},QP=function(e,t,i){t.forEach(function(n){for(var r in e.mediaGroups[n])for(var o in e.mediaGroups[n][r]){var u=e.mediaGroups[n][r][o];i(u,n,r,o)}})},Td={},ua={},nl={},cE;function _m(){if(cE)return nl;cE=1;function s(r,o,u){if(u===void 0&&(u=Array.prototype),r&&typeof u.find=="function")return u.find.call(r,o);for(var c=0;c=0&&H=0){for(var Ge=G.length-1;we0},lookupPrefix:function(H){for(var G=this;G;){var re=G._nsMap;if(re){for(var we in re)if(Object.prototype.hasOwnProperty.call(re,we)&&re[we]===H)return we}G=G.nodeType==g?G.ownerDocument:G.parentNode}return null},lookupNamespaceURI:function(H){for(var G=this;G;){var re=G._nsMap;if(re&&Object.prototype.hasOwnProperty.call(re,H))return re[H];G=G.nodeType==g?G.ownerDocument:G.parentNode}return null},isDefaultNamespace:function(H){var G=this.lookupPrefix(H);return G==null}};function ie(H){return H=="<"&&"<"||H==">"&&">"||H=="&"&&"&"||H=='"'&&"""||"&#"+H.charCodeAt()+";"}c(f,$),c(f,$.prototype);function he(H,G){if(G(H))return!0;if(H=H.firstChild)do if(he(H,G))return!0;while(H=H.nextSibling)}function Ce(){this.ownerDocument=this}function be(H,G,re){H&&H._inc++;var we=re.namespaceURI;we===t.XMLNS&&(G._nsMap[re.prefix?re.localName:""]=re.value)}function Ue(H,G,re,we){H&&H._inc++;var Ge=re.namespaceURI;Ge===t.XMLNS&&delete G._nsMap[re.prefix?re.localName:""]}function Ee(H,G,re){if(H&&H._inc){H._inc++;var we=G.childNodes;if(re)we[we.length++]=re;else{for(var Ge=G.firstChild,Ye=0;Ge;)we[Ye++]=Ge,Ge=Ge.nextSibling;we.length=Ye,delete we[we.length]}}}function je(H,G){var re=G.previousSibling,we=G.nextSibling;return re?re.nextSibling=we:H.firstChild=we,we?we.previousSibling=re:H.lastChild=re,G.parentNode=null,G.previousSibling=null,G.nextSibling=null,Ee(H.ownerDocument,H),G}function Ve(H){return H&&(H.nodeType===$.DOCUMENT_NODE||H.nodeType===$.DOCUMENT_FRAGMENT_NODE||H.nodeType===$.ELEMENT_NODE)}function tt(H){return H&&(Me(H)||Je(H)||lt(H)||H.nodeType===$.DOCUMENT_FRAGMENT_NODE||H.nodeType===$.COMMENT_NODE||H.nodeType===$.PROCESSING_INSTRUCTION_NODE)}function lt(H){return H&&H.nodeType===$.DOCUMENT_TYPE_NODE}function Me(H){return H&&H.nodeType===$.ELEMENT_NODE}function Je(H){return H&&H.nodeType===$.TEXT_NODE}function st(H,G){var re=H.childNodes||[];if(e(re,Me)||lt(G))return!1;var we=e(re,lt);return!(G&&we&&re.indexOf(we)>re.indexOf(G))}function Ct(H,G){var re=H.childNodes||[];function we(Ye){return Me(Ye)&&Ye!==G}if(e(re,we))return!1;var Ge=e(re,lt);return!(G&&Ge&&re.indexOf(Ge)>re.indexOf(G))}function Fe(H,G,re){if(!Ve(H))throw new X(k,"Unexpected parent node type "+H.nodeType);if(re&&re.parentNode!==H)throw new X(R,"child not in parent");if(!tt(G)||lt(G)&&H.nodeType!==$.DOCUMENT_NODE)throw new X(k,"Unexpected node type "+G.nodeType+" for parent node type "+H.nodeType)}function ut(H,G,re){var we=H.childNodes||[],Ge=G.childNodes||[];if(G.nodeType===$.DOCUMENT_FRAGMENT_NODE){var Ye=Ge.filter(Me);if(Ye.length>1||e(Ge,Je))throw new X(k,"More than one element or text in fragment");if(Ye.length===1&&!st(H,re))throw new X(k,"Element in fragment can not be inserted before doctype")}if(Me(G)&&!st(H,re))throw new X(k,"Only one element can be added and only after doctype");if(lt(G)){if(e(we,lt))throw new X(k,"Only one doctype is allowed");var wt=e(we,Me);if(re&&we.indexOf(wt)1||e(Ge,Je))throw new X(k,"More than one element or text in fragment");if(Ye.length===1&&!Ct(H,re))throw new X(k,"Element in fragment can not be inserted before doctype")}if(Me(G)&&!Ct(H,re))throw new X(k,"Only one element can be added and only after doctype");if(lt(G)){let is=function(ji){return lt(ji)&&ji!==re};var Ci=is;if(e(we,is))throw new X(k,"Only one doctype is allowed");var wt=e(we,Me);if(re&&we.indexOf(wt)0&&he(re.documentElement,function(Ge){if(Ge!==re&&Ge.nodeType===m){var Ye=Ge.getAttribute("class");if(Ye){var wt=H===Ye;if(!wt){var Ci=o(Ye);wt=G.every(u(Ci))}wt&&we.push(Ge)}}}),we})},createElement:function(H){var G=new He;G.ownerDocument=this,G.nodeName=H,G.tagName=H,G.localName=H,G.childNodes=new ee;var re=G.attributes=new Y;return re._ownerElement=G,G},createDocumentFragment:function(){var H=new $t;return H.ownerDocument=this,H.childNodes=new ee,H},createTextNode:function(H){var G=new pt;return G.ownerDocument=this,G.appendData(H),G},createComment:function(H){var G=new mt;return G.ownerDocument=this,G.appendData(H),G},createCDATASection:function(H){var G=new jt;return G.ownerDocument=this,G.appendData(H),G},createProcessingInstruction:function(H,G){var re=new Ls;return re.ownerDocument=this,re.tagName=re.nodeName=re.target=H,re.nodeValue=re.data=G,re},createAttribute:function(H){var G=new Xe;return G.ownerDocument=this,G.name=H,G.nodeName=H,G.localName=H,G.specified=!0,G},createEntityReference:function(H){var G=new ts;return G.ownerDocument=this,G.nodeName=H,G},createElementNS:function(H,G){var re=new He,we=G.split(":"),Ge=re.attributes=new Y;return re.childNodes=new ee,re.ownerDocument=this,re.nodeName=G,re.tagName=G,re.namespaceURI=H,we.length==2?(re.prefix=we[0],re.localName=we[1]):re.localName=G,Ge._ownerElement=re,re},createAttributeNS:function(H,G){var re=new Xe,we=G.split(":");return re.ownerDocument=this,re.nodeName=G,re.name=G,re.namespaceURI=H,re.specified=!0,we.length==2?(re.prefix=we[0],re.localName=we[1]):re.localName=G,re}},d(Ce,$);function He(){this._nsMap={}}He.prototype={nodeType:m,hasAttribute:function(H){return this.getAttributeNode(H)!=null},getAttribute:function(H){var G=this.getAttributeNode(H);return G&&G.value||""},getAttributeNode:function(H){return this.attributes.getNamedItem(H)},setAttribute:function(H,G){var re=this.ownerDocument.createAttribute(H);re.value=re.nodeValue=""+G,this.setAttributeNode(re)},removeAttribute:function(H){var G=this.getAttributeNode(H);G&&this.removeAttributeNode(G)},appendChild:function(H){return H.nodeType===U?this.insertBefore(H,null):$e(this,H)},setAttributeNode:function(H){return this.attributes.setNamedItem(H)},setAttributeNodeNS:function(H){return this.attributes.setNamedItemNS(H)},removeAttributeNode:function(H){return this.attributes.removeNamedItem(H.nodeName)},removeAttributeNS:function(H,G){var re=this.getAttributeNodeNS(H,G);re&&this.removeAttributeNode(re)},hasAttributeNS:function(H,G){return this.getAttributeNodeNS(H,G)!=null},getAttributeNS:function(H,G){var re=this.getAttributeNodeNS(H,G);return re&&re.value||""},setAttributeNS:function(H,G,re){var we=this.ownerDocument.createAttributeNS(H,G);we.value=we.nodeValue=""+re,this.setAttributeNode(we)},getAttributeNodeNS:function(H,G){return this.attributes.getNamedItemNS(H,G)},getElementsByTagName:function(H){return new le(this,function(G){var re=[];return he(G,function(we){we!==G&&we.nodeType==m&&(H==="*"||we.tagName==H)&&re.push(we)}),re})},getElementsByTagNameNS:function(H,G){return new le(this,function(re){var we=[];return he(re,function(Ge){Ge!==re&&Ge.nodeType===m&&(H==="*"||Ge.namespaceURI===H)&&(G==="*"||Ge.localName==G)&&we.push(Ge)}),we})}},Ce.prototype.getElementsByTagName=He.prototype.getElementsByTagName,Ce.prototype.getElementsByTagNameNS=He.prototype.getElementsByTagNameNS,d(He,$);function Xe(){}Xe.prototype.nodeType=g,d(Xe,$);function We(){}We.prototype={data:"",substringData:function(H,G){return this.data.substring(H,H+G)},appendData:function(H){H=this.data+H,this.nodeValue=this.data=H,this.length=H.length},insertData:function(H,G){this.replaceData(H,0,G)},appendChild:function(H){throw new Error(q[k])},deleteData:function(H,G){this.replaceData(H,G,"")},replaceData:function(H,G,re){var we=this.data.substring(0,H),Ge=this.data.substring(H+G);re=we+re+Ge,this.nodeValue=this.data=re,this.length=re.length}},d(We,$);function pt(){}pt.prototype={nodeName:"#text",nodeType:v,splitText:function(H){var G=this.data,re=G.substring(H);G=G.substring(0,H),this.data=this.nodeValue=G,this.length=G.length;var we=this.ownerDocument.createTextNode(re);return this.parentNode&&this.parentNode.insertBefore(we,this.nextSibling),we}},d(pt,We);function mt(){}mt.prototype={nodeName:"#comment",nodeType:I},d(mt,We);function jt(){}jt.prototype={nodeName:"#cdata-section",nodeType:b},d(jt,We);function fi(){}fi.prototype.nodeType=F,d(fi,$);function Ai(){}Ai.prototype.nodeType=V,d(Ai,$);function Yi(){}Yi.prototype.nodeType=E,d(Yi,$);function ts(){}ts.prototype.nodeType=_,d(ts,$);function $t(){}$t.prototype.nodeName="#document-fragment",$t.prototype.nodeType=U,d($t,$);function Ls(){}Ls.prototype.nodeType=L,d(Ls,$);function Ti(){}Ti.prototype.serializeToString=function(H,G,re){return Ri.call(H,G,re)},$.prototype.toString=Ri;function Ri(H,G){var re=[],we=this.nodeType==9&&this.documentElement||this,Ge=we.prefix,Ye=we.namespaceURI;if(Ye&&Ge==null){var Ge=we.lookupPrefix(Ye);if(Ge==null)var wt=[{namespace:Ye,prefix:null}]}return Ae(this,re,H,G,wt),re.join("")}function ce(H,G,re){var we=H.prefix||"",Ge=H.namespaceURI;if(!Ge||we==="xml"&&Ge===t.XML||Ge===t.XMLNS)return!1;for(var Ye=re.length;Ye--;){var wt=re[Ye];if(wt.prefix===we)return wt.namespace!==Ge}return!0}function ye(H,G,re){H.push(" ",G,'="',re.replace(/[<>&"\t\n\r]/g,ie),'"')}function Ae(H,G,re,we,Ge){if(Ge||(Ge=[]),we)if(H=we(H),H){if(typeof H=="string"){G.push(H);return}}else return;switch(H.nodeType){case m:var Ye=H.attributes,wt=Ye.length,Bt=H.firstChild,Ci=H.tagName;re=t.isHTML(H.namespaceURI)||re;var is=Ci;if(!re&&!H.prefix&&H.namespaceURI){for(var ji,Oi=0;Oi=0;Pi--){var rt=Ge[Pi];if(rt.prefix===""&&rt.namespace===H.namespaceURI){ji=rt.namespace;break}}if(ji!==H.namespaceURI)for(var Pi=Ge.length-1;Pi>=0;Pi--){var rt=Ge[Pi];if(rt.namespace===H.namespaceURI){rt.prefix&&(is=rt.prefix+":"+Ci);break}}}G.push("<",is);for(var hs=0;hs"),re&&/^script$/i.test(Ci))for(;Bt;)Bt.data?G.push(Bt.data):Ae(Bt,G,re,we,Ge.slice()),Bt=Bt.nextSibling;else for(;Bt;)Ae(Bt,G,re,we,Ge.slice()),Bt=Bt.nextSibling;G.push("")}else G.push("/>");return;case w:case U:for(var Bt=H.firstChild;Bt;)Ae(Bt,G,re,we,Ge.slice()),Bt=Bt.nextSibling;return;case g:return ye(G,H.name,H.value);case v:return G.push(H.data.replace(/[<&>]/g,ie));case b:return G.push("");case I:return G.push("");case F:var Ot=H.publicId,Cn=H.systemId;if(G.push("");else if(Cn&&Cn!=".")G.push(" SYSTEM ",Cn,">");else{var jr=H.internalSubset;jr&&G.push(" [",jr,"]"),G.push(">")}return;case L:return G.push("");case _:return G.push("&",H.nodeName,";");default:G.push("??",H.nodeName)}}function ze(H,G,re){var we;switch(G.nodeType){case m:we=G.cloneNode(!1),we.ownerDocument=H;case U:break;case g:re=!0;break}if(we||(we=G.cloneNode(!1)),we.ownerDocument=H,we.parentNode=null,re)for(var Ge=G.firstChild;Ge;)we.appendChild(ze(H,Ge,re)),Ge=Ge.nextSibling;return we}function ht(H,G,re){var we=new G.constructor;for(var Ge in G)if(Object.prototype.hasOwnProperty.call(G,Ge)){var Ye=G[Ge];typeof Ye!="object"&&Ye!=we[Ge]&&(we[Ge]=Ye)}switch(G.childNodes&&(we.childNodes=new ee),we.ownerDocument=H,we.nodeType){case m:var wt=G.attributes,Ci=we.attributes=new Y,is=wt.length;Ci._ownerElement=we;for(var ji=0;ji",lt:"<",quot:'"'}),s.HTML_ENTITIES=e({Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"⁡",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"ℭ",cfr:"𝔠",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"𝕔",coprod:"∐",Coproduct:"∐",COPY:"©",copy:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"𝒻",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",Gt:"≫",GT:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"𝔥",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"𝕙",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"𝒽",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"ℑ",ifr:"𝔦",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"ℐ",iscr:"𝒾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"𝓁",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",Lt:"≪",LT:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",Mscr:"ℳ",mscr:"𝓂",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:` -`,nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",nopf:"𝕟",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"𝕡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",Qopf:"ℚ",qopf:"𝕢",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"𝔯",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"𝓇",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:" ",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}),s.entityMap=s.HTML_ENTITIES})(py)),py}var qf={},fE;function JP(){if(fE)return qf;fE=1;var s=_m().NAMESPACE,e=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,t=new RegExp("[\\-\\.0-9"+e.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),i=new RegExp("^"+e.source+t.source+"*(?::"+e.source+t.source+"*)?$"),n=0,r=1,o=2,u=3,c=4,d=5,f=6,m=7;function g(k,R){this.message=k,this.locator=R,Error.captureStackTrace&&Error.captureStackTrace(this,g)}g.prototype=new Error,g.prototype.name=g.name;function v(){}v.prototype={parse:function(k,R,K){var X=this.domBuilder;X.startDocument(),F(R,R={}),b(k,R,K,X,this.errorHandler),X.endDocument()}};function b(k,R,K,X,ee){function le($e){if($e>65535){$e-=65536;var He=55296+($e>>10),Xe=56320+($e&1023);return String.fromCharCode(He,Xe)}else return String.fromCharCode($e)}function ae($e){var He=$e.slice(1,-1);return Object.hasOwnProperty.call(K,He)?K[He]:He.charAt(0)==="#"?le(parseInt(He.substr(1).replace("x","0x"))):(ee.error("entity not found:"+$e),$e)}function Y($e){if($e>Ce){var He=k.substring(Ce,$e).replace(/&#?\w+;/g,ae);$&&Q(Ce),X.characters(He,0,$e-Ce),Ce=$e}}function Q($e,He){for(;$e>=oe&&(He=de.exec(k));)te=He.index,oe=te+He[0].length,$.lineNumber++;$.columnNumber=$e-te+1}for(var te=0,oe=0,de=/.*(?:\r\n?|\n)|.*$/g,$=X.locator,ie=[{currentNSMap:R}],he={},Ce=0;;){try{var be=k.indexOf("<",Ce);if(be<0){if(!k.substr(Ce).match(/^\s*$/)){var Ue=X.doc,Ee=Ue.createTextNode(k.substr(Ce));Ue.appendChild(Ee),X.currentElement=Ee}return}switch(be>Ce&&Y(be),k.charAt(be+1)){case"/":var Fe=k.indexOf(">",be+3),je=k.substring(be+2,Fe).replace(/[ \t\n\r]+$/g,""),Ve=ie.pop();Fe<0?(je=k.substring(be+2).replace(/[\s<].*/,""),ee.error("end tag name: "+je+" is not complete:"+Ve.tagName),Fe=be+1+je.length):je.match(/\sCe?Ce=Fe:Y(Math.max(be,Ce)+1)}}function _(k,R){return R.lineNumber=k.lineNumber,R.columnNumber=k.columnNumber,R}function E(k,R,K,X,ee,le){function ae($,ie,he){K.attributeNames.hasOwnProperty($)&&le.fatalError("Attribute "+$+" redefined"),K.addValue($,ie.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,ee),he)}for(var Y,Q,te=++R,oe=n;;){var de=k.charAt(te);switch(de){case"=":if(oe===r)Y=k.slice(R,te),oe=u;else if(oe===o)oe=u;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(oe===u||oe===r)if(oe===r&&(le.warning('attribute value must after "="'),Y=k.slice(R,te)),R=te+1,te=k.indexOf(de,R),te>0)Q=k.slice(R,te),ae(Y,Q,R-1),oe=d;else throw new Error("attribute value no end '"+de+"' match");else if(oe==c)Q=k.slice(R,te),ae(Y,Q,R),le.warning('attribute "'+Y+'" missed start quot('+de+")!!"),R=te+1,oe=d;else throw new Error('attribute value must after "="');break;case"/":switch(oe){case n:K.setTagName(k.slice(R,te));case d:case f:case m:oe=m,K.closed=!0;case c:case r:break;case o:K.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return le.error("unexpected end of input"),oe==n&&K.setTagName(k.slice(R,te)),te;case">":switch(oe){case n:K.setTagName(k.slice(R,te));case d:case f:case m:break;case c:case r:Q=k.slice(R,te),Q.slice(-1)==="/"&&(K.closed=!0,Q=Q.slice(0,-1));case o:oe===o&&(Q=Y),oe==c?(le.warning('attribute "'+Q+'" missed quot(")!'),ae(Y,Q,R)):((!s.isHTML(X[""])||!Q.match(/^(?:disabled|checked|selected)$/i))&&le.warning('attribute "'+Q+'" missed value!! "'+Q+'" instead!!'),ae(Q,Q,R));break;case u:throw new Error("attribute value missed!!")}return te;case"€":de=" ";default:if(de<=" ")switch(oe){case n:K.setTagName(k.slice(R,te)),oe=f;break;case r:Y=k.slice(R,te),oe=o;break;case c:var Q=k.slice(R,te);le.warning('attribute "'+Q+'" missed quot(")!!'),ae(Y,Q,R);case d:oe=f;break}else switch(oe){case o:K.tagName,(!s.isHTML(X[""])||!Y.match(/^(?:disabled|checked|selected)$/i))&&le.warning('attribute "'+Y+'" missed value!! "'+Y+'" instead2!!'),ae(Y,Y,R),R=te,oe=r;break;case d:le.warning('attribute space is required"'+Y+'"!!');case f:oe=r,R=te;break;case u:oe=c,R=te;break;case m:throw new Error("elements closed character '/' and '>' must be connected to")}}te++}}function L(k,R,K){for(var X=k.tagName,ee=null,de=k.length;de--;){var le=k[de],ae=le.qName,Y=le.value,$=ae.indexOf(":");if($>0)var Q=le.prefix=ae.slice(0,$),te=ae.slice($+1),oe=Q==="xmlns"&&te;else te=ae,Q=null,oe=ae==="xmlns"&&"";le.localName=te,oe!==!1&&(ee==null&&(ee={},F(K,K={})),K[oe]=ee[oe]=Y,le.uri=s.XMLNS,R.startPrefixMapping(oe,Y))}for(var de=k.length;de--;){le=k[de];var Q=le.prefix;Q&&(Q==="xml"&&(le.uri=s.XML),Q!=="xmlns"&&(le.uri=K[Q||""]))}var $=X.indexOf(":");$>0?(Q=k.prefix=X.slice(0,$),te=k.localName=X.slice($+1)):(Q=null,te=k.localName=X);var ie=k.uri=K[Q||""];if(R.startElement(ie,te,X,k),k.closed){if(R.endElement(ie,te,X),ee)for(Q in ee)Object.prototype.hasOwnProperty.call(ee,Q)&&R.endPrefixMapping(Q)}else return k.currentNSMap=K,k.localNSMap=ee,!0}function I(k,R,K,X,ee){if(/^(?:script|textarea)$/i.test(K)){var le=k.indexOf("",R),ae=k.substring(R+1,le);if(/[&<]/.test(ae))return/^script$/i.test(K)?(ee.characters(ae,0,ae.length),le):(ae=ae.replace(/&#?\w+;/g,X),ee.characters(ae,0,ae.length),le)}return R+1}function w(k,R,K,X){var ee=X[K];return ee==null&&(ee=k.lastIndexOf(""),ee",R+4);return le>R?(K.comment(k,R+4,le-R-4),le+3):(X.error("Unclosed comment"),-1)}else return-1;default:if(k.substr(R+3,6)=="CDATA["){var le=k.indexOf("]]>",R+9);return K.startCDATA(),K.characters(k,R+9,le-R-9),K.endCDATA(),le+3}var ae=q(k,R),Y=ae.length;if(Y>1&&/!doctype/i.test(ae[0][0])){var Q=ae[1][0],te=!1,oe=!1;Y>3&&(/^public$/i.test(ae[2][0])?(te=ae[3][0],oe=Y>4&&ae[4][0]):/^system$/i.test(ae[2][0])&&(oe=ae[3][0]));var de=ae[Y-1];return K.startDTD(Q,te,oe),K.endDTD(),de.index+de[0].length}}return-1}function V(k,R,K){var X=k.indexOf("?>",R);if(X){var ee=k.substring(R,X).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return ee?(ee[0].length,K.processingInstruction(ee[1],ee[2]),X+2):-1}return-1}function B(){this.attributeNames={}}B.prototype={setTagName:function(k){if(!i.test(k))throw new Error("invalid tagName:"+k);this.tagName=k},addValue:function(k,R,K){if(!i.test(k))throw new Error("invalid attribute:"+k);this.attributeNames[k]=this.length,this[this.length++]={qName:k,value:R,offset:K}},length:0,getLocalName:function(k){return this[k].localName},getLocator:function(k){return this[k].locator},getQName:function(k){return this[k].qName},getURI:function(k){return this[k].uri},getValue:function(k){return this[k].value}};function q(k,R){var K,X=[],ee=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(ee.lastIndex=R,ee.exec(k);K=ee.exec(k);)if(X.push(K),K[1])return X}return qf.XMLReader=v,qf.ParseError=g,qf}var pE;function eM(){if(pE)return bd;pE=1;var s=_m(),e=$A(),t=ZP(),i=JP(),n=e.DOMImplementation,r=s.NAMESPACE,o=i.ParseError,u=i.XMLReader;function c(E){return E.replace(/\r[\n\u0085]/g,` -`).replace(/[\r\u0085\u2028]/g,` -`)}function d(E){this.options=E||{locator:{}}}d.prototype.parseFromString=function(E,L){var I=this.options,w=new u,F=I.domBuilder||new m,U=I.errorHandler,V=I.locator,B=I.xmlns||{},q=/\/x?html?$/.test(L),k=q?t.HTML_ENTITIES:t.XML_ENTITIES;V&&F.setDocumentLocator(V),w.errorHandler=f(U,F,V),w.domBuilder=I.domBuilder||F,q&&(B[""]=r.HTML),B.xml=B.xml||r.XML;var R=I.normalizeLineEndings||c;return E&&typeof E=="string"?w.parse(R(E),B,k):w.errorHandler.error("invalid doc source"),F.doc};function f(E,L,I){if(!E){if(L instanceof m)return L;E=L}var w={},F=E instanceof Function;I=I||{};function U(V){var B=E[V];!B&&F&&(B=E.length==2?function(q){E(V,q)}:E),w[V]=B&&function(q){B("[xmldom "+V+"] "+q+v(I))}||function(){}}return U("warning"),U("error"),U("fatalError"),w}function m(){this.cdata=!1}function g(E,L){L.lineNumber=E.lineNumber,L.columnNumber=E.columnNumber}m.prototype={startDocument:function(){this.doc=new n().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(E,L,I,w){var F=this.doc,U=F.createElementNS(E,I||L),V=w.length;_(this,U),this.currentElement=U,this.locator&&g(this.locator,U);for(var B=0;B=L+I||L?new java.lang.String(E,L,I)+"":E}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(E){m.prototype[E]=function(){return null}});function _(E,L){E.currentElement?E.currentElement.appendChild(L):E.doc.appendChild(L)}return bd.__DOMHandler=m,bd.normalizeLineEndings=c,bd.DOMParser=d,bd}var mE;function tM(){if(mE)return Td;mE=1;var s=$A();return Td.DOMImplementation=s.DOMImplementation,Td.XMLSerializer=s.XMLSerializer,Td.DOMParser=eM().DOMParser,Td}var iM=tM();const gE=s=>!!s&&typeof s=="object",cs=(...s)=>s.reduce((e,t)=>(typeof t!="object"||Object.keys(t).forEach(i=>{Array.isArray(e[i])&&Array.isArray(t[i])?e[i]=e[i].concat(t[i]):gE(e[i])&&gE(t[i])?e[i]=cs(e[i],t[i]):e[i]=t[i]}),e),{}),jA=s=>Object.keys(s).map(e=>s[e]),sM=(s,e)=>{const t=[];for(let i=s;is.reduce((e,t)=>e.concat(t),[]),HA=s=>{if(!s.length)return[];const e=[];for(let t=0;ts.reduce((t,i,n)=>(i[e]&&t.push(n),t),[]),rM=(s,e)=>jA(s.reduce((t,i)=>(i.forEach(n=>{t[e(n)]=n}),t),{}));var Zu={INVALID_NUMBER_OF_PERIOD:"INVALID_NUMBER_OF_PERIOD",DASH_EMPTY_MANIFEST:"DASH_EMPTY_MANIFEST",DASH_INVALID_XML:"DASH_INVALID_XML",NO_BASE_URL:"NO_BASE_URL",SEGMENT_TIME_UNSPECIFIED:"SEGMENT_TIME_UNSPECIFIED",UNSUPPORTED_UTC_TIMING_SCHEME:"UNSUPPORTED_UTC_TIMING_SCHEME"};const qd=({baseUrl:s="",source:e="",range:t="",indexRange:i=""})=>{const n={uri:e,resolvedUri:bm(s||"",e)};if(t||i){const o=(t||i).split("-");let u=se.BigInt?se.BigInt(o[0]):parseInt(o[0],10),c=se.BigInt?se.BigInt(o[1]):parseInt(o[1],10);u{let e;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=se.BigInt(s.offset)+se.BigInt(s.length)-se.BigInt(1):e=s.offset+s.length-1,`${s.offset}-${e}`},yE=s=>(s&&typeof s!="number"&&(s=parseInt(s,10)),isNaN(s)?null:s),oM={static(s){const{duration:e,timescale:t=1,sourceDuration:i,periodDuration:n}=s,r=yE(s.endNumber),o=e/t;return typeof r=="number"?{start:0,end:r}:typeof n=="number"?{start:0,end:n/o}:{start:0,end:i/o}},dynamic(s){const{NOW:e,clientOffset:t,availabilityStartTime:i,timescale:n=1,duration:r,periodStart:o=0,minimumUpdatePeriod:u=0,timeShiftBufferDepth:c=1/0}=s,d=yE(s.endNumber),f=(e+t)/1e3,m=i+o,v=f+u-m,b=Math.ceil(v*n/r),_=Math.floor((f-m-c)*n/r),E=Math.floor((f-m)*n/r);return{start:Math.max(0,_),end:typeof d=="number"?d:Math.min(b,E)}}},lM=s=>e=>{const{duration:t,timescale:i=1,periodStart:n,startNumber:r=1}=s;return{number:r+e,duration:t/i,timeline:n,time:e*t}},mT=s=>{const{type:e,duration:t,timescale:i=1,periodDuration:n,sourceDuration:r}=s,{start:o,end:u}=oM[e](s),c=sM(o,u).map(lM(s));if(e==="static"){const d=c.length-1,f=typeof n=="number"?n:r;c[d].duration=f-t/i*d}return c},GA=s=>{const{baseUrl:e,initialization:t={},sourceDuration:i,indexRange:n="",periodStart:r,presentationTime:o,number:u=0,duration:c}=s;if(!e)throw new Error(Zu.NO_BASE_URL);const d=qd({baseUrl:e,source:t.sourceURL,range:t.range}),f=qd({baseUrl:e,source:e,indexRange:n});if(f.map=d,c){const m=mT(s);m.length&&(f.duration=m[0].duration,f.timeline=m[0].timeline)}else i&&(f.duration=i,f.timeline=r);return f.presentationTime=o||r,f.number=u,[f]},gT=(s,e,t)=>{const i=s.sidx.map?s.sidx.map:null,n=s.sidx.duration,r=s.timeline||0,o=s.sidx.byterange,u=o.offset+o.length,c=e.timescale,d=e.references.filter(E=>E.referenceType!==1),f=[],m=s.endList?"static":"dynamic",g=s.sidx.timeline;let v=g,b=s.mediaSequence||0,_;typeof e.firstOffset=="bigint"?_=se.BigInt(u)+e.firstOffset:_=u+e.firstOffset;for(let E=0;ErM(s,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),dM=(s,e)=>{for(let t=0;t{let e=[];return QP(s,uM,(t,i,n,r)=>{e=e.concat(t.playlists||[])}),e},TE=({playlist:s,mediaSequence:e})=>{s.mediaSequence=e,s.segments.forEach((t,i)=>{t.number=s.mediaSequence+i})},hM=({oldPlaylists:s,newPlaylists:e,timelineStarts:t})=>{e.forEach(i=>{i.discontinuitySequence=t.findIndex(function({timeline:c}){return c===i.timeline});const n=dM(s,i.attributes.NAME);if(!n||i.sidx)return;const r=i.segments[0],o=n.segments.findIndex(function(c){return Math.abs(c.presentationTime-r.presentationTime)n.timeline||n.segments.length&&i.timeline>n.segments[n.segments.length-1].timeline)&&i.discontinuitySequence--;return}n.segments[o].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,i.discontinuityStarts.unshift(0),i.discontinuitySequence--),TE({playlist:i,mediaSequence:n.segments[o].number})})},fM=({oldManifest:s,newManifest:e})=>{const t=s.playlists.concat(vE(s)),i=e.playlists.concat(vE(e));return e.timelineStarts=VA([s.timelineStarts,e.timelineStarts]),hM({oldPlaylists:t,newPlaylists:i,timelineStarts:e.timelineStarts}),e},xm=s=>s&&s.uri+"-"+aM(s.byterange),my=s=>{const e=s.reduce(function(i,n){return i[n.attributes.baseUrl]||(i[n.attributes.baseUrl]=[]),i[n.attributes.baseUrl].push(n),i},{});let t=[];return Object.values(e).forEach(i=>{const n=jA(i.reduce((r,o)=>{const u=o.attributes.id+(o.attributes.lang||"");return r[u]?(o.segments&&(o.segments[0]&&(o.segments[0].discontinuity=!0),r[u].segments.push(...o.segments)),o.attributes.contentProtection&&(r[u].attributes.contentProtection=o.attributes.contentProtection)):(r[u]=o,r[u].attributes.timelineStarts=[]),r[u].attributes.timelineStarts.push({start:o.attributes.periodStart,timeline:o.attributes.periodStart}),r},{}));t=t.concat(n)}),t.map(i=>(i.discontinuityStarts=nM(i.segments||[],"discontinuity"),i))},yT=(s,e)=>{const t=xm(s.sidx),i=t&&e[t]&&e[t].sidx;return i&&gT(s,i,s.sidx.resolvedUri),s},pM=(s,e={})=>{if(!Object.keys(e).length)return s;for(const t in s)s[t]=yT(s[t],e);return s},mM=({attributes:s,segments:e,sidx:t,mediaSequence:i,discontinuitySequence:n,discontinuityStarts:r},o)=>{const u={attributes:{NAME:s.id,BANDWIDTH:s.bandwidth,CODECS:s.codecs,"PROGRAM-ID":1},uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,discontinuitySequence:n,discontinuityStarts:r,timelineStarts:s.timelineStarts,mediaSequence:i,segments:e};return s.contentProtection&&(u.contentProtection=s.contentProtection),s.serviceLocation&&(u.attributes.serviceLocation=s.serviceLocation),t&&(u.sidx=t),o&&(u.attributes.AUDIO="audio",u.attributes.SUBTITLES="subs"),u},gM=({attributes:s,segments:e,mediaSequence:t,discontinuityStarts:i,discontinuitySequence:n})=>{typeof e>"u"&&(e=[{uri:s.baseUrl,timeline:s.periodStart,resolvedUri:s.baseUrl||"",duration:s.sourceDuration,number:0}],s.duration=s.sourceDuration);const r={NAME:s.id,BANDWIDTH:s.bandwidth,"PROGRAM-ID":1};s.codecs&&(r.CODECS=s.codecs);const o={attributes:r,uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,timelineStarts:s.timelineStarts,discontinuityStarts:i,discontinuitySequence:n,mediaSequence:t,segments:e};return s.serviceLocation&&(o.attributes.serviceLocation=s.serviceLocation),o},yM=(s,e={},t=!1)=>{let i;const n=s.reduce((r,o)=>{const u=o.attributes.role&&o.attributes.role.value||"",c=o.attributes.lang||"";let d=o.attributes.label||"main";if(c&&!o.attributes.label){const m=u?` (${u})`:"";d=`${o.attributes.lang}${m}`}r[d]||(r[d]={language:c,autoselect:!0,default:u==="main",playlists:[],uri:""});const f=yT(mM(o,t),e);return r[d].playlists.push(f),typeof i>"u"&&u==="main"&&(i=o,i.default=!0),r},{});if(!i){const r=Object.keys(n)[0];n[r].default=!0}return n},vM=(s,e={})=>s.reduce((t,i)=>{const n=i.attributes.label||i.attributes.lang||"text",r=i.attributes.lang||"und";return t[n]||(t[n]={language:r,default:!1,autoselect:!1,playlists:[],uri:""}),t[n].playlists.push(yT(gM(i),e)),t},{}),TM=s=>s.reduce((e,t)=>(t&&t.forEach(i=>{const{channel:n,language:r}=i;e[r]={autoselect:!1,default:!1,instreamId:n,language:r},i.hasOwnProperty("aspectRatio")&&(e[r].aspectRatio=i.aspectRatio),i.hasOwnProperty("easyReader")&&(e[r].easyReader=i.easyReader),i.hasOwnProperty("3D")&&(e[r]["3D"]=i["3D"])}),e),{}),bM=({attributes:s,segments:e,sidx:t,discontinuityStarts:i})=>{const n={attributes:{NAME:s.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:s.width,height:s.height},CODECS:s.codecs,BANDWIDTH:s.bandwidth,"PROGRAM-ID":1},uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,discontinuityStarts:i,timelineStarts:s.timelineStarts,segments:e};return s.frameRate&&(n.attributes["FRAME-RATE"]=s.frameRate),s.contentProtection&&(n.contentProtection=s.contentProtection),s.serviceLocation&&(n.attributes.serviceLocation=s.serviceLocation),t&&(n.sidx=t),n},_M=({attributes:s})=>s.mimeType==="video/mp4"||s.mimeType==="video/webm"||s.contentType==="video",xM=({attributes:s})=>s.mimeType==="audio/mp4"||s.mimeType==="audio/webm"||s.contentType==="audio",SM=({attributes:s})=>s.mimeType==="text/vtt"||s.contentType==="text",EM=(s,e)=>{s.forEach(t=>{t.mediaSequence=0,t.discontinuitySequence=e.findIndex(function({timeline:i}){return i===t.timeline}),t.segments&&t.segments.forEach((i,n)=>{i.number=n})})},bE=s=>s?Object.keys(s).reduce((e,t)=>{const i=s[t];return e.concat(i.playlists)},[]):[],AM=({dashPlaylists:s,locations:e,contentSteering:t,sidxMapping:i={},previousManifest:n,eventStream:r})=>{if(!s.length)return{};const{sourceDuration:o,type:u,suggestedPresentationDelay:c,minimumUpdatePeriod:d}=s[0].attributes,f=my(s.filter(_M)).map(bM),m=my(s.filter(xM)),g=my(s.filter(SM)),v=s.map(F=>F.attributes.captionServices).filter(Boolean),b={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:o,playlists:pM(f,i)};d>=0&&(b.minimumUpdatePeriod=d*1e3),e&&(b.locations=e),t&&(b.contentSteering=t),u==="dynamic"&&(b.suggestedPresentationDelay=c),r&&r.length>0&&(b.eventStream=r);const _=b.playlists.length===0,E=m.length?yM(m,i,_):null,L=g.length?vM(g,i):null,I=f.concat(bE(E),bE(L)),w=I.map(({timelineStarts:F})=>F);return b.timelineStarts=VA(w),EM(I,b.timelineStarts),E&&(b.mediaGroups.AUDIO.audio=E),L&&(b.mediaGroups.SUBTITLES.subs=L),v.length&&(b.mediaGroups["CLOSED-CAPTIONS"].cc=TM(v)),n?fM({oldManifest:n,newManifest:b}):b},CM=(s,e,t)=>{const{NOW:i,clientOffset:n,availabilityStartTime:r,timescale:o=1,periodStart:u=0,minimumUpdatePeriod:c=0}=s,d=(i+n)/1e3,f=r+u,g=d+c-f;return Math.ceil((g*o-e)/t)},qA=(s,e)=>{const{type:t,minimumUpdatePeriod:i=0,media:n="",sourceDuration:r,timescale:o=1,startNumber:u=1,periodStart:c}=s,d=[];let f=-1;for(let m=0;mf&&(f=_);let E;if(b<0){const w=m+1;w===e.length?t==="dynamic"&&i>0&&n.indexOf("$Number$")>0?E=CM(s,f,v):E=(r*o-f)/v:E=(e[w].t-f)/v}else E=b+1;const L=u+d.length+E;let I=u+d.length;for(;I(e,t,i,n)=>{if(e==="$$")return"$";if(typeof s[t]>"u")return e;const r=""+s[t];return t==="RepresentationID"||(i?n=parseInt(n,10):n=1,r.length>=n)?r:`${new Array(n-r.length+1).join("0")}${r}`},_E=(s,e)=>s.replace(DM,wM(e)),LM=(s,e)=>!s.duration&&!e?[{number:s.startNumber||1,duration:s.sourceDuration,time:0,timeline:s.periodStart}]:s.duration?mT(s):qA(s,e),IM=(s,e)=>{const t={RepresentationID:s.id,Bandwidth:s.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=s,n=qd({baseUrl:s.baseUrl,source:_E(i.sourceURL,t),range:i.range});return LM(s,e).map(o=>{t.Number=o.number,t.Time=o.time;const u=_E(s.media||"",t),c=s.timescale||1,d=s.presentationTimeOffset||0,f=s.periodStart+(o.time-d)/c;return{uri:u,timeline:o.timeline,duration:o.duration,resolvedUri:bm(s.baseUrl||"",u),map:n,number:o.number,presentationTime:f}})},kM=(s,e)=>{const{baseUrl:t,initialization:i={}}=s,n=qd({baseUrl:t,source:i.sourceURL,range:i.range}),r=qd({baseUrl:t,source:e.media,range:e.mediaRange});return r.map=n,r},RM=(s,e)=>{const{duration:t,segmentUrls:i=[],periodStart:n}=s;if(!t&&!e||t&&e)throw new Error(Zu.SEGMENT_TIME_UNSPECIFIED);const r=i.map(c=>kM(s,c));let o;return t&&(o=mT(s)),e&&(o=qA(s,e)),o.map((c,d)=>{if(r[d]){const f=r[d],m=s.timescale||1,g=s.presentationTimeOffset||0;return f.timeline=c.timeline,f.duration=c.duration,f.number=c.number,f.presentationTime=n+(c.time-g)/m,f}}).filter(c=>c)},OM=({attributes:s,segmentInfo:e})=>{let t,i;e.template?(i=IM,t=cs(s,e.template)):e.base?(i=GA,t=cs(s,e.base)):e.list&&(i=RM,t=cs(s,e.list));const n={attributes:s};if(!i)return n;const r=i(t,e.segmentTimeline);if(t.duration){const{duration:o,timescale:u=1}=t;t.duration=o/u}else r.length?t.duration=r.reduce((o,u)=>Math.max(o,Math.ceil(u.duration)),0):t.duration=0;return n.attributes=t,n.segments=r,e.base&&t.indexRange&&(n.sidx=r[0],n.segments=[]),n},PM=s=>s.map(OM),yi=(s,e)=>HA(s.childNodes).filter(({tagName:t})=>t===e),oh=s=>s.textContent.trim(),MM=s=>parseFloat(s.split("/").reduce((e,t)=>e/t)),bu=s=>{const u=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(s);if(!u)return 0;const[c,d,f,m,g,v]=u.slice(1);return parseFloat(c||0)*31536e3+parseFloat(d||0)*2592e3+parseFloat(f||0)*86400+parseFloat(m||0)*3600+parseFloat(g||0)*60+parseFloat(v||0)},NM=s=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(s)&&(s+="Z"),Date.parse(s)),xE={mediaPresentationDuration(s){return bu(s)},availabilityStartTime(s){return NM(s)/1e3},minimumUpdatePeriod(s){return bu(s)},suggestedPresentationDelay(s){return bu(s)},type(s){return s},timeShiftBufferDepth(s){return bu(s)},start(s){return bu(s)},width(s){return parseInt(s,10)},height(s){return parseInt(s,10)},bandwidth(s){return parseInt(s,10)},frameRate(s){return MM(s)},startNumber(s){return parseInt(s,10)},timescale(s){return parseInt(s,10)},presentationTimeOffset(s){return parseInt(s,10)},duration(s){const e=parseInt(s,10);return isNaN(e)?bu(s):e},d(s){return parseInt(s,10)},t(s){return parseInt(s,10)},r(s){return parseInt(s,10)},presentationTime(s){return parseInt(s,10)},DEFAULT(s){return s}},Ki=s=>s&&s.attributes?HA(s.attributes).reduce((e,t)=>{const i=xE[t.name]||xE.DEFAULT;return e[t.name]=i(t.value),e},{}):{},BM={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime","urn:mpeg:dash:mp4protection:2011":"mp4protection"},Sm=(s,e)=>e.length?Qu(s.map(function(t){return e.map(function(i){const n=oh(i),r=bm(t.baseUrl,n),o=cs(Ki(i),{baseUrl:r});return r!==n&&!o.serviceLocation&&t.serviceLocation&&(o.serviceLocation=t.serviceLocation),o})})):s,vT=s=>{const e=yi(s,"SegmentTemplate")[0],t=yi(s,"SegmentList")[0],i=t&&yi(t,"SegmentURL").map(m=>cs({tag:"SegmentURL"},Ki(m))),n=yi(s,"SegmentBase")[0],r=t||e,o=r&&yi(r,"SegmentTimeline")[0],u=t||n||e,c=u&&yi(u,"Initialization")[0],d=e&&Ki(e);d&&c?d.initialization=c&&Ki(c):d&&d.initialization&&(d.initialization={sourceURL:d.initialization});const f={template:d,segmentTimeline:o&&yi(o,"S").map(m=>Ki(m)),list:t&&cs(Ki(t),{segmentUrls:i,initialization:Ki(c)}),base:n&&cs(Ki(n),{initialization:Ki(c)})};return Object.keys(f).forEach(m=>{f[m]||delete f[m]}),f},FM=(s,e,t)=>i=>{const n=yi(i,"BaseURL"),r=Sm(e,n),o=cs(s,Ki(i)),u=vT(i);return r.map(c=>({segmentInfo:cs(t,u),attributes:cs(o,c)}))},UM=s=>s.reduce((e,t)=>{const i=Ki(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=BM[i.schemeIdUri];if(n){e[n]={attributes:i};const r=yi(t,"cenc:pssh")[0];if(r){const o=oh(r);e[n].pssh=o&&PA(o)}}return e},{}),$M=s=>{if(s.schemeIdUri==="urn:scte:dash:cc:cea-608:2015")return(typeof s.value!="string"?[]:s.value.split(";")).map(t=>{let i,n;return n=t,/^CC\d=/.test(t)?[i,n]=t.split("="):/^CC\d$/.test(t)&&(i=t),{channel:i,language:n}});if(s.schemeIdUri==="urn:scte:dash:cc:cea-708:2015")return(typeof s.value!="string"?[]:s.value.split(";")).map(t=>{const i={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(t)){const[n,r=""]=t.split("=");i.channel=n,i.language=t,r.split(",").forEach(o=>{const[u,c]=o.split(":");u==="lang"?i.language=c:u==="er"?i.easyReader=Number(c):u==="war"?i.aspectRatio=Number(c):u==="3D"&&(i["3D"]=Number(c))})}else i.language=t;return i.channel&&(i.channel="SERVICE"+i.channel),i})},jM=s=>Qu(yi(s.node,"EventStream").map(e=>{const t=Ki(e),i=t.schemeIdUri;return yi(e,"Event").map(n=>{const r=Ki(n),o=r.presentationTime||0,u=t.timescale||1,c=r.duration||0,d=o/u+s.attributes.start;return{schemeIdUri:i,value:t.value,id:r.id,start:d,end:d+c/u,messageData:oh(n)||r.messageData,contentEncoding:t.contentEncoding,presentationTimeOffset:t.presentationTimeOffset||0}})})),HM=(s,e,t)=>i=>{const n=Ki(i),r=Sm(e,yi(i,"BaseURL")),o=yi(i,"Role")[0],u={role:Ki(o)};let c=cs(s,n,u);const d=yi(i,"Accessibility")[0],f=$M(Ki(d));f&&(c=cs(c,{captionServices:f}));const m=yi(i,"Label")[0];if(m&&m.childNodes.length){const E=m.childNodes[0].nodeValue.trim();c=cs(c,{label:E})}const g=UM(yi(i,"ContentProtection"));Object.keys(g).length&&(c=cs(c,{contentProtection:g}));const v=vT(i),b=yi(i,"Representation"),_=cs(t,v);return Qu(b.map(FM(c,r,_)))},GM=(s,e)=>(t,i)=>{const n=Sm(e,yi(t.node,"BaseURL")),r=cs(s,{periodStart:t.attributes.start});typeof t.attributes.duration=="number"&&(r.periodDuration=t.attributes.duration);const o=yi(t.node,"AdaptationSet"),u=vT(t.node);return Qu(o.map(HM(r,n,u)))},VM=(s,e)=>{if(s.length>1&&e({type:"warn",message:"The MPD manifest should contain no more than one ContentSteering tag"}),!s.length)return null;const t=cs({serverURL:oh(s[0])},Ki(s[0]));return t.queryBeforeStart=t.queryBeforeStart==="true",t},qM=({attributes:s,priorPeriodAttributes:e,mpdType:t})=>typeof s.start=="number"?s.start:e&&typeof e.start=="number"&&typeof e.duration=="number"?e.start+e.duration:!e&&t==="static"?0:null,zM=(s,e={})=>{const{manifestUri:t="",NOW:i=Date.now(),clientOffset:n=0,eventHandler:r=function(){}}=e,o=yi(s,"Period");if(!o.length)throw new Error(Zu.INVALID_NUMBER_OF_PERIOD);const u=yi(s,"Location"),c=Ki(s),d=Sm([{baseUrl:t}],yi(s,"BaseURL")),f=yi(s,"ContentSteering");c.type=c.type||"static",c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=i,c.clientOffset=n,u.length&&(c.locations=u.map(oh));const m=[];return o.forEach((g,v)=>{const b=Ki(g),_=m[v-1];b.start=qM({attributes:b,priorPeriodAttributes:_?_.attributes:null,mpdType:c.type}),m.push({node:g,attributes:b})}),{locations:c.locations,contentSteeringInfo:VM(f,r),representationInfo:Qu(m.map(GM(c,d))),eventStream:Qu(m.map(jM))}},zA=s=>{if(s==="")throw new Error(Zu.DASH_EMPTY_MANIFEST);const e=new iM.DOMParser;let t,i;try{t=e.parseFromString(s,"application/xml"),i=t&&t.documentElement.tagName==="MPD"?t.documentElement:null}catch{}if(!i||i&&i.getElementsByTagName("parsererror").length>0)throw new Error(Zu.DASH_INVALID_XML);return i},KM=s=>{const e=yi(s,"UTCTiming")[0];if(!e)return null;const t=Ki(e);switch(t.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":t.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":t.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":t.method="DIRECT",t.value=Date.parse(t.value);break;default:throw new Error(Zu.UNSUPPORTED_UTC_TIMING_SCHEME)}return t},YM=(s,e={})=>{const t=zM(zA(s),e),i=PM(t.representationInfo);return AM({dashPlaylists:i,locations:t.locations,contentSteering:t.contentSteeringInfo,sidxMapping:e.sidxMapping,previousManifest:e.previousManifest,eventStream:t.eventStream})},WM=s=>KM(zA(s));var gy,SE;function XM(){if(SE)return gy;SE=1;var s=Math.pow(2,32),e=function(t){var i=new DataView(t.buffer,t.byteOffset,t.byteLength),n;return i.getBigUint64?(n=i.getBigUint64(0),n0;r+=12,o--)n.references.push({referenceType:(t[r]&128)>>>7,referencedSize:i.getUint32(r)&2147483647,subsegmentDuration:i.getUint32(r+4),startsWithSap:!!(t[r+8]&128),sapType:(t[r+8]&112)>>>4,sapDeltaTime:i.getUint32(r+8)&268435455});return n};return yy=e,yy}var ZM=QM();const JM=oc(ZM);var eN=dt([73,68,51]),tN=function(e,t){t===void 0&&(t=0),e=dt(e);var i=e[t+5],n=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9],r=(i&16)>>4;return r?n+20:n+10},wd=function s(e,t){return t===void 0&&(t=0),e=dt(e),e.length-t<10||!gi(e,eN,{offset:t})?t:(t+=tN(e,t),s(e,t))},AE=function(e){return typeof e=="string"?UA(e):e},iN=function(e){return Array.isArray(e)?e.map(function(t){return AE(t)}):[AE(e)]},sN=function s(e,t,i){i===void 0&&(i=!1),t=iN(t),e=dt(e);var n=[];if(!t.length)return n;for(var r=0;r>>0,u=e.subarray(r+4,r+8);if(o===0)break;var c=r+o;if(c>e.length){if(i)break;c=e.length}var d=e.subarray(r+8,c);gi(u,t[0])&&(t.length===1?n.push(d):n.push.apply(n,s(d,t.slice(1),i))),r=c}return n},zf={EBML:dt([26,69,223,163]),DocType:dt([66,130]),Segment:dt([24,83,128,103]),SegmentInfo:dt([21,73,169,102]),Tracks:dt([22,84,174,107]),Track:dt([174]),TrackNumber:dt([215]),DefaultDuration:dt([35,227,131]),TrackEntry:dt([174]),TrackType:dt([131]),FlagDefault:dt([136]),CodecID:dt([134]),CodecPrivate:dt([99,162]),VideoTrack:dt([224]),AudioTrack:dt([225]),Cluster:dt([31,67,182,117]),Timestamp:dt([231]),TimestampScale:dt([42,215,177]),BlockGroup:dt([160]),BlockDuration:dt([155]),Block:dt([161]),SimpleBlock:dt([163])},gv=[128,64,32,16,8,4,2,1],nN=function(e){for(var t=1,i=0;i=t.length)return t.length;var n=kp(t,i,!1);if(gi(e.bytes,n.bytes))return i;var r=kp(t,i+n.length);return s(e,t,i+r.length+r.value+n.length)},DE=function s(e,t){t=rN(t),e=dt(e);var i=[];if(!t.length)return i;for(var n=0;ne.length?e.length:u+o.value,d=e.subarray(u,c);gi(t[0],r.bytes)&&(t.length===1?i.push(d):i=i.concat(s(d,t.slice(1))));var f=r.length+o.length+d.length;n+=f}return i},oN=dt([0,0,0,1]),lN=dt([0,0,1]),uN=dt([0,0,3]),cN=function(e){for(var t=[],i=1;i>1&63),i.indexOf(d)!==-1&&(o=r+c),r+=c+(t==="h264"?1:2)}return e.subarray(0,0)},dN=function(e,t,i){return KA(e,"h264",t,i)},hN=function(e,t,i){return KA(e,"h265",t,i)},Ms={webm:dt([119,101,98,109]),matroska:dt([109,97,116,114,111,115,107,97]),flac:dt([102,76,97,67]),ogg:dt([79,103,103,83]),ac3:dt([11,119]),riff:dt([82,73,70,70]),avi:dt([65,86,73]),wav:dt([87,65,86,69]),"3gp":dt([102,116,121,112,51,103]),mp4:dt([102,116,121,112]),fmp4:dt([115,116,121,112]),mov:dt([102,116,121,112,113,116]),moov:dt([109,111,111,118]),moof:dt([109,111,111,102])},Ju={aac:function(e){var t=wd(e);return gi(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=wd(e);return gi(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=DE(e,[zf.EBML,zf.DocType])[0];return gi(t,Ms.webm)},mkv:function(e){var t=DE(e,[zf.EBML,zf.DocType])[0];return gi(t,Ms.matroska)},mp4:function(e){if(Ju["3gp"](e)||Ju.mov(e))return!1;if(gi(e,Ms.mp4,{offset:4})||gi(e,Ms.fmp4,{offset:4})||gi(e,Ms.moof,{offset:4})||gi(e,Ms.moov,{offset:4}))return!0},mov:function(e){return gi(e,Ms.mov,{offset:4})},"3gp":function(e){return gi(e,Ms["3gp"],{offset:4})},ac3:function(e){var t=wd(e);return gi(e,Ms.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+1880},vy,wE;function mN(){if(wE)return vy;wE=1;var s=9e4,e,t,i,n,r,o,u;return e=function(c){return c*s},t=function(c,d){return c*d},i=function(c){return c/s},n=function(c,d){return c/d},r=function(c,d){return e(n(c,d))},o=function(c,d){return t(i(c),d)},u=function(c,d,f){return i(f?c:c-d)},vy={ONE_SECOND_IN_TS:s,secondsToVideoTs:e,secondsToAudioTs:t,videoTsToSeconds:i,audioTsToSeconds:n,audioTsToVideoTs:r,videoTsToAudioTs:o,metadataTsToSeconds:u},vy}var ml=mN();var vv="8.23.4";const ma={},xo=function(s,e){return ma[s]=ma[s]||[],e&&(ma[s]=ma[s].concat(e)),ma[s]},gN=function(s,e){xo(s,e)},YA=function(s,e){const t=xo(s).indexOf(e);return t<=-1?!1:(ma[s]=ma[s].slice(),ma[s].splice(t,1),!0)},yN=function(s,e){xo(s,[].concat(e).map(t=>{const i=(...n)=>(YA(s,i),t(...n));return i}))},Rp={prefixed:!0},gp=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],LE=gp[0];let Ld;for(let s=0;s(i,n,r)=>{const o=e.levels[n],u=new RegExp(`^(${o})$`);let c=s;if(i!=="log"&&r.unshift(i.toUpperCase()+":"),t&&(c=`%c${s}`,r.unshift(t)),r.unshift(c+":"),Js){Js.push([].concat(r));const f=Js.length-1e3;Js.splice(0,f>0?f:0)}if(!se.console)return;let d=se.console[i];!d&&i==="debug"&&(d=se.console.info||se.console.log),!(!d||!o||!u.test(i))&&d[Array.isArray(r)?"apply":"call"](se.console,r)};function Tv(s,e=":",t=""){let i="info",n;function r(...o){n("log",i,o)}return n=vN(s,r,t),r.createLogger=(o,u,c)=>{const d=u!==void 0?u:e,f=c!==void 0?c:t,m=`${s} ${d} ${o}`;return Tv(m,d,f)},r.createNewLogger=(o,u,c)=>Tv(o,u,c),r.levels={all:"debug|log|warn|error",off:"",debug:"debug|log|warn|error",info:"log|warn|error",warn:"warn|error",error:"error",DEFAULT:i},r.level=o=>{if(typeof o=="string"){if(!r.levels.hasOwnProperty(o))throw new Error(`"${o}" in not a valid log level`);i=o}return i},r.history=()=>Js?[].concat(Js):[],r.history.filter=o=>(Js||[]).filter(u=>new RegExp(`.*${o}.*`).test(u[0])),r.history.clear=()=>{Js&&(Js.length=0)},r.history.disable=()=>{Js!==null&&(Js.length=0,Js=null)},r.history.enable=()=>{Js===null&&(Js=[])},r.error=(...o)=>n("error",i,o),r.warn=(...o)=>n("warn",i,o),r.debug=(...o)=>n("debug",i,o),r}const It=Tv("VIDEOJS"),WA=It.createLogger,TN=Object.prototype.toString,XA=function(s){return Mr(s)?Object.keys(s):[]};function Bu(s,e){XA(s).forEach(t=>e(s[t],t))}function QA(s,e,t=0){return XA(s).reduce((i,n)=>e(i,s[n],n),t)}function Mr(s){return!!s&&typeof s=="object"}function ec(s){return Mr(s)&&TN.call(s)==="[object Object]"&&s.constructor===Object}function si(...s){const e={};return s.forEach(t=>{t&&Bu(t,(i,n)=>{if(!ec(i)){e[n]=i;return}ec(e[n])||(e[n]={}),e[n]=si(e[n],i)})}),e}function ZA(s={}){const e=[];for(const t in s)if(s.hasOwnProperty(t)){const i=s[t];e.push(i)}return e}function Em(s,e,t,i=!0){const n=o=>Object.defineProperty(s,e,{value:o,enumerable:!0,writable:!0}),r={configurable:!0,enumerable:!0,get(){const o=t();return n(o),o}};return i&&(r.set=n),Object.defineProperty(s,e,r)}var bN=Object.freeze({__proto__:null,each:Bu,reduce:QA,isObject:Mr,isPlain:ec,merge:si,values:ZA,defineLazyProperty:Em});let bT=!1,JA=null,ir=!1,eC,tC=!1,Fu=!1,Uu=!1,Nr=!1,_T=null,Am=null;const _N=!!(se.cast&&se.cast.framework&&se.cast.framework.CastReceiverContext);let iC=null,Op=!1,Cm=!1,Pp=!1,Dm=!1,Mp=!1,Np=!1,Bp=!1;const zd=!!(lc()&&("ontouchstart"in se||se.navigator.maxTouchPoints||se.DocumentTouch&&se.document instanceof se.DocumentTouch)),oo=se.navigator&&se.navigator.userAgentData;oo&&oo.platform&&oo.brands&&(ir=oo.platform==="Android",Fu=!!oo.brands.find(s=>s.brand==="Microsoft Edge"),Uu=!!oo.brands.find(s=>s.brand==="Chromium"),Nr=!Fu&&Uu,_T=Am=(oo.brands.find(s=>s.brand==="Chromium")||{}).version||null,Cm=oo.platform==="Windows");if(!Uu){const s=se.navigator&&se.navigator.userAgent||"";bT=/iPod/i.test(s),JA=(function(){const e=s.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null})(),ir=/Android/i.test(s),eC=(function(){const e=s.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);return t&&i?parseFloat(e[1]+"."+e[2]):t||null})(),tC=/Firefox/i.test(s),Fu=/Edg/i.test(s),Uu=/Chrome/i.test(s)||/CriOS/i.test(s),Nr=!Fu&&Uu,_T=Am=(function(){const e=s.match(/(Chrome|CriOS)\/(\d+)/);return e&&e[2]?parseFloat(e[2]):null})(),iC=(function(){const e=/MSIE\s(\d+)\.\d/.exec(s);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(s)&&/rv:11.0/.test(s)&&(t=11),t})(),Mp=/Tizen/i.test(s),Np=/Web0S/i.test(s),Bp=Mp||Np,Op=/Safari/i.test(s)&&!Nr&&!ir&&!Fu&&!Bp,Cm=/Windows/i.test(s),Pp=/iPad/i.test(s)||Op&&zd&&!/iPhone/i.test(s),Dm=/iPhone/i.test(s)&&!Pp}const Cs=Dm||Pp||bT,wm=(Op||Cs)&&!Nr;var sC=Object.freeze({__proto__:null,get IS_IPOD(){return bT},get IOS_VERSION(){return JA},get IS_ANDROID(){return ir},get ANDROID_VERSION(){return eC},get IS_FIREFOX(){return tC},get IS_EDGE(){return Fu},get IS_CHROMIUM(){return Uu},get IS_CHROME(){return Nr},get CHROMIUM_VERSION(){return _T},get CHROME_VERSION(){return Am},IS_CHROMECAST_RECEIVER:_N,get IE_VERSION(){return iC},get IS_SAFARI(){return Op},get IS_WINDOWS(){return Cm},get IS_IPAD(){return Pp},get IS_IPHONE(){return Dm},get IS_TIZEN(){return Mp},get IS_WEBOS(){return Np},get IS_SMART_TV(){return Bp},TOUCH_ENABLED:zd,IS_IOS:Cs,IS_ANY_SAFARI:wm});function IE(s){return typeof s=="string"&&!!s.trim()}function xN(s){if(s.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function lc(){return qe===se.document}function uc(s){return Mr(s)&&s.nodeType===1}function nC(){try{return se.parent!==se.self}catch{return!0}}function rC(s){return function(e,t){if(!IE(e))return qe[s](null);IE(t)&&(t=qe.querySelector(t));const i=uc(t)?t:qe;return i[s]&&i[s](e)}}function gt(s="div",e={},t={},i){const n=qe.createElement(s);return Object.getOwnPropertyNames(e).forEach(function(r){const o=e[r];r==="textContent"?Co(n,o):(n[r]!==o||r==="tabIndex")&&(n[r]=o)}),Object.getOwnPropertyNames(t).forEach(function(r){n.setAttribute(r,t[r])}),i&&xT(n,i),n}function Co(s,e){return typeof s.textContent>"u"?s.innerText=e:s.textContent=e,s}function bv(s,e){e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)}function Bd(s,e){return xN(e),s.classList.contains(e)}function vl(s,...e){return s.classList.add(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s}function Lm(s,...e){return s?(s.classList.remove(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s):(It.warn("removeClass was called with an element that doesn't exist"),null)}function aC(s,e,t){return typeof t=="function"&&(t=t(s,e)),typeof t!="boolean"&&(t=void 0),e.split(/\s+/).forEach(i=>s.classList.toggle(i,t)),s}function oC(s,e){Object.getOwnPropertyNames(e).forEach(function(t){const i=e[t];i===null||typeof i>"u"||i===!1?s.removeAttribute(t):s.setAttribute(t,i===!0?"":i)})}function fo(s){const e={},t=["autoplay","controls","playsinline","loop","muted","default","defaultMuted"];if(s&&s.attributes&&s.attributes.length>0){const i=s.attributes;for(let n=i.length-1;n>=0;n--){const r=i[n].name;let o=i[n].value;t.includes(r)&&(o=o!==null),e[r]=o}}return e}function lC(s,e){return s.getAttribute(e)}function tc(s,e,t){s.setAttribute(e,t)}function Im(s,e){s.removeAttribute(e)}function uC(){qe.body.focus(),qe.onselectstart=function(){return!1}}function cC(){qe.onselectstart=function(){return!0}}function ic(s){if(s&&s.getBoundingClientRect&&s.parentNode){const e=s.getBoundingClientRect(),t={};return["bottom","height","left","right","top","width"].forEach(i=>{e[i]!==void 0&&(t[i]=e[i])}),t.height||(t.height=parseFloat(sc(s,"height"))),t.width||(t.width=parseFloat(sc(s,"width"))),t}}function Kd(s){if(!s||s&&!s.offsetParent)return{left:0,top:0,width:0,height:0};const e=s.offsetWidth,t=s.offsetHeight;let i=0,n=0;for(;s.offsetParent&&s!==qe[Rp.fullscreenElement];)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;return{left:i,top:n,width:e,height:t}}function km(s,e){const t={x:0,y:0};if(Cs){let f=s;for(;f&&f.nodeName.toLowerCase()!=="html";){const m=sc(f,"transform");if(/^matrix/.test(m)){const g=m.slice(7,-1).split(/,\s/).map(Number);t.x+=g[4],t.y+=g[5]}else if(/^matrix3d/.test(m)){const g=m.slice(9,-1).split(/,\s/).map(Number);t.x+=g[12],t.y+=g[13]}if(f.assignedSlot&&f.assignedSlot.parentElement&&se.WebKitCSSMatrix){const g=se.getComputedStyle(f.assignedSlot.parentElement).transform,v=new se.WebKitCSSMatrix(g);t.x+=v.m41,t.y+=v.m42}f=f.parentNode||f.host}}const i={},n=Kd(e.target),r=Kd(s),o=r.width,u=r.height;let c=e.offsetY-(r.top-n.top),d=e.offsetX-(r.left-n.left);return e.changedTouches&&(d=e.changedTouches[0].pageX-r.left,c=e.changedTouches[0].pageY+r.top,Cs&&(d-=t.x,c-=t.y)),i.y=1-Math.max(0,Math.min(1,c/u)),i.x=Math.max(0,Math.min(1,d/o)),i}function dC(s){return Mr(s)&&s.nodeType===3}function Rm(s){for(;s.firstChild;)s.removeChild(s.firstChild);return s}function hC(s){return typeof s=="function"&&(s=s()),(Array.isArray(s)?s:[s]).map(e=>{if(typeof e=="function"&&(e=e()),uc(e)||dC(e))return e;if(typeof e=="string"&&/\S/.test(e))return qe.createTextNode(e)}).filter(e=>e)}function xT(s,e){return hC(e).forEach(t=>s.appendChild(t)),s}function fC(s,e){return xT(Rm(s),e)}function Yd(s){return s.button===void 0&&s.buttons===void 0||s.button===0&&s.buttons===void 0||s.type==="mouseup"&&s.button===0&&s.buttons===0||s.type==="mousedown"&&s.button===0&&s.buttons===0?!0:!(s.button!==0||s.buttons!==1)}const So=rC("querySelector"),pC=rC("querySelectorAll");function sc(s,e){if(!s||!e)return"";if(typeof se.getComputedStyle=="function"){let t;try{t=se.getComputedStyle(s)}catch{return""}return t?t.getPropertyValue(e)||t[e]:""}return""}function mC(s){[...qe.styleSheets].forEach(e=>{try{const t=[...e.cssRules].map(n=>n.cssText).join(""),i=qe.createElement("style");i.textContent=t,s.document.head.appendChild(i)}catch{const i=qe.createElement("link");i.rel="stylesheet",i.type=e.type,i.media=e.media.mediaText,i.href=e.href,s.document.head.appendChild(i)}})}var gC=Object.freeze({__proto__:null,isReal:lc,isEl:uc,isInFrame:nC,createEl:gt,textContent:Co,prependTo:bv,hasClass:Bd,addClass:vl,removeClass:Lm,toggleClass:aC,setAttributes:oC,getAttributes:fo,getAttribute:lC,setAttribute:tc,removeAttribute:Im,blockTextSelection:uC,unblockTextSelection:cC,getBoundingClientRect:ic,findPosition:Kd,getPointerPosition:km,isTextNode:dC,emptyEl:Rm,normalizeContent:hC,appendContent:xT,insertContent:fC,isSingleLeftClick:Yd,$:So,$$:pC,computedStyle:sc,copyStyleSheetsToWindow:mC});let yC=!1,_v;const SN=function(){if(_v.options.autoSetup===!1)return;const s=Array.prototype.slice.call(qe.getElementsByTagName("video")),e=Array.prototype.slice.call(qe.getElementsByTagName("audio")),t=Array.prototype.slice.call(qe.getElementsByTagName("video-js")),i=s.concat(e,t);if(i&&i.length>0)for(let n=0,r=i.length;n-1&&(n={passive:!0}),s.addEventListener(e,i.dispatcher,n)}else s.attachEvent&&s.attachEvent("on"+e,i.dispatcher)}function Ds(s,e,t){if(!Bs.has(s))return;const i=Bs.get(s);if(!i.handlers)return;if(Array.isArray(e))return ST(Ds,s,e,t);const n=function(o,u){i.handlers[u]=[],kE(o,u)};if(e===void 0){for(const o in i.handlers)Object.prototype.hasOwnProperty.call(i.handlers||{},o)&&n(s,o);return}const r=i.handlers[e];if(r){if(!t){n(s,e);return}if(t.guid)for(let o=0;o=e&&(s(...n),t=r)}},bC=function(s,e,t,i=se){let n;const r=()=>{i.clearTimeout(n),n=null},o=function(){const u=this,c=arguments;let d=function(){n=null,d=null,t||s.apply(u,c)};!n&&t&&s.apply(u,c),i.clearTimeout(n),n=i.setTimeout(d,e)};return o.cancel=r,o};var LN=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:Bn,bind_:di,throttle:Br,debounce:bC});let _d;class An{on(e,t){const i=this.addEventListener;this.addEventListener=()=>{},En(this,e,t),this.addEventListener=i}off(e,t){Ds(this,e,t)}one(e,t){const i=this.addEventListener;this.addEventListener=()=>{},Pm(this,e,t),this.addEventListener=i}any(e,t){const i=this.addEventListener;this.addEventListener=()=>{},ET(this,e,t),this.addEventListener=i}trigger(e){const t=e.type||e;typeof e=="string"&&(e={type:t}),e=Om(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),cc(this,e)}queueTrigger(e){_d||(_d=new Map);const t=e.type||e;let i=_d.get(this);i||(i=new Map,_d.set(this,i));const n=i.get(t);i.delete(t),se.clearTimeout(n);const r=se.setTimeout(()=>{i.delete(t),i.size===0&&(i=null,_d.delete(this)),this.trigger(e)},0);i.set(t,r)}}An.prototype.allowedEvents_={};An.prototype.addEventListener=An.prototype.on;An.prototype.removeEventListener=An.prototype.off;An.prototype.dispatchEvent=An.prototype.trigger;const Mm=s=>typeof s.name=="function"?s.name():typeof s.name=="string"?s.name:s.name_?s.name_:s.constructor&&s.constructor.name?s.constructor.name:typeof s,va=s=>s instanceof An||!!s.eventBusEl_&&["on","one","off","trigger"].every(e=>typeof s[e]=="function"),IN=(s,e)=>{va(s)?e():(s.eventedCallbacks||(s.eventedCallbacks=[]),s.eventedCallbacks.push(e))},Ev=s=>typeof s=="string"&&/\S/.test(s)||Array.isArray(s)&&!!s.length,Fp=(s,e,t)=>{if(!s||!s.nodeName&&!va(s))throw new Error(`Invalid target for ${Mm(e)}#${t}; must be a DOM node or evented object.`)},_C=(s,e,t)=>{if(!Ev(s))throw new Error(`Invalid event type for ${Mm(e)}#${t}; must be a non-empty string or array.`)},xC=(s,e,t)=>{if(typeof s!="function")throw new Error(`Invalid listener for ${Mm(e)}#${t}; must be a function.`)},Ty=(s,e,t)=>{const i=e.length<3||e[0]===s||e[0]===s.eventBusEl_;let n,r,o;return i?(n=s.eventBusEl_,e.length>=3&&e.shift(),[r,o]=e):(n=e[0],r=e[1],o=e[2]),Fp(n,s,t),_C(r,s,t),xC(o,s,t),o=di(s,o),{isTargetingSelf:i,target:n,type:r,listener:o}},rl=(s,e,t,i)=>{Fp(s,s,e),s.nodeName?wN[e](s,t,i):s[e](t,i)},kN={on(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Ty(this,s,"on");if(rl(t,"on",i,n),!e){const r=()=>this.off(t,i,n);r.guid=n.guid;const o=()=>this.off("dispose",r);o.guid=n.guid,rl(this,"on","dispose",r),rl(t,"on","dispose",o)}},one(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Ty(this,s,"one");if(e)rl(t,"one",i,n);else{const r=(...o)=>{this.off(t,i,r),n.apply(null,o)};r.guid=n.guid,rl(t,"one",i,r)}},any(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Ty(this,s,"any");if(e)rl(t,"any",i,n);else{const r=(...o)=>{this.off(t,i,r),n.apply(null,o)};r.guid=n.guid,rl(t,"any",i,r)}},off(s,e,t){if(!s||Ev(s))Ds(this.eventBusEl_,s,e);else{const i=s,n=e;Fp(i,this,"off"),_C(n,this,"off"),xC(t,this,"off"),t=di(this,t),this.off("dispose",t),i.nodeName?(Ds(i,n,t),Ds(i,"dispose",t)):va(i)&&(i.off(n,t),i.off("dispose",t))}},trigger(s,e){Fp(this.eventBusEl_,this,"trigger");const t=s&&typeof s!="string"?s.type:s;if(!Ev(t))throw new Error(`Invalid event type for ${Mm(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return cc(this.eventBusEl_,s,e)}};function AT(s,e={}){const{eventBusKey:t}=e;if(t){if(!s[t].nodeName)throw new Error(`The eventBusKey "${t}" does not refer to an element.`);s.eventBusEl_=s[t]}else s.eventBusEl_=gt("span",{className:"vjs-event-bus"});return Object.assign(s,kN),s.eventedCallbacks&&s.eventedCallbacks.forEach(i=>{i()}),s.on("dispose",()=>{s.off(),[s,s.el_,s.eventBusEl_].forEach(function(i){i&&Bs.has(i)&&Bs.delete(i)}),se.setTimeout(()=>{s.eventBusEl_=null},0)}),s}const RN={state:{},setState(s){typeof s=="function"&&(s=s());let e;return Bu(s,(t,i)=>{this.state[i]!==t&&(e=e||{},e[i]={from:this.state[i],to:t}),this.state[i]=t}),e&&va(this)&&this.trigger({changes:e,type:"statechanged"}),e}};function SC(s,e){return Object.assign(s,RN),s.state=Object.assign({},s.state,e),typeof s.handleStateChanged=="function"&&va(s)&&s.on("statechanged",s.handleStateChanged),s}const Fd=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toLowerCase())},ki=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toUpperCase())},EC=function(s,e){return ki(s)===ki(e)};var ON=Object.freeze({__proto__:null,toLowerCase:Fd,toTitleCase:ki,titleCaseEquals:EC});class ke{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=si({},this.options_),t=this.options_=si(this.options_,t),this.id_=t.id||t.el&&t.el.id,!this.id_){const n=e&&e.id&&e.id()||"no_player";this.id_=`${n}_component_${Nn()}`}this.name_=t.name||null,t.el?this.el_=t.el:t.createEl!==!1&&(this.el_=this.createEl()),t.className&&this.el_&&t.className.split(" ").forEach(n=>this.addClass(n)),["on","off","one","any","trigger"].forEach(n=>{this[n]=void 0}),t.evented!==!1&&(AT(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),SC(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Set,this.setIntervalIds_=new Set,this.rafIds_=new Set,this.namedRafs_=new Map,this.clearingTimersOnDispose_=!1,t.initChildren!==!1&&this.initChildren(),this.ready(i),t.reportTouchActivity!==!1&&this.enableTouchActivity()}dispose(e={}){if(!this.isDisposed_){if(this.readyQueue_&&(this.readyQueue_.length=0),this.trigger({type:"dispose",bubbles:!1}),this.isDisposed_=!0,this.children_)for(let t=this.children_.length-1;t>=0;t--)this.children_[t].dispose&&this.children_[t].dispose();this.children_=null,this.childIndex_=null,this.childNameIndex_=null,this.parentComponent_=null,this.el_&&(this.el_.parentNode&&(e.restoreEl?this.el_.parentNode.replaceChild(e.restoreEl,this.el_):this.el_.parentNode.removeChild(this.el_)),this.el_=null),this.player_=null}}isDisposed(){return!!this.isDisposed_}player(){return this.player_}options(e){return e?(this.options_=si(this.options_,e),this.options_):this.options_}el(){return this.el_}createEl(e,t,i){return gt(e,t,i)}localize(e,t,i=e){const n=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),o=r&&r[n],u=n&&n.split("-")[0],c=r&&r[u];let d=i;return o&&o[e]?d=o[e]:c&&c[e]&&(d=c[e]),t&&(d=d.replace(/\{(\d+)\}/g,function(f,m){const g=t[m-1];let v=g;return typeof g>"u"&&(v=f),v})),d}handleLanguagechange(){}contentEl(){return this.contentEl_||this.el_}id(){return this.id_}name(){return this.name_}children(){return this.children_}getChildById(e){return this.childIndex_[e]}getChild(e){if(e)return this.childNameIndex_[e]}getDescendant(...e){e=e.reduce((i,n)=>i.concat(n),[]);let t=this;for(let i=0;i=0;n--)if(this.children_[n]===e){t=!0,this.children_.splice(n,1);break}if(!t)return;e.parentComponent_=null,this.childIndex_[e.id()]=null,this.childNameIndex_[ki(e.name())]=null,this.childNameIndex_[Fd(e.name())]=null;const i=e.el();i&&i.parentNode===this.contentEl()&&this.contentEl().removeChild(e.el())}initChildren(){const e=this.options_.children;if(e){const t=this.options_,i=o=>{const u=o.name;let c=o.opts;if(t[u]!==void 0&&(c=t[u]),c===!1)return;c===!0&&(c={}),c.playerOptions=this.options_.playerOptions;const d=this.addChild(u,c);d&&(this[u]=d)};let n;const r=ke.getComponent("Tech");Array.isArray(e)?n=e:n=Object.keys(e),n.concat(Object.keys(this.options_).filter(function(o){return!n.some(function(u){return typeof u=="string"?o===u:o===u.name})})).map(o=>{let u,c;return typeof o=="string"?(u=o,c=e[u]||this.options_[u]||{}):(u=o.name,c=o),{name:u,opts:c}}).filter(o=>{const u=ke.getComponent(o.opts.componentClass||ki(o.name));return u&&!r.isTech(u)}).forEach(i)}}buildCSSClass(){return""}ready(e,t=!1){if(e){if(!this.isReady_){this.readyQueue_=this.readyQueue_||[],this.readyQueue_.push(e);return}t?e.call(this):this.setTimeout(e,1)}}triggerReady(){this.isReady_=!0,this.setTimeout(function(){const e=this.readyQueue_;this.readyQueue_=[],e&&e.length>0&&e.forEach(function(t){t.call(this)},this),this.trigger("ready")},1)}$(e,t){return So(e,t||this.contentEl())}$$(e,t){return pC(e,t||this.contentEl())}hasClass(e){return Bd(this.el_,e)}addClass(...e){vl(this.el_,...e)}removeClass(...e){Lm(this.el_,...e)}toggleClass(e,t){aC(this.el_,e,t)}show(){this.removeClass("vjs-hidden")}hide(){this.addClass("vjs-hidden")}lockShowing(){this.addClass("vjs-lock-showing")}unlockShowing(){this.removeClass("vjs-lock-showing")}getAttribute(e){return lC(this.el_,e)}setAttribute(e,t){tc(this.el_,e,t)}removeAttribute(e){Im(this.el_,e)}width(e,t){return this.dimension("width",e,t)}height(e,t){return this.dimension("height",e,t)}dimensions(e,t){this.width(e,!0),this.height(t)}dimension(e,t,i){if(t!==void 0){(t===null||t!==t)&&(t=0),(""+t).indexOf("%")!==-1||(""+t).indexOf("px")!==-1?this.el_.style[e]=t:t==="auto"?this.el_.style[e]="":this.el_.style[e]=t+"px",i||this.trigger("componentresize");return}if(!this.el_)return 0;const n=this.el_.style[e],r=n.indexOf("px");return parseInt(r!==-1?n.slice(0,r):this.el_["offset"+ki(e)],10)}currentDimension(e){let t=0;if(e!=="width"&&e!=="height")throw new Error("currentDimension only accepts width or height value");if(t=sc(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){const i=`offset${ki(e)}`;t=this.el_[i]}return t}currentDimensions(){return{width:this.currentDimension("width"),height:this.currentDimension("height")}}currentWidth(){return this.currentDimension("width")}currentHeight(){return this.currentDimension("height")}getPositions(){const e=this.el_.getBoundingClientRect(),t={x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left},i={x:e.left+e.width/2,y:e.top+e.height/2,width:0,height:0,top:e.top+e.height/2,right:e.left+e.width/2,bottom:e.top+e.height/2,left:e.left+e.width/2};return{boundingClientRect:t,center:i}}focus(){this.el_.focus()}blur(){this.el_.blur()}handleKeyDown(e){this.player_&&(e.key!=="Tab"&&!(this.player_.options_.playerOptions.spatialNavigation&&this.player_.options_.playerOptions.spatialNavigation.enabled)&&e.stopPropagation(),this.player_.handleKeyDown(e))}handleKeyPress(e){this.handleKeyDown(e)}emitTapEvents(){let e=0,t=null;const i=10,n=200;let r;this.on("touchstart",function(u){u.touches.length===1&&(t={pageX:u.touches[0].pageX,pageY:u.touches[0].pageY},e=se.performance.now(),r=!0)}),this.on("touchmove",function(u){if(u.touches.length>1)r=!1;else if(t){const c=u.touches[0].pageX-t.pageX,d=u.touches[0].pageY-t.pageY;Math.sqrt(c*c+d*d)>i&&(r=!1)}});const o=function(){r=!1};this.on("touchleave",o),this.on("touchcancel",o),this.on("touchend",function(u){t=null,r===!0&&se.performance.now()-e{this.setTimeoutIds_.has(i)&&this.setTimeoutIds_.delete(i),e()},t),this.setTimeoutIds_.add(i),i}clearTimeout(e){return this.setTimeoutIds_.has(e)&&(this.setTimeoutIds_.delete(e),se.clearTimeout(e)),e}setInterval(e,t){e=di(this,e),this.clearTimersOnDispose_();const i=se.setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),se.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=di(this,e),t=se.requestAnimationFrame(()=>{this.rafIds_.has(t)&&this.rafIds_.delete(t),e()}),this.rafIds_.add(t),t}requestNamedAnimationFrame(e,t){this.namedRafs_.has(e)&&this.cancelNamedAnimationFrame(e),this.clearTimersOnDispose_(),t=di(this,t);const i=this.requestAnimationFrame(()=>{t(),this.namedRafs_.has(e)&&this.namedRafs_.delete(e)});return this.namedRafs_.set(e,i),e}cancelNamedAnimationFrame(e){this.namedRafs_.has(e)&&(this.cancelAnimationFrame(this.namedRafs_.get(e)),this.namedRafs_.delete(e))}cancelAnimationFrame(e){return this.rafIds_.has(e)&&(this.rafIds_.delete(e),se.cancelAnimationFrame(e)),e}clearTimersOnDispose_(){this.clearingTimersOnDispose_||(this.clearingTimersOnDispose_=!0,this.one("dispose",()=>{[["namedRafs_","cancelNamedAnimationFrame"],["rafIds_","cancelAnimationFrame"],["setTimeoutIds_","clearTimeout"],["setIntervalIds_","clearInterval"]].forEach(([e,t])=>{this[e].forEach((i,n)=>this[t](n))}),this.clearingTimersOnDispose_=!1}))}getIsDisabled(){return!!this.el_.disabled}getIsExpresslyInert(){return this.el_.inert&&!this.el_.ownerDocument.documentElement.inert}getIsFocusable(e){return(e||this.el_).tabIndex>=0&&!(this.getIsDisabled()||this.getIsExpresslyInert())}getIsAvailableToBeFocused(e){function t(r){const o=se.getComputedStyle(r,null),u=o.getPropertyValue("visibility");return o.getPropertyValue("display")!=="none"&&!["hidden","collapse"].includes(u)}function i(r){return!(!t(r.parentElement)||!t(r)||r.style.opacity==="0"||se.getComputedStyle(r).height==="0px"||se.getComputedStyle(r).width==="0px")}function n(r){if(r.offsetWidth+r.offsetHeight+r.getBoundingClientRect().height+r.getBoundingClientRect().width===0)return!1;const o={x:r.getBoundingClientRect().left+r.offsetWidth/2,y:r.getBoundingClientRect().top+r.offsetHeight/2};if(o.x<0||o.x>(qe.documentElement.clientWidth||se.innerWidth)||o.y<0||o.y>(qe.documentElement.clientHeight||se.innerHeight))return!1;let u=qe.elementFromPoint(o.x,o.y);for(;u;){if(u===r)return!0;if(u.parentNode)u=u.parentNode;else return!1}}return e||(e=this.el()),!!(n(e)&&i(e)&&(!e.parentElement||e.tabIndex>=0))}static registerComponent(e,t){if(typeof e!="string"||!e)throw new Error(`Illegal component name, "${e}"; must be a non-empty string.`);const i=ke.getComponent("Tech"),n=i&&i.isTech(t),r=ke===t||ke.prototype.isPrototypeOf(t.prototype);if(n||!r){let u;throw n?u="techs must be registered using Tech.registerTech()":u="must be a Component subclass",new Error(`Illegal component, "${e}"; ${u}.`)}e=ki(e),ke.components_||(ke.components_={});const o=ke.getComponent("Player");if(e==="Player"&&o&&o.players){const u=o.players,c=Object.keys(u);if(u&&c.length>0){for(let d=0;dt)throw new Error(`Failed to execute '${s}' on 'TimeRanges': The index provided (${e}) is non-numeric or out of bounds (0-${t}).`)}function RE(s,e,t,i){return PN(s,i,t.length-1),t[i][e]}function by(s){let e;return s===void 0||s.length===0?e={length:0,start(){throw new Error("This TimeRanges object is empty")},end(){throw new Error("This TimeRanges object is empty")}}:e={length:s.length,start:RE.bind(null,"start",0,s),end:RE.bind(null,"end",1,s)},se.Symbol&&se.Symbol.iterator&&(e[se.Symbol.iterator]=()=>(s||[]).values()),e}function tr(s,e){return Array.isArray(s)?by(s):s===void 0||e===void 0?by():by([[s,e]])}const AC=function(s,e){s=s<0?0:s;let t=Math.floor(s%60),i=Math.floor(s/60%60),n=Math.floor(s/3600);const r=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(s)||s===1/0)&&(n=i=t="-"),n=n>0||o>0?n+":":"",i=((n||r>=10)&&i<10?"0"+i:i)+":",t=t<10?"0"+t:t,n+i+t};let CT=AC;function CC(s){CT=s}function DC(){CT=AC}function El(s,e=s){return CT(s,e)}var MN=Object.freeze({__proto__:null,createTimeRanges:tr,createTimeRange:tr,setFormatTime:CC,resetFormatTime:DC,formatTime:El});function wC(s,e){let t=0,i,n;if(!e)return 0;(!s||!s.length)&&(s=tr(0,0));for(let r=0;re&&(n=e),t+=n-i;return t/e}function Ei(s){if(s instanceof Ei)return s;typeof s=="number"?this.code=s:typeof s=="string"?this.message=s:Mr(s)&&(typeof s.code=="number"&&(this.code=s.code),Object.assign(this,s)),this.message||(this.message=Ei.defaultMessages[this.code]||"")}Ei.prototype.code=0;Ei.prototype.message="";Ei.prototype.status=null;Ei.prototype.metadata=null;Ei.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"];Ei.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail part-way.",3:"The media playback was aborted due to a corruption problem or because the media used features your browser did not support.",4:"The media could not be loaded, either because the server or network failed or because the format is not supported.",5:"The media is encrypted and we do not have the keys to decrypt it."};Ei.MEDIA_ERR_CUSTOM=0;Ei.prototype.MEDIA_ERR_CUSTOM=0;Ei.MEDIA_ERR_ABORTED=1;Ei.prototype.MEDIA_ERR_ABORTED=1;Ei.MEDIA_ERR_NETWORK=2;Ei.prototype.MEDIA_ERR_NETWORK=2;Ei.MEDIA_ERR_DECODE=3;Ei.prototype.MEDIA_ERR_DECODE=3;Ei.MEDIA_ERR_SRC_NOT_SUPPORTED=4;Ei.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4;Ei.MEDIA_ERR_ENCRYPTED=5;Ei.prototype.MEDIA_ERR_ENCRYPTED=5;function Ud(s){return s!=null&&typeof s.then=="function"}function wr(s){Ud(s)&&s.then(null,e=>{})}const Av=function(s){return["kind","label","language","id","inBandMetadataTrackDispatchType","mode","src"].reduce((t,i,n)=>(s[i]&&(t[i]=s[i]),t),{cues:s.cues&&Array.prototype.map.call(s.cues,function(t){return{startTime:t.startTime,endTime:t.endTime,text:t.text,id:t.id}})})},NN=function(s){const e=s.$$("track"),t=Array.prototype.map.call(e,n=>n.track);return Array.prototype.map.call(e,function(n){const r=Av(n.track);return n.src&&(r.src=n.src),r}).concat(Array.prototype.filter.call(s.textTracks(),function(n){return t.indexOf(n)===-1}).map(Av))},BN=function(s,e){return s.forEach(function(t){const i=e.addRemoteTextTrack(t).track;!t.src&&t.cues&&t.cues.forEach(n=>i.addCue(n))}),e.textTracks()};var Cv={textTracksToJson:NN,jsonToTextTracks:BN,trackToJson:Av};const _y="vjs-modal-dialog";class dc extends ke{constructor(e,t){super(e,t),this.handleKeyDown_=i=>this.handleKeyDown(i),this.close_=i=>this.close(i),this.opened_=this.hasBeenOpened_=this.hasBeenFilled_=!1,this.closeable(!this.options_.uncloseable),this.content(this.options_.content),this.contentEl_=gt("div",{className:`${_y}-content`},{role:"document"}),this.descEl_=gt("p",{className:`${_y}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),Co(this.descEl_,this.description()),this.el_.appendChild(this.descEl_),this.el_.appendChild(this.contentEl_)}createEl(){return super.createEl("div",{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":`${this.id()}_description`,"aria-hidden":"true","aria-label":this.label(),role:"dialog","aria-live":"polite"})}dispose(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,super.dispose()}buildCSSClass(){return`${_y} vjs-hidden ${super.buildCSSClass()}`}label(){return this.localize(this.options_.label||"Modal Window")}description(){let e=this.options_.description||this.localize("This is a modal window.");return this.closeable()&&(e+=" "+this.localize("This modal can be closed by pressing the Escape key or activating the close button.")),e}open(){if(this.opened_){this.options_.fillAlways&&this.fill();return}const e=this.player();this.trigger("beforemodalopen"),this.opened_=!0,(this.options_.fillAlways||!this.hasBeenOpened_&&!this.hasBeenFilled_)&&this.fill(),this.wasPlaying_=!e.paused(),this.options_.pauseOnOpen&&this.wasPlaying_&&e.pause(),this.on("keydown",this.handleKeyDown_),this.hadControls_=e.controls(),e.controls(!1),this.show(),this.conditionalFocus_(),this.el().setAttribute("aria-hidden","false"),this.trigger("modalopen"),this.hasBeenOpened_=!0}opened(e){return typeof e=="boolean"&&this[e?"open":"close"](),this.opened_}close(){if(!this.opened_)return;const e=this.player();this.trigger("beforemodalclose"),this.opened_=!1,this.wasPlaying_&&this.options_.pauseOnOpen&&e.play(),this.off("keydown",this.handleKeyDown_),this.hadControls_&&e.controls(!0),this.hide(),this.el().setAttribute("aria-hidden","true"),this.trigger({type:"modalclose",bubbles:!0}),this.conditionalBlur_(),this.options_.temporary&&this.dispose()}closeable(e){if(typeof e=="boolean"){const t=this.closeable_=!!e;let i=this.getChild("closeButton");if(t&&!i){const n=this.contentEl_;this.contentEl_=this.el_,i=this.addChild("closeButton",{controlText:"Close Modal Dialog"}),this.contentEl_=n,this.on(i,"close",this.close_)}!t&&i&&(this.off(i,"close",this.close_),this.removeChild(i),i.dispose())}return this.closeable_}fill(){this.fillWith(this.content())}fillWith(e){const t=this.contentEl(),i=t.parentNode,n=t.nextSibling;this.trigger("beforemodalfill"),this.hasBeenFilled_=!0,i.removeChild(t),this.empty(),fC(t,e),this.trigger("modalfill"),n?i.insertBefore(t,n):i.appendChild(t);const r=this.getChild("closeButton");r&&i.appendChild(r.el_),this.trigger("aftermodalfill")}empty(){this.trigger("beforemodalempty"),Rm(this.contentEl()),this.trigger("modalempty")}content(e){return typeof e<"u"&&(this.content_=e),this.content_}conditionalFocus_(){const e=qe.activeElement,t=this.player_.el_;this.previouslyActiveEl_=null,(t.contains(e)||t===e)&&(this.previouslyActiveEl_=e,this.focus())}conditionalBlur_(){this.previouslyActiveEl_&&(this.previouslyActiveEl_.focus(),this.previouslyActiveEl_=null)}handleKeyDown(e){if(this.trigger({type:"modalKeydown",originalEvent:e,target:this,bubbles:!0}),e.stopPropagation(),e.key==="Escape"&&this.closeable()){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;const t=this.focusableEls_(),i=this.el_.querySelector(":focus");let n;for(let r=0;r(t instanceof se.HTMLAnchorElement||t instanceof se.HTMLAreaElement)&&t.hasAttribute("href")||(t instanceof se.HTMLInputElement||t instanceof se.HTMLSelectElement||t instanceof se.HTMLTextAreaElement||t instanceof se.HTMLButtonElement)&&!t.hasAttribute("disabled")||t instanceof se.HTMLIFrameElement||t instanceof se.HTMLObjectElement||t instanceof se.HTMLEmbedElement||t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!==-1||t.hasAttribute("contenteditable"))}}dc.prototype.options_={pauseOnOpen:!0,temporary:!0};ke.registerComponent("ModalDialog",dc);class Al extends An{constructor(e=[]){super(),this.tracks_=[],Object.defineProperty(this,"length",{get(){return this.tracks_.length}});for(let t=0;t{this.trigger({track:e,type:"labelchange",target:this})},va(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,n=this.length;i=0;t--)if(e[t].enabled){xy(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&xy(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,xy(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("enabledchange",e.enabledChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.enabledChange_&&(e.removeEventListener("enabledchange",e.enabledChange_),e.enabledChange_=null)}}const Sy=function(s,e){for(let t=0;t=0;t--)if(e[t].selected){Sy(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let t=0;t{this.changing_||(this.changing_=!0,Sy(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("selectedchange",e.selectedChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.selectedChange_&&(e.removeEventListener("selectedchange",e.selectedChange_),e.selectedChange_=null)}}class DT extends Al{addTrack(e){super.addTrack(e),this.queueChange_||(this.queueChange_=()=>this.queueTrigger("change")),this.triggerSelectedlanguagechange||(this.triggerSelectedlanguagechange_=()=>this.trigger("selectedlanguagechange")),e.addEventListener("modechange",this.queueChange_),["metadata","chapters"].indexOf(e.kind)===-1&&e.addEventListener("modechange",this.triggerSelectedlanguagechange_)}removeTrack(e){super.removeTrack(e),e.removeEventListener&&(this.queueChange_&&e.removeEventListener("modechange",this.queueChange_),this.selectedlanguagechange_&&e.removeEventListener("modechange",this.triggerSelectedlanguagechange_))}toJSON(){return this.tracks_.map(e=>e.toJSON())}}class FN{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;t0&&(se.console&&se.console.groupCollapsed&&se.console.groupCollapsed(`Text Track parsing errors for ${e.src}`),i.forEach(n=>It.error(n)),se.console&&se.console.groupEnd&&se.console.groupEnd()),t.flush()},ME=function(s,e){const t={uri:s},i=Nm(s);i&&(t.cors=i);const n=e.tech_.crossOrigin()==="use-credentials";n&&(t.withCredentials=n),OA(t,di(this,function(r,o,u){if(r)return It.error(r,o);e.loaded_=!0,typeof se.WebVTT!="function"?e.tech_&&e.tech_.any(["vttjsloaded","vttjserror"],c=>{if(c.type==="vttjserror"){It.error(`vttjs failed to load, stopping trying to process ${e.src}`);return}return PE(u,e)}):PE(u,e)}))};class lh extends wT{constructor(e={}){if(!e.tech)throw new Error("A tech was not provided.");const t=si(e,{kind:jN[e.kind]||"subtitles",language:e.language||e.srclang||""});let i=OE[t.mode]||"disabled";const n=t.default;(t.kind==="metadata"||t.kind==="chapters")&&(i="hidden"),super(t),this.tech_=t.tech,this.cues_=[],this.activeCues_=[],this.preload_=this.tech_.preloadTextTracks!==!1;const r=new Up(this.cues_),o=new Up(this.activeCues_);let u=!1;this.timeupdateHandler=di(this,function(d={}){if(!this.tech_.isDisposed()){if(!this.tech_.isReady_){d.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler));return}this.activeCues=this.activeCues,u&&(this.trigger("cuechange"),u=!1),d.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))}});const c=()=>{this.stopTracking()};this.tech_.one("dispose",c),i!=="disabled"&&this.startTracking(),Object.defineProperties(this,{default:{get(){return n},set(){}},mode:{get(){return i},set(d){OE[d]&&i!==d&&(i=d,!this.preload_&&i!=="disabled"&&this.cues.length===0&&ME(this.src,this),this.stopTracking(),i!=="disabled"&&this.startTracking(),this.trigger("modechange"))}},cues:{get(){return this.loaded_?r:null},set(){}},activeCues:{get(){if(!this.loaded_)return null;if(this.cues.length===0)return o;const d=this.tech_.currentTime(),f=[];for(let m=0,g=this.cues.length;m=d&&f.push(v)}if(u=!1,f.length!==this.activeCues_.length)u=!0;else for(let m=0;m{t=ba.LOADED,this.trigger({type:"load",target:this})})}}ba.prototype.allowedEvents_={load:"load"};ba.NONE=0;ba.LOADING=1;ba.LOADED=2;ba.ERROR=3;const Mn={audio:{ListClass:LC,TrackClass:RC,capitalName:"Audio"},video:{ListClass:IC,TrackClass:OC,capitalName:"Video"},text:{ListClass:DT,TrackClass:lh,capitalName:"Text"}};Object.keys(Mn).forEach(function(s){Mn[s].getterName=`${s}Tracks`,Mn[s].privateName=`${s}Tracks_`});const nc={remoteText:{ListClass:DT,TrackClass:lh,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:FN,TrackClass:ba,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},Ns=Object.assign({},Mn,nc);nc.names=Object.keys(nc);Mn.names=Object.keys(Mn);Ns.names=[].concat(nc.names).concat(Mn.names);function GN(s,e,t,i,n={}){const r=s.textTracks();n.kind=e,t&&(n.label=t),i&&(n.language=i),n.tech=s;const o=new Ns.text.TrackClass(n);return r.addTrack(o),o}class Et extends ke{constructor(e={},t=function(){}){e.reportTouchActivity=!1,super(null,e,t),this.onDurationChange_=i=>this.onDurationChange(i),this.trackProgress_=i=>this.trackProgress(i),this.trackCurrentTime_=i=>this.trackCurrentTime(i),this.stopTrackingCurrentTime_=i=>this.stopTrackingCurrentTime(i),this.disposeSourceHandler_=i=>this.disposeSourceHandler(i),this.queuedHanders_=new Set,this.hasStarted_=!1,this.on("playing",function(){this.hasStarted_=!0}),this.on("loadstart",function(){this.hasStarted_=!1}),Ns.names.forEach(i=>{const n=Ns[i];e&&e[n.getterName]&&(this[n.privateName]=e[n.getterName])}),this.featuresProgressEvents||this.manualProgressOn(),this.featuresTimeupdateEvents||this.manualTimeUpdatesOn(),["Text","Audio","Video"].forEach(i=>{e[`native${i}Tracks`]===!1&&(this[`featuresNative${i}Tracks`]=!1)}),e.nativeCaptions===!1||e.nativeTextTracks===!1?this.featuresNativeTextTracks=!1:(e.nativeCaptions===!0||e.nativeTextTracks===!0)&&(this.featuresNativeTextTracks=!0),this.featuresNativeTextTracks||this.emulateTextTracks(),this.preloadTextTracks=e.preloadTextTracks!==!1,this.autoRemoteTextTracks_=new Ns.text.ListClass,this.initTrackListeners(),e.nativeControlsForTouch||this.emitTapEvents(),this.constructor&&(this.name_=this.constructor.name||"Unknown Tech")}triggerSourceset(e){this.isReady_||this.one("ready",()=>this.setTimeout(()=>this.triggerSourceset(e),1)),this.trigger({src:e,type:"sourceset"})}manualProgressOn(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)}manualProgressOff(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)}trackProgress(e){this.stopTrackingProgress(),this.progressInterval=this.setInterval(di(this,function(){const t=this.bufferedPercent();this.bufferedPercent_!==t&&this.trigger("progress"),this.bufferedPercent_=t,t===1&&this.stopTrackingProgress()}),500)}onDurationChange(e){this.duration_=this.duration()}buffered(){return tr(0,0)}bufferedPercent(){return wC(this.buffered(),this.duration_)}stopTrackingProgress(){this.clearInterval(this.progressInterval)}manualTimeUpdatesOn(){this.manualTimeUpdates=!0,this.on("play",this.trackCurrentTime_),this.on("pause",this.stopTrackingCurrentTime_)}manualTimeUpdatesOff(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off("play",this.trackCurrentTime_),this.off("pause",this.stopTrackingCurrentTime_)}trackCurrentTime(){this.currentTimeInterval&&this.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval(function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},250)}stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval),this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}dispose(){this.clearTracks(Mn.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),super.dispose()}clearTracks(e){e=[].concat(e),e.forEach(t=>{const i=this[`${t}Tracks`]()||[];let n=i.length;for(;n--;){const r=i[n];t==="text"&&this.removeRemoteTextTrack(r),i.removeTrack(r)}})}cleanupAutoTextTracks(){const e=this.autoRemoteTextTracks_||[];let t=e.length;for(;t--;){const i=e[t];this.removeRemoteTextTrack(i)}}reset(){}crossOrigin(){}setCrossOrigin(){}error(e){return e!==void 0&&(this.error_=new Ei(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?tr(0,0):tr()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){Mn.names.forEach(e=>{const t=Mn[e],i=()=>{this.trigger(`${e}trackchange`)},n=this[t.getterName]();n.addEventListener("removetrack",i),n.addEventListener("addtrack",i),this.on("dispose",()=>{n.removeEventListener("removetrack",i),n.removeEventListener("addtrack",i)})})}addWebVttScript_(){if(!se.WebVTT)if(qe.body.contains(this.el())){if(!this.options_["vtt.js"]&&ec(rE)&&Object.keys(rE).length>0){this.trigger("vttjsloaded");return}const e=qe.createElement("script");e.src=this.options_["vtt.js"]||"https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js",e.onload=()=>{this.trigger("vttjsloaded")},e.onerror=()=>{this.trigger("vttjserror")},this.on("dispose",()=>{e.onload=null,e.onerror=null}),se.WebVTT=!0,this.el().parentNode.appendChild(e)}else this.ready(this.addWebVttScript_)}emulateTextTracks(){const e=this.textTracks(),t=this.remoteTextTracks(),i=u=>e.addTrack(u.track),n=u=>e.removeTrack(u.track);t.on("addtrack",i),t.on("removetrack",n),this.addWebVttScript_();const r=()=>this.trigger("texttrackchange"),o=()=>{r();for(let u=0;uthis.autoRemoteTextTracks_.addTrack(i.track)),i}removeRemoteTextTrack(e){const t=this.remoteTextTrackEls().getTrackElementByTrack_(e);this.remoteTextTrackEls().removeTrackElement_(t),this.remoteTextTracks().removeTrack(e),this.autoRemoteTextTracks_.removeTrack(e)}getVideoPlaybackQuality(){return{}}requestPictureInPicture(){return Promise.reject()}disablePictureInPicture(){return!0}setDisablePictureInPicture(){}requestVideoFrameCallback(e){const t=Nn();return!this.isReady_||this.paused()?(this.queuedHanders_.add(t),this.one("playing",()=>{this.queuedHanders_.has(t)&&(this.queuedHanders_.delete(t),e())})):this.requestNamedAnimationFrame(t,e),t}cancelVideoFrameCallback(e){this.queuedHanders_.has(e)?this.queuedHanders_.delete(e):this.cancelNamedAnimationFrame(e)}setPoster(){}playsinline(){}setPlaysinline(){}overrideNativeAudioTracks(e){}overrideNativeVideoTracks(e){}canPlayType(e){return""}static canPlayType(e){return""}static canPlaySource(e,t){return Et.canPlayType(e.type)}static isTech(e){return e.prototype instanceof Et||e instanceof Et||e===Et}static registerTech(e,t){if(Et.techs_||(Et.techs_={}),!Et.isTech(t))throw new Error(`Tech ${e} must be a Tech`);if(!Et.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!Et.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return e=ki(e),Et.techs_[e]=t,Et.techs_[Fd(e)]=t,e!=="Tech"&&Et.defaultTechOrder_.push(e),t}static getTech(e){if(e){if(Et.techs_&&Et.techs_[e])return Et.techs_[e];if(e=ki(e),se&&se.videojs&&se.videojs[e])return It.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),se.videojs[e]}}}Ns.names.forEach(function(s){const e=Ns[s];Et.prototype[e.getterName]=function(){return this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName]}});Et.prototype.featuresVolumeControl=!0;Et.prototype.featuresMuteControl=!0;Et.prototype.featuresFullscreenResize=!1;Et.prototype.featuresPlaybackRate=!1;Et.prototype.featuresProgressEvents=!1;Et.prototype.featuresSourceset=!1;Et.prototype.featuresTimeupdateEvents=!1;Et.prototype.featuresNativeTextTracks=!1;Et.prototype.featuresVideoFrameCallback=!1;Et.withSourceHandlers=function(s){s.registerSourceHandler=function(t,i){let n=s.sourceHandlers;n||(n=s.sourceHandlers=[]),i===void 0&&(i=n.length),n.splice(i,0,t)},s.canPlayType=function(t){const i=s.sourceHandlers||[];let n;for(let r=0;rcl(e,Tl[e.type],t,s),1)}function zN(s,e){s.forEach(t=>t.setTech&&t.setTech(e))}function KN(s,e,t){return s.reduceRight(kT(t),e[t]())}function YN(s,e,t,i){return e[t](s.reduce(kT(t),i))}function NE(s,e,t,i=null){const n="call"+ki(t),r=s.reduce(kT(n),i),o=r===jp,u=o?null:e[t](r);return QN(s,t,u,o),u}const WN={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},XN={setCurrentTime:1,setMuted:1,setVolume:1},BE={play:1,pause:1};function kT(s){return(e,t)=>e===jp?jp:t[s]?t[s](e):e}function QN(s,e,t,i){for(let n=s.length-1;n>=0;n--){const r=s[n];r[e]&&r[e](i,t)}}function ZN(s){$p.hasOwnProperty(s.id())&&delete $p[s.id()]}function JN(s,e){const t=$p[s.id()];let i=null;if(t==null)return i=e(s),$p[s.id()]=[[e,i]],i;for(let n=0;n{if(!e)return"";if(s.cache_.source.src===e&&s.cache_.source.type)return s.cache_.source.type;const t=s.cache_.sources.filter(n=>n.src===e);if(t.length)return t[0].type;const i=s.$$("source");for(let n=0;n - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -`;const UE=Mp?10009:Np?461:8,_u={codes:{play:415,pause:19,ff:417,rw:412,back:UE},names:{415:"play",19:"pause",417:"ff",412:"rw",[UE]:"back"},isEventKey(s,e){return e=e.toLowerCase(),!!(this.names[s.keyCode]&&this.names[s.keyCode]===e)},getEventName(s){if(this.names[s.keyCode])return this.names[s.keyCode];if(this.codes[s.code]){const e=this.codes[s.code];return this.names[e]}return null}},$E=5;class s3 extends An{constructor(e){super(),this.player_=e,this.focusableComponents=[],this.isListening_=!1,this.isPaused_=!1,this.onKeyDown_=this.onKeyDown_.bind(this),this.lastFocusedComponent_=null}start(){this.isListening_||(this.player_.on("keydown",this.onKeyDown_),this.player_.on("modalKeydown",this.onKeyDown_),this.player_.on("loadedmetadata",()=>{this.focus(this.updateFocusableComponents()[0])}),this.player_.on("modalclose",()=>{this.refocusComponent()}),this.player_.on("focusin",this.handlePlayerFocus_.bind(this)),this.player_.on("focusout",this.handlePlayerBlur_.bind(this)),this.isListening_=!0,this.player_.errorDisplay&&this.player_.errorDisplay.on("aftermodalfill",()=>{this.updateFocusableComponents(),this.focusableComponents.length&&(this.focusableComponents.length>1?this.focusableComponents[1].focus():this.focusableComponents[0].focus())}))}stop(){this.player_.off("keydown",this.onKeyDown_),this.isListening_=!1}onKeyDown_(e){const t=e.originalEvent?e.originalEvent:e;if(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(t.key)){if(this.isPaused_)return;t.preventDefault();const i=t.key.substring(5).toLowerCase();this.move(i)}else if(_u.isEventKey(t,"play")||_u.isEventKey(t,"pause")||_u.isEventKey(t,"ff")||_u.isEventKey(t,"rw")){t.preventDefault();const i=_u.getEventName(t);this.performMediaAction_(i)}else _u.isEventKey(t,"Back")&&e.target&&typeof e.target.closeable=="function"&&e.target.closeable()&&(t.preventDefault(),e.target.close())}performMediaAction_(e){if(this.player_)switch(e){case"play":this.player_.paused()&&this.player_.play();break;case"pause":this.player_.paused()||this.player_.pause();break;case"ff":this.userSeek_(this.player_.currentTime()+$E);break;case"rw":this.userSeek_(this.player_.currentTime()-$E);break}}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}pause(){this.isPaused_=!0}resume(){this.isPaused_=!1}handlePlayerBlur_(e){const t=e.relatedTarget;let i=null;const n=this.getCurrentComponent(e.target);t&&(i=!!t.closest(".video-js"),t.classList.contains("vjs-text-track-settings")&&!this.isPaused_&&this.searchForTrackSelect_()),(!e.currentTarget.contains(e.relatedTarget)&&!i||!t)&&(n&&n.name()==="CloseButton"?this.refocusComponent():(this.pause(),n&&n.el()&&(this.lastFocusedComponent_=n)))}handlePlayerFocus_(){this.getCurrentComponent()&&this.getCurrentComponent().getIsFocusable()&&this.resume()}updateFocusableComponents(){const e=this.player_,t=[];function i(n){for(const r of n)r.hasOwnProperty("el_")&&r.getIsFocusable()&&r.getIsAvailableToBeFocused(r.el())&&t.push(r),r.hasOwnProperty("children_")&&r.children_.length>0&&i(r.children_)}return e.children_.forEach(n=>{if(n.hasOwnProperty("el_"))if(n.getIsFocusable&&n.getIsAvailableToBeFocused&&n.getIsFocusable()&&n.getIsAvailableToBeFocused(n.el())){t.push(n);return}else n.hasOwnProperty("children_")&&n.children_.length>0?i(n.children_):n.hasOwnProperty("items")&&n.items.length>0?i(n.items):this.findSuitableDOMChild(n)&&t.push(n);if(n.name_==="ErrorDisplay"&&n.opened_){const r=n.el_.querySelector(".vjs-errors-ok-button-container");r&&r.querySelectorAll("button").forEach((u,c)=>{t.push({name:()=>"ModalButton"+(c+1),el:()=>u,getPositions:()=>{const d=u.getBoundingClientRect(),f={x:d.x,y:d.y,width:d.width,height:d.height,top:d.top,right:d.right,bottom:d.bottom,left:d.left},m={x:d.left+d.width/2,y:d.top+d.height/2,width:0,height:0,top:d.top+d.height/2,right:d.left+d.width/2,bottom:d.top+d.height/2,left:d.left+d.width/2};return{boundingClientRect:f,center:m}},getIsAvailableToBeFocused:()=>!0,getIsFocusable:d=>!0,focus:()=>u.focus()})})}}),this.focusableComponents=t,this.focusableComponents}findSuitableDOMChild(e){function t(i){if(e.getIsFocusable(i)&&e.getIsAvailableToBeFocused(i))return i;for(let n=0;n0&&(this.focusableComponents=[],this.trigger({type:"focusableComponentsChanged",focusableComponents:this.focusableComponents}))}move(e){const t=this.getCurrentComponent();if(!t)return;const i=t.getPositions(),n=this.focusableComponents.filter(o=>o!==t&&this.isInDirection_(i.boundingClientRect,o.getPositions().boundingClientRect,e)),r=this.findBestCandidate_(i.center,n,e);r?this.focus(r):this.trigger({type:"endOfFocusableComponents",direction:e,focusedComponent:t})}findBestCandidate_(e,t,i){let n=1/0,r=null;for(const o of t){const u=o.getPositions().center,c=this.calculateDistance_(e,u,i);c=e.right;case"left":return t.right<=e.left;case"down":return t.top>=e.bottom;case"up":return t.bottom<=e.top;default:return!1}}refocusComponent(){if(this.lastFocusedComponent_){this.player_.userActive()||this.player_.userActive(!0),this.updateFocusableComponents();for(let e=0;ethis.handleMouseOver(i),this.handleMouseOut_=i=>this.handleMouseOut(i),this.handleClick_=i=>this.handleClick(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.emitTapEvents(),this.enable()}createEl(e="div",t={},i={}){t=Object.assign({className:this.buildCSSClass(),tabIndex:0},t),e==="button"&&It.error(`Creating a ClickableComponent with an HTML element of ${e} is not supported; use a Button instead.`),i=Object.assign({role:"button"},i),this.tabIndex_=t.tabIndex;const n=gt(e,t,i);return this.player_.options_.experimentalSvgIcons||n.appendChild(gt("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(n),n}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=gt("span",{className:"vjs-control-text"},{"aria-live":"polite"}),e&&e.appendChild(this.controlTextEl_),this.controlText(this.controlText_,e),this.controlTextEl_}controlText(e,t=this.el()){if(e===void 0)return this.controlText_||"Need Text";const i=this.localize(e);this.controlText_=e,Co(this.controlTextEl_,i),!this.nonIconControl&&!this.player_.options_.noUITitleAttributes&&t.setAttribute("title",i)}buildCSSClass(){return`vjs-control vjs-button ${super.buildCSSClass()}`}enable(){this.enabled_||(this.enabled_=!0,this.removeClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","false"),typeof this.tabIndex_<"u"&&this.el_.setAttribute("tabIndex",this.tabIndex_),this.on(["tap","click"],this.handleClick_),this.on("keydown",this.handleKeyDown_))}disable(){this.enabled_=!1,this.addClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","true"),typeof this.tabIndex_<"u"&&this.el_.removeAttribute("tabIndex"),this.off("mouseover",this.handleMouseOver_),this.off("mouseout",this.handleMouseOut_),this.off(["tap","click"],this.handleClick_),this.off("keydown",this.handleKeyDown_)}handleLanguagechange(){this.controlText(this.controlText_)}handleClick(e){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)}handleKeyDown(e){e.key===" "||e.key==="Enter"?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}ke.registerComponent("ClickableComponent",Bm);class Dv extends Bm{constructor(e,t){super(e,t),this.update(),this.update_=i=>this.update(i),e.on("posterchange",this.update_)}dispose(){this.player().off("posterchange",this.update_),super.dispose()}createEl(){return gt("div",{className:"vjs-poster"})}crossOrigin(e){if(typeof e>"u")return this.$("img")?this.$("img").crossOrigin:this.player_.tech_&&this.player_.tech_.isReady_?this.player_.crossOrigin():this.player_.options_.crossOrigin||this.player_.options_.crossorigin||null;if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.$("img")&&(this.$("img").crossOrigin=e)}update(e){const t=this.player().poster();this.setSrc(t),t?this.show():this.hide()}setSrc(e){if(!e){this.el_.textContent="";return}this.$("img")||this.el_.appendChild(gt("picture",{className:"vjs-poster",tabIndex:-1},{},gt("img",{loading:"lazy",crossOrigin:this.crossOrigin()},{alt:""}))),this.$("img").src=e}handleClick(e){this.player_.controls()&&(this.player_.tech(!0)&&this.player_.tech(!0).focus(),this.player_.paused()?wr(this.player_.play()):this.player_.pause())}}Dv.prototype.crossorigin=Dv.prototype.crossOrigin;ke.registerComponent("PosterImage",Dv);const On="#222",jE="#ccc",r3={monospace:"monospace",sansSerif:"sans-serif",serif:"serif",monospaceSansSerif:'"Andale Mono", "Lucida Console", monospace',monospaceSerif:'"Courier New", monospace',proportionalSansSerif:"sans-serif",proportionalSerif:"serif",casual:'"Comic Sans MS", Impact, fantasy',script:'"Monotype Corsiva", cursive',smallcaps:'"Andale Mono", "Lucida Console", monospace, sans-serif'};function Ey(s,e){let t;if(s.length===4)t=s[1]+s[1]+s[2]+s[2]+s[3]+s[3];else if(s.length===7)t=s.slice(1);else throw new Error("Invalid color code provided, "+s+"; must be formatted as e.g. #f0e or #f604e2.");return"rgba("+parseInt(t.slice(0,2),16)+","+parseInt(t.slice(2,4),16)+","+parseInt(t.slice(4,6),16)+","+e+")"}function br(s,e,t){try{s.style[e]=t}catch{return}}function HE(s){return s?`${s}px`:""}class a3 extends ke{constructor(e,t,i){super(e,t,i);const n=o=>this.updateDisplay(o),r=o=>{this.updateDisplayOverlay(),this.updateDisplay(o)};e.on("loadstart",o=>this.toggleDisplay(o)),e.on("useractive",n),e.on("userinactive",n),e.on("texttrackchange",n),e.on("loadedmetadata",o=>{this.updateDisplayOverlay(),this.preselectTrack(o)}),e.ready(di(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",r),e.on("playerresize",r);const o=se.screen.orientation||se,u=se.screen.orientation?"change":"orientationchange";o.addEventListener(u,r),e.on("dispose",()=>o.removeEventListener(u,r));const c=this.options_.playerOptions.tracks||[];for(let d=0;d0&&u.forEach(f=>{if(f.style.inset){const m=f.style.inset.split(" ");m.length===3&&Object.assign(f.style,{top:m[0],right:m[1],bottom:m[2],left:"unset"})}})}}updateDisplayOverlay(){if(!this.player_.videoHeight()||!se.CSS.supports("inset-inline: 10px"))return;const e=this.player_.currentWidth(),t=this.player_.currentHeight(),i=e/t,n=this.player_.videoWidth()/this.player_.videoHeight();let r=0,o=0;Math.abs(i-n)>.1&&(i>n?r=Math.round((e-t*n)/2):o=Math.round((t-e/n)/2)),br(this.el_,"insetInline",HE(r)),br(this.el_,"insetBlock",HE(o))}updateDisplayState(e){const t=this.player_.textTrackSettings.getValues(),i=e.activeCues;let n=i.length;for(;n--;){const r=i[n];if(!r)continue;const o=r.displayState;if(t.color&&(o.firstChild.style.color=t.color),t.textOpacity&&br(o.firstChild,"color",Ey(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(o.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&br(o.firstChild,"backgroundColor",Ey(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?br(o,"backgroundColor",Ey(t.windowColor,t.windowOpacity)):o.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle==="dropshadow"?o.firstChild.style.textShadow=`2px 2px 3px ${On}, 2px 2px 4px ${On}, 2px 2px 5px ${On}`:t.edgeStyle==="raised"?o.firstChild.style.textShadow=`1px 1px ${On}, 2px 2px ${On}, 3px 3px ${On}`:t.edgeStyle==="depressed"?o.firstChild.style.textShadow=`1px 1px ${jE}, 0 1px ${jE}, -1px -1px ${On}, 0 -1px ${On}`:t.edgeStyle==="uniform"&&(o.firstChild.style.textShadow=`0 0 4px ${On}, 0 0 4px ${On}, 0 0 4px ${On}, 0 0 4px ${On}`)),t.fontPercent&&t.fontPercent!==1){const u=se.parseFloat(o.style.fontSize);o.style.fontSize=u*t.fontPercent+"px",o.style.height="auto",o.style.top="auto"}t.fontFamily&&t.fontFamily!=="default"&&(t.fontFamily==="small-caps"?o.firstChild.style.fontVariant="small-caps":o.firstChild.style.fontFamily=r3[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof se.WebVTT!="function"||e.every(i=>!i.activeCues))return;const t=[];for(let i=0;ithis.handleMouseDown(i))}buildCSSClass(){return"vjs-big-play-button"}handleClick(e){const t=this.player_.play();if(e.type==="tap"||this.mouseused_&&"clientX"in e&&"clientY"in e){wr(t),this.player_.tech(!0)&&this.player_.tech(!0).focus();return}const i=this.player_.getChild("controlBar"),n=i&&i.getChild("playToggle");if(!n){this.player_.tech(!0).focus();return}const r=()=>n.focus();Ud(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}MC.prototype.controlText_="Play Video";ke.registerComponent("BigPlayButton",MC);class l3 extends ws{constructor(e,t){super(e,t),this.setIcon("cancel"),this.controlText(t&&t.controlText||this.localize("Close"))}buildCSSClass(){return`vjs-close-button ${super.buildCSSClass()}`}handleClick(e){this.trigger({type:"close",bubbles:!1})}handleKeyDown(e){e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}ke.registerComponent("CloseButton",l3);class NC extends ws{constructor(e,t={}){super(e,t),t.replay=t.replay===void 0||t.replay,this.setIcon("play"),this.on(e,"play",i=>this.handlePlay(i)),this.on(e,"pause",i=>this.handlePause(i)),t.replay&&this.on(e,"ended",i=>this.handleEnded(i))}buildCSSClass(){return`vjs-play-control ${super.buildCSSClass()}`}handleClick(e){this.player_.paused()?wr(this.player_.play()):this.player_.pause()}handleSeeked(e){this.removeClass("vjs-ended"),this.player_.paused()?this.handlePause(e):this.handlePlay(e)}handlePlay(e){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.setIcon("pause"),this.controlText("Pause")}handlePause(e){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.setIcon("play"),this.controlText("Play")}handleEnded(e){this.removeClass("vjs-playing"),this.addClass("vjs-ended"),this.setIcon("replay"),this.controlText("Replay"),this.one(this.player_,"seeked",t=>this.handleSeeked(t))}}NC.prototype.controlText_="Play";ke.registerComponent("PlayToggle",NC);class hc extends ke{constructor(e,t){super(e,t),this.on(e,["timeupdate","ended","seeking"],i=>this.update(i)),this.updateTextNode_()}createEl(){const e=this.buildCSSClass(),t=super.createEl("div",{className:`${e} vjs-time-control vjs-control`}),i=gt("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)} `},{role:"presentation"});return t.appendChild(i),this.contentEl_=gt("span",{className:`${e}-display`},{role:"presentation"}),t.appendChild(this.contentEl_),t}dispose(){this.contentEl_=null,this.textNode_=null,super.dispose()}update(e){!this.player_.options_.enableSmoothSeeking&&e.type==="seeking"||this.updateContent(e)}updateTextNode_(e=0){e=El(e),this.formattedTime_!==e&&(this.formattedTime_=e,this.requestNamedAnimationFrame("TimeDisplay#updateTextNode_",()=>{if(!this.contentEl_)return;let t=this.textNode_;t&&this.contentEl_.firstChild!==t&&(t=null,It.warn("TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.")),this.textNode_=qe.createTextNode(this.formattedTime_),this.textNode_&&(t?this.contentEl_.replaceChild(this.textNode_,t):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}}hc.prototype.labelText_="Time";hc.prototype.controlText_="Time";ke.registerComponent("TimeDisplay",hc);class RT extends hc{buildCSSClass(){return"vjs-current-time"}updateContent(e){let t;this.player_.ended()?t=this.player_.duration():e&&e.target&&typeof e.target.pendingSeekTime=="function"?t=e.target.pendingSeekTime():t=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime(),this.updateTextNode_(t)}}RT.prototype.labelText_="Current Time";RT.prototype.controlText_="Current Time";ke.registerComponent("CurrentTimeDisplay",RT);class OT extends hc{constructor(e,t){super(e,t);const i=n=>this.updateContent(n);this.on(e,"durationchange",i),this.on(e,"loadstart",i),this.on(e,"loadedmetadata",i)}buildCSSClass(){return"vjs-duration"}updateContent(e){const t=this.player_.duration();this.updateTextNode_(t)}}OT.prototype.labelText_="Duration";OT.prototype.controlText_="Duration";ke.registerComponent("DurationDisplay",OT);class u3 extends ke{createEl(){const e=super.createEl("div",{className:"vjs-time-control vjs-time-divider"},{"aria-hidden":!0}),t=super.createEl("div"),i=super.createEl("span",{textContent:"/"});return t.appendChild(i),e.appendChild(t),e}}ke.registerComponent("TimeDivider",u3);class PT extends hc{constructor(e,t){super(e,t),this.on(e,"durationchange",i=>this.updateContent(i))}buildCSSClass(){return"vjs-remaining-time"}createEl(){const e=super.createEl();return this.options_.displayNegative!==!1&&e.insertBefore(gt("span",{},{"aria-hidden":!0},"-"),this.contentEl_),e}updateContent(e){if(typeof this.player_.duration()!="number")return;let t;this.player_.ended()?t=0:this.player_.remainingTimeDisplay?t=this.player_.remainingTimeDisplay():t=this.player_.remainingTime(),this.updateTextNode_(t)}}PT.prototype.labelText_="Remaining Time";PT.prototype.controlText_="Remaining Time";ke.registerComponent("RemainingTimeDisplay",PT);class c3 extends ke{constructor(e,t){super(e,t),this.updateShowing(),this.on(this.player(),"durationchange",i=>this.updateShowing(i))}createEl(){const e=super.createEl("div",{className:"vjs-live-control vjs-control"});return this.contentEl_=gt("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(gt("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(qe.createTextNode(this.localize("LIVE"))),e.appendChild(this.contentEl_),e}dispose(){this.contentEl_=null,super.dispose()}updateShowing(e){this.player().duration()===1/0?this.show():this.hide()}}ke.registerComponent("LiveDisplay",c3);class BC extends ws{constructor(e,t){super(e,t),this.updateLiveEdgeStatus(),this.player_.liveTracker&&(this.updateLiveEdgeStatusHandler_=i=>this.updateLiveEdgeStatus(i),this.on(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_))}createEl(){const e=super.createEl("button",{className:"vjs-seek-to-live-control vjs-control"});return this.setIcon("circle",e),this.textEl_=gt("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),e.appendChild(this.textEl_),e}updateLiveEdgeStatus(){!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()?(this.setAttribute("aria-disabled",!0),this.addClass("vjs-at-live-edge"),this.controlText("Seek to live, currently playing live")):(this.setAttribute("aria-disabled",!1),this.removeClass("vjs-at-live-edge"),this.controlText("Seek to live, currently behind live"))}handleClick(){this.player_.liveTracker.seekToLiveEdge()}dispose(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,super.dispose()}}BC.prototype.controlText_="Seek to live, currently playing live";ke.registerComponent("SeekToLive",BC);function uh(s,e,t){return s=Number(s),Math.min(t,Math.max(e,isNaN(s)?e:s))}var d3=Object.freeze({__proto__:null,clamp:uh});class MT extends ke{constructor(e,t){super(e,t),this.handleMouseDown_=i=>this.handleMouseDown(i),this.handleMouseUp_=i=>this.handleMouseUp(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.handleClick_=i=>this.handleClick(i),this.handleMouseMove_=i=>this.handleMouseMove(i),this.update_=i=>this.update(i),this.bar=this.getChild(this.options_.barName),this.vertical(!!this.options_.vertical),this.enable()}enabled(){return this.enabled_}enable(){this.enabled()||(this.on("mousedown",this.handleMouseDown_),this.on("touchstart",this.handleMouseDown_),this.on("keydown",this.handleKeyDown_),this.on("click",this.handleClick_),this.on(this.player_,"controlsvisible",this.update),this.playerEvent&&this.on(this.player_,this.playerEvent,this.update),this.removeClass("disabled"),this.setAttribute("tabindex",0),this.enabled_=!0)}disable(){if(!this.enabled())return;const e=this.bar.el_.ownerDocument;this.off("mousedown",this.handleMouseDown_),this.off("touchstart",this.handleMouseDown_),this.off("keydown",this.handleKeyDown_),this.off("click",this.handleClick_),this.off(this.player_,"controlsvisible",this.update_),this.off(e,"mousemove",this.handleMouseMove_),this.off(e,"mouseup",this.handleMouseUp_),this.off(e,"touchmove",this.handleMouseMove_),this.off(e,"touchend",this.handleMouseUp_),this.removeAttribute("tabindex"),this.addClass("disabled"),this.playerEvent&&this.off(this.player_,this.playerEvent,this.update),this.enabled_=!1}createEl(e,t={},i={}){return t.className=t.className+" vjs-slider",t=Object.assign({tabIndex:0},t),i=Object.assign({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100},i),super.createEl(e,t,i)}handleMouseDown(e){const t=this.bar.el_.ownerDocument;e.type==="mousedown"&&e.preventDefault(),e.type==="touchstart"&&!Nr&&e.preventDefault(),uC(),this.addClass("vjs-sliding"),this.trigger("slideractive"),this.on(t,"mousemove",this.handleMouseMove_),this.on(t,"mouseup",this.handleMouseUp_),this.on(t,"touchmove",this.handleMouseMove_),this.on(t,"touchend",this.handleMouseUp_),this.handleMouseMove(e,!0)}handleMouseMove(e){}handleMouseUp(e){const t=this.bar.el_.ownerDocument;cC(),this.removeClass("vjs-sliding"),this.trigger("sliderinactive"),this.off(t,"mousemove",this.handleMouseMove_),this.off(t,"mouseup",this.handleMouseUp_),this.off(t,"touchmove",this.handleMouseMove_),this.off(t,"touchend",this.handleMouseUp_),this.update()}update(){if(!this.el_||!this.bar)return;const e=this.getProgress();return e===this.progress_||(this.progress_=e,this.requestNamedAnimationFrame("Slider#update",()=>{const t=this.vertical()?"height":"width";this.bar.el().style[t]=(e*100).toFixed(2)+"%"})),e}getProgress(){return Number(uh(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){const t=km(this.el_,e);return this.vertical()?t.y:t.x}handleKeyDown(e){const t=this.options_.playerOptions.spatialNavigation,i=t&&t.enabled,n=t&&t.horizontalSeek;i?n&&e.key==="ArrowLeft"||!n&&e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepBack()):n&&e.key==="ArrowRight"||!n&&e.key==="ArrowUp"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(this.pendingSeekTime()&&(this.pendingSeekTime(null),this.userSeek_(this.player_.currentTime())),super.handleKeyDown(e)):e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepBack()):e.key==="ArrowUp"||e.key==="ArrowRight"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):super.handleKeyDown(e)}handleClick(e){e.stopPropagation(),e.preventDefault()}vertical(e){if(e===void 0)return this.vertical_||!1;this.vertical_=!!e,this.vertical_?this.addClass("vjs-slider-vertical"):this.addClass("vjs-slider-horizontal")}}ke.registerComponent("Slider",MT);const Ay=(s,e)=>uh(s/e*100,0,100).toFixed(2)+"%";class h3 extends ke{constructor(e,t){super(e,t),this.partEls_=[],this.on(e,"progress",i=>this.update(i))}createEl(){const e=super.createEl("div",{className:"vjs-load-progress"}),t=gt("span",{className:"vjs-control-text"}),i=gt("span",{textContent:this.localize("Loaded")}),n=qe.createTextNode(": ");return this.percentageEl_=gt("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),e.appendChild(t),t.appendChild(i),t.appendChild(n),t.appendChild(this.percentageEl_),e}dispose(){this.partEls_=null,this.percentageEl_=null,super.dispose()}update(e){this.requestNamedAnimationFrame("LoadProgressBar#update",()=>{const t=this.player_.liveTracker,i=this.player_.buffered(),n=t&&t.isLive()?t.seekableEnd():this.player_.duration(),r=this.player_.bufferedEnd(),o=this.partEls_,u=Ay(r,n);this.percent_!==u&&(this.el_.style.width=u,Co(this.percentageEl_,u),this.percent_=u);for(let c=0;ci.length;c--)this.el_.removeChild(o[c-1]);o.length=i.length})}}ke.registerComponent("LoadProgressBar",h3);class f3 extends ke{constructor(e,t){super(e,t),this.update=Br(di(this,this.update),Bn)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){const n=Kd(this.el_),r=ic(this.player_.el()),o=e.width*t;if(!r||!n)return;let u=e.left-r.left+o,c=e.width-o+(r.right-e.right);c||(c=e.width-o,u=o);let d=n.width/2;un.width&&(d=n.width),d=Math.round(d),this.el_.style.right=`-${d}px`,this.write(i)}write(e){Co(this.el_,e)}updateTime(e,t,i,n){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;const o=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const u=this.player_.liveTracker.liveWindow(),c=u-t*u;r=(c<1?"":"-")+El(c,u)}else r=El(i,o);this.update(e,t,r),n&&n()})}}ke.registerComponent("TimeTooltip",f3);class NT extends ke{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=Br(di(this,this.update),Bn)}createEl(){return super.createEl("div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})}update(e,t,i){const n=this.getChild("timeTooltip");if(!n)return;const r=i&&i.target&&typeof i.target.pendingSeekTime=="function"?i.target.pendingSeekTime():this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();n.updateTime(e,t,r)}}NT.prototype.options_={children:[]};!Cs&&!ir&&NT.prototype.options_.children.push("timeTooltip");ke.registerComponent("PlayProgressBar",NT);class FC extends ke{constructor(e,t){super(e,t),this.update=Br(di(this,this.update),Bn)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t){const i=t*this.player_.duration();this.getChild("timeTooltip").updateTime(e,t,i,()=>{this.el_.style.left=`${e.width*t}px`})}}FC.prototype.options_={children:["timeTooltip"]};ke.registerComponent("MouseTimeDisplay",FC);class Fm extends MT{constructor(e,t){t=si(Fm.prototype.options_,t),t.children=[...t.children];const i=e.options_.disableSeekWhileScrubbingOnMobile&&(Cs||ir)||e.options_.disableSeekWhileScrubbingOnSTV;(!Cs&&!ir||i)&&t.children.splice(1,0,"mouseTimeDisplay"),super(e,t),this.shouldDisableSeekWhileScrubbing_=i,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=di(this,this.update),this.update=Br(this.update_,Bn),this.on(this.player_,["durationchange","timeupdate"],this.update),this.on(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in qe&&"visibilityState"in qe&&this.on(qe,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){qe.visibilityState==="hidden"?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(e)):(!this.player_.ended()&&!this.player_.paused()&&this.enableInterval_(),this.update())}enableInterval_(){this.updateInterval||(this.updateInterval=this.setInterval(this.update,Bn))}disableInterval_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&e&&e.type!=="ended"||this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)}createEl(){return super.createEl("div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})}update(e){if(qe.visibilityState==="hidden")return;const t=super.update();return this.requestNamedAnimationFrame("SeekBar#update",()=>{const i=this.player_.ended()?this.player_.duration():this.getCurrentTime_(),n=this.player_.liveTracker;let r=this.player_.duration();n&&n.isLive()&&(r=this.player_.liveTracker.liveCurrentTime()),this.percent_!==t&&(this.el_.setAttribute("aria-valuenow",(t*100).toFixed(2)),this.percent_=t),(this.currentTime_!==i||this.duration_!==r)&&(this.el_.setAttribute("aria-valuetext",this.localize("progress bar timing: currentTime={1} duration={2}",[El(i,r),El(r,r)],"{1} of {2}")),this.currentTime_=i,this.duration_=r),this.bar&&this.bar.update(ic(this.el()),this.getProgress(),e)}),t}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()}pendingSeekTime(e){if(e!==void 0)if(e!==null){const t=this.player_.duration();this.pendingSeekTime_=Math.max(0,Math.min(e,t))}else this.pendingSeekTime_=null;return this.pendingSeekTime_}getPercent(){if(this.pendingSeekTime()!==null)return this.pendingSeekTime()/this.player_.duration();const e=this.getCurrentTime_();let t;const i=this.player_.liveTracker;return i&&i.isLive()?(t=(e-i.seekableStart())/i.liveWindow(),i.atLiveEdge()&&(t=1)):t=e/this.player_.duration(),t}handleMouseDown(e){Yd(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!Yd(e)||isNaN(this.player_.duration()))return;!t&&!this.player_.scrubbing()&&this.player_.scrubbing(!0);let i;const n=this.calculateDistance(e),r=this.player_.liveTracker;if(!r||!r.isLive())i=n*this.player_.duration(),i===this.player_.duration()&&(i=i-.1);else{if(n>=.99){r.seekToLiveEdge();return}const o=r.seekableStart(),u=r.liveCurrentTime();if(i=o+n*r.liveWindow(),i>=u&&(i=u),i<=o&&(i=o+.1),i===1/0)return}this.shouldDisableSeekWhileScrubbing_?this.pendingSeekTime(i):this.userSeek_(i),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();const e=this.getChild("mouseTimeDisplay");e&&e.show()}disable(){super.disable();const e=this.getChild("mouseTimeDisplay");e&&e.hide()}handleMouseUp(e){super.handleMouseUp(e),e&&e.stopPropagation(),this.player_.scrubbing(!1),this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?wr(this.player_.play()):this.update_()}handlePendingSeek_(e){this.player_.paused()||this.player_.pause();const t=this.pendingSeekTime()!==null?this.pendingSeekTime():this.player_.currentTime();this.pendingSeekTime(t+e),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}stepForward(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(this.options().stepSeconds):this.userSeek_(this.player_.currentTime()+this.options().stepSeconds)}stepBack(){this.shouldDisableSeekWhileScrubbing_?this.handlePendingSeek_(-this.options().stepSeconds):this.userSeek_(this.player_.currentTime()-this.options().stepSeconds)}handleAction(e){this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(e){const t=this.player_.liveTracker;if(e.key===" "||e.key==="Enter")e.preventDefault(),e.stopPropagation(),this.handleAction(e);else if(e.key==="Home")e.preventDefault(),e.stopPropagation(),this.userSeek_(0);else if(e.key==="End")e.preventDefault(),e.stopPropagation(),t&&t.isLive()?this.userSeek_(t.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(e.key)){e.preventDefault(),e.stopPropagation();const i=parseInt(e.key,10)*.1;t&&t.isLive()?this.userSeek_(t.seekableStart()+t.liveWindow()*i):this.userSeek_(this.player_.duration()*i)}else e.key==="PageDown"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()-this.options().stepSeconds*this.options().pageMultiplier)):e.key==="PageUp"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()+this.options().stepSeconds*this.options().pageMultiplier)):super.handleKeyDown(e)}dispose(){this.disableInterval_(),this.off(this.player_,["durationchange","timeupdate"],this.update),this.off(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.update),this.off(this.player_,["playing"],this.enableIntervalHandler_),this.off(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in qe&&"visibilityState"in qe&&this.off(qe,"visibilitychange",this.toggleVisibility_),super.dispose()}}Fm.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar",stepSeconds:5,pageMultiplier:12};ke.registerComponent("SeekBar",Fm);class UC extends ke{constructor(e,t){super(e,t),this.handleMouseMove=Br(di(this,this.handleMouseMove),Bn),this.throttledHandleMouseSeek=Br(di(this,this.handleMouseSeek),Bn),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.handleMouseDownHandler_=i=>this.handleMouseDown(i),this.enable()}createEl(){return super.createEl("div",{className:"vjs-progress-control vjs-control"})}handleMouseMove(e){const t=this.getChild("seekBar");if(!t)return;const i=t.getChild("playProgressBar"),n=t.getChild("mouseTimeDisplay");if(!i&&!n)return;const r=t.el(),o=Kd(r);let u=km(r,e).x;u=uh(u,0,1),n&&n.update(o,u),i&&i.update(o,t.getProgress())}handleMouseSeek(e){const t=this.getChild("seekBar");t&&t.handleMouseMove(e)}enabled(){return this.enabled_}disable(){if(this.children().forEach(e=>e.disable&&e.disable()),!!this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.off(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){const e=this.getChild("seekBar");this.player_.scrubbing(!1),e.videoWasPlaying&&wr(this.player_.play())}}enable(){this.children().forEach(e=>e.enable&&e.enable()),!this.enabled()&&(this.on(["mousedown","touchstart"],this.handleMouseDownHandler_),this.on(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeClass("disabled"),this.enabled_=!0)}removeListenersAddedOnMousedownAndTouchstart(){const e=this.el_.ownerDocument;this.off(e,"mousemove",this.throttledHandleMouseSeek),this.off(e,"touchmove",this.throttledHandleMouseSeek),this.off(e,"mouseup",this.handleMouseUpHandler_),this.off(e,"touchend",this.handleMouseUpHandler_)}handleMouseDown(e){const t=this.el_.ownerDocument,i=this.getChild("seekBar");i&&i.handleMouseDown(e),this.on(t,"mousemove",this.throttledHandleMouseSeek),this.on(t,"touchmove",this.throttledHandleMouseSeek),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.getChild("seekBar");t&&t.handleMouseUp(e),this.removeListenersAddedOnMousedownAndTouchstart()}}UC.prototype.options_={children:["seekBar"]};ke.registerComponent("ProgressControl",UC);class $C extends ws{constructor(e,t){super(e,t),this.setIcon("picture-in-picture-enter"),this.on(e,["enterpictureinpicture","leavepictureinpicture"],i=>this.handlePictureInPictureChange(i)),this.on(e,["disablepictureinpicturechanged","loadedmetadata"],i=>this.handlePictureInPictureEnabledChange(i)),this.on(e,["loadedmetadata","audioonlymodechange","audiopostermodechange"],()=>this.handlePictureInPictureAudioModeChange()),this.disable()}buildCSSClass(){return`vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`}handlePictureInPictureAudioModeChange(){if(!(this.player_.currentType().substring(0,5)==="audio"||this.player_.audioPosterMode()||this.player_.audioOnlyMode())){this.show();return}this.player_.isInPictureInPicture()&&this.player_.exitPictureInPicture(),this.hide()}handlePictureInPictureEnabledChange(){qe.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in se?this.enable():this.disable()}handlePictureInPictureChange(e){this.player_.isInPictureInPicture()?(this.setIcon("picture-in-picture-exit"),this.controlText("Exit Picture-in-Picture")):(this.setIcon("picture-in-picture-enter"),this.controlText("Picture-in-Picture")),this.handlePictureInPictureEnabledChange()}handleClick(e){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()}show(){typeof qe.exitPictureInPicture=="function"&&super.show()}}$C.prototype.controlText_="Picture-in-Picture";ke.registerComponent("PictureInPictureToggle",$C);class jC extends ws{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),qe[e.fsApi_.fullscreenEnabled]===!1&&this.disable()}buildCSSClass(){return`vjs-fullscreen-control ${super.buildCSSClass()}`}handleFullscreenChange(e){this.player_.isFullscreen()?(this.controlText("Exit Fullscreen"),this.setIcon("fullscreen-exit")):(this.controlText("Fullscreen"),this.setIcon("fullscreen-enter"))}handleClick(e){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()}}jC.prototype.controlText_="Fullscreen";ke.registerComponent("FullscreenToggle",jC);const p3=function(s,e){e.tech_&&!e.tech_.featuresVolumeControl&&s.addClass("vjs-hidden"),s.on(e,"loadstart",function(){e.tech_.featuresVolumeControl?s.removeClass("vjs-hidden"):s.addClass("vjs-hidden")})};class m3 extends ke{createEl(){const e=super.createEl("div",{className:"vjs-volume-level"});return this.setIcon("circle",e),e.appendChild(super.createEl("span",{className:"vjs-control-text"})),e}}ke.registerComponent("VolumeLevel",m3);class g3 extends ke{constructor(e,t){super(e,t),this.update=Br(di(this,this.update),Bn)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,n){if(!i){const r=ic(this.el_),o=ic(this.player_.el()),u=e.width*t;if(!o||!r)return;const c=e.left-o.left+u,d=e.width-u+(o.right-e.right);let f=r.width/2;cr.width&&(f=r.width),this.el_.style.right=`-${f}px`}this.write(`${n}%`)}write(e){Co(this.el_,e)}updateVolume(e,t,i,n,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,n.toFixed(0)),r&&r()})}}ke.registerComponent("VolumeLevelTooltip",g3);class HC extends ke{constructor(e,t){super(e,t),this.update=Br(di(this,this.update),Bn)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t,i){const n=100*t;this.getChild("volumeLevelTooltip").updateVolume(e,t,i,n,()=>{i?this.el_.style.bottom=`${e.height*t}px`:this.el_.style.left=`${e.width*t}px`})}}HC.prototype.options_={children:["volumeLevelTooltip"]};ke.registerComponent("MouseVolumeLevelDisplay",HC);class Um extends MT{constructor(e,t){super(e,t),this.on("slideractive",i=>this.updateLastVolume_(i)),this.on(e,"volumechange",i=>this.updateARIAAttributes(i)),e.ready(()=>this.updateARIAAttributes())}createEl(){return super.createEl("div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})}handleMouseDown(e){Yd(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),n=ic(i),r=this.vertical();let o=km(i,e);o=r?o.y:o.x,o=uh(o,0,1),t.update(n,o,r)}Yd(e)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(e)))}checkMuted(){this.player_.muted()&&this.player_.muted(!1)}getPercent(){return this.player_.muted()?0:this.player_.volume()}stepForward(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)}stepBack(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)}updateARIAAttributes(e){const t=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",t),this.el_.setAttribute("aria-valuetext",t+"%")}volumeAsPercentage_(){return Math.round(this.player_.volume()*100)}updateLastVolume_(){const e=this.player_.volume();this.one("sliderinactive",()=>{this.player_.volume()===0&&this.player_.lastVolume_(e)})}}Um.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!Cs&&!ir&&Um.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");Um.prototype.playerEvent="volumechange";ke.registerComponent("VolumeBar",Um);class GC extends ke{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||ec(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),p3(this,e),this.throttledHandleMouseMove=Br(di(this,this.handleMouseMove),Bn),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.on("mousedown",i=>this.handleMouseDown(i)),this.on("touchstart",i=>this.handleMouseDown(i)),this.on("mousemove",i=>this.handleMouseMove(i)),this.on(this.volumeBar,["focus","slideractive"],()=>{this.volumeBar.addClass("vjs-slider-active"),this.addClass("vjs-slider-active"),this.trigger("slideractive")}),this.on(this.volumeBar,["blur","sliderinactive"],()=>{this.volumeBar.removeClass("vjs-slider-active"),this.removeClass("vjs-slider-active"),this.trigger("sliderinactive")})}createEl(){let e="vjs-volume-horizontal";return this.options_.vertical&&(e="vjs-volume-vertical"),super.createEl("div",{className:`vjs-volume-control vjs-control ${e}`})}handleMouseDown(e){const t=this.el_.ownerDocument;this.on(t,"mousemove",this.throttledHandleMouseMove),this.on(t,"touchmove",this.throttledHandleMouseMove),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.el_.ownerDocument;this.off(t,"mousemove",this.throttledHandleMouseMove),this.off(t,"touchmove",this.throttledHandleMouseMove),this.off(t,"mouseup",this.handleMouseUpHandler_),this.off(t,"touchend",this.handleMouseUpHandler_)}handleMouseMove(e){this.volumeBar.handleMouseMove(e)}}GC.prototype.options_={children:["volumeBar"]};ke.registerComponent("VolumeControl",GC);const y3=function(s,e){e.tech_&&!e.tech_.featuresMuteControl&&s.addClass("vjs-hidden"),s.on(e,"loadstart",function(){e.tech_.featuresMuteControl?s.removeClass("vjs-hidden"):s.addClass("vjs-hidden")})};class VC extends ws{constructor(e,t){super(e,t),y3(this,e),this.on(e,["loadstart","volumechange"],i=>this.update(i))}buildCSSClass(){return`vjs-mute-control ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.volume(),i=this.player_.lastVolume_();if(t===0){const n=i<.1?.1:i;this.player_.volume(n),this.player_.muted(!1)}else this.player_.muted(!this.player_.muted())}update(e){this.updateIcon_(),this.updateControlText_()}updateIcon_(){const e=this.player_.volume();let t=3;this.setIcon("volume-high"),Cs&&this.player_.tech_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),e===0||this.player_.muted()?(this.setIcon("volume-mute"),t=0):e<.33?(this.setIcon("volume-low"),t=1):e<.67&&(this.setIcon("volume-medium"),t=2),Lm(this.el_,[0,1,2,3].reduce((i,n)=>i+`${n?" ":""}vjs-vol-${n}`,"")),vl(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}VC.prototype.controlText_="Mute";ke.registerComponent("MuteToggle",VC);class qC extends ke{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||ec(t.volumeControl))&&(t.volumeControl=t.volumeControl||{},t.volumeControl.vertical=!t.inline),super(e,t),this.handleKeyPressHandler_=i=>this.handleKeyPress(i),this.on(e,["loadstart"],i=>this.volumePanelState_(i)),this.on(this.muteToggle,"keyup",i=>this.handleKeyPress(i)),this.on(this.volumeControl,"keyup",i=>this.handleVolumeControlKeyUp(i)),this.on("keydown",i=>this.handleKeyPress(i)),this.on("mouseover",i=>this.handleMouseOver(i)),this.on("mouseout",i=>this.handleMouseOut(i)),this.on(this.volumeControl,["slideractive"],this.sliderActive_),this.on(this.volumeControl,["sliderinactive"],this.sliderInactive_)}sliderActive_(){this.addClass("vjs-slider-active")}sliderInactive_(){this.removeClass("vjs-slider-active")}volumePanelState_(){this.volumeControl.hasClass("vjs-hidden")&&this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-hidden"),this.volumeControl.hasClass("vjs-hidden")&&!this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-mute-toggle-only")}createEl(){let e="vjs-volume-panel-horizontal";return this.options_.inline||(e="vjs-volume-panel-vertical"),super.createEl("div",{className:`vjs-volume-panel vjs-control ${e}`})}dispose(){this.handleMouseOut(),super.dispose()}handleVolumeControlKeyUp(e){e.key==="Escape"&&this.muteToggle.focus()}handleMouseOver(e){this.addClass("vjs-hover"),En(qe,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),Ds(qe,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}qC.prototype.options_={children:["muteToggle","volumeControl"]};ke.registerComponent("VolumePanel",qC);class zC extends ws{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipForwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`forward-${this.skipTime}`),this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipForwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.forward}buildCSSClass(){return`vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`}handleClick(e){if(isNaN(this.player_.duration()))return;const t=this.player_.currentTime(),i=this.player_.liveTracker,n=i&&i.isLive()?i.seekableEnd():this.player_.duration();let r;t+this.skipTime<=n?r=t+this.skipTime:r=n,this.player_.currentTime(r)}handleLanguagechange(){this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime]))}}zC.prototype.controlText_="Skip Forward";ke.registerComponent("SkipForward",zC);class KC extends ws{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipBackwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`replay-${this.skipTime}`),this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipBackwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.backward}buildCSSClass(){return`vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.currentTime(),i=this.player_.liveTracker,n=i&&i.isLive()&&i.seekableStart();let r;n&&t-this.skipTime<=n?r=n:t>=this.skipTime?r=t-this.skipTime:r=0,this.player_.currentTime(r)}handleLanguagechange(){this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime]))}}KC.prototype.controlText_="Skip Backward";ke.registerComponent("SkipBackward",KC);class YC extends ke{constructor(e,t){super(e,t),t&&(this.menuButton_=t.menuButton),this.focusedChild_=-1,this.on("keydown",i=>this.handleKeyDown(i)),this.boundHandleBlur_=i=>this.handleBlur(i),this.boundHandleTapClick_=i=>this.handleTapClick(i)}addEventListenerForItem(e){e instanceof ke&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof ke&&(this.off(e,"blur",this.boundHandleBlur_),this.off(e,["tap","click"],this.boundHandleTapClick_))}removeChild(e){typeof e=="string"&&(e=this.getChild(e)),this.removeEventListenerForItem(e),super.removeChild(e)}addItem(e){const t=this.addChild(e);t&&this.addEventListenerForItem(t)}createEl(){const e=this.options_.contentElType||"ul";this.contentEl_=gt(e,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");const t=super.createEl("div",{append:this.contentEl_,className:"vjs-menu"});return t.appendChild(this.contentEl_),En(t,"click",function(i){i.preventDefault(),i.stopImmediatePropagation()}),t}dispose(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,super.dispose()}handleBlur(e){const t=e.relatedTarget||qe.activeElement;if(!this.children().some(i=>i.el()===t)){const i=this.menuButton_;i&&i.buttonPressed_&&t!==i.el().firstChild&&i.unpressButton()}}handleTapClick(e){if(this.menuButton_){this.menuButton_.unpressButton();const t=this.children();if(!Array.isArray(t))return;const i=t.filter(n=>n.el()===e.target)[0];if(!i)return;i.name()!=="CaptionSettingsMenuItem"&&this.menuButton_.focus()}}handleKeyDown(e){e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(e.key==="ArrowRight"||e.key==="ArrowUp")&&(e.preventDefault(),e.stopPropagation(),this.stepBack())}stepForward(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_+1),this.focus(e)}stepBack(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_-1),this.focus(e)}focus(e=0){const t=this.children().slice();t.length&&t[0].hasClass("vjs-menu-title")&&t.shift(),t.length>0&&(e<0?e=0:e>=t.length&&(e=t.length-1),this.focusedChild_=e,t[e].el_.focus())}}ke.registerComponent("Menu",YC);class BT extends ke{constructor(e,t={}){super(e,t),this.menuButton_=new ws(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=ws.prototype.buildCSSClass();this.menuButton_.el_.className=this.buildCSSClass()+" "+i,this.menuButton_.removeClass("vjs-control"),this.addChild(this.menuButton_),this.update(),this.enabled_=!0;const n=r=>this.handleClick(r);this.handleMenuKeyUp_=r=>this.handleMenuKeyUp(r),this.on(this.menuButton_,"tap",n),this.on(this.menuButton_,"click",n),this.on(this.menuButton_,"keydown",r=>this.handleKeyDown(r)),this.on(this.menuButton_,"mouseenter",()=>{this.addClass("vjs-hover"),this.menu.show(),En(qe,"keyup",this.handleMenuKeyUp_)}),this.on("mouseleave",r=>this.handleMouseLeave(r)),this.on("keydown",r=>this.handleSubmenuKeyDown(r))}update(){const e=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=e,this.addChild(e),this.buttonPressed_=!1,this.menuButton_.el_.setAttribute("aria-expanded","false"),this.items&&this.items.length<=this.hideThreshold_?(this.hide(),this.menu.contentEl_.removeAttribute("role")):(this.show(),this.menu.contentEl_.setAttribute("role","menu"))}createMenu(){const e=new YC(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=gt("li",{className:"vjs-menu-title",textContent:ki(this.options_.title),tabIndex:-1}),i=new ke(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,u)},o=(...u)=>{this.handleSelectedLanguageChange.apply(this,u)};if(e.on(["loadstart","texttrackchange"],r),n.addEventListener("change",r),n.addEventListener("selectedlanguagechange",o),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),n.removeEventListener("change",r),n.removeEventListener("selectedlanguagechange",o)}),n.onchange===void 0){let u;this.on(["tap","click"],function(){if(typeof se.Event!="object")try{u=new se.Event("change")}catch{}u||(u=qe.createEvent("Event"),u.initEvent("change",!0,!0)),n.dispatchEvent(u)})}this.handleTracksChange()}handleClick(e){const t=this.track,i=this.player_.textTracks();if(super.handleClick(e),!!i)for(let n=0;n-1&&o.mode==="showing"){i=!1;break}}i!==this.isSelected_&&this.selected(i)}handleSelectedLanguageChange(e){const t=this.player().textTracks();let i=!0;for(let n=0,r=t.length;n-1&&o.mode==="showing"){i=!1;break}}i&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}}ke.registerComponent("OffTextTrackMenuItem",WC);class fc extends FT{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=dh){let i;this.label_&&(i=`${this.label_} off`),e.push(new WC(this.player_,{kinds:this.kinds_,kind:this.kind_,label:i})),this.hideThreshold_+=1;const n=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let r=0;r-1){const u=new t(this.player_,{track:o,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});u.addClass(`vjs-${o.kind}-menu-item`),e.push(u)}}return e}}ke.registerComponent("TextTrackButton",fc);class XC extends ch{constructor(e,t){const i=t.track,n=t.cue,r=e.currentTime();t.selectable=!0,t.multiSelectable=!1,t.label=n.text,t.selected=n.startTime<=r&&r{this.items.forEach(n=>{n.selected(this.track_.activeCues[0]===n.cue)})}}buildCSSClass(){return`vjs-chapters-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-chapters-button ${super.buildWrapperCSSClass()}`}update(e){if(e&&e.track&&e.track.kind!=="chapters")return;const t=this.findChaptersTrack();t!==this.track_?(this.setTrack(t),super.update()):(!this.items||t&&t.cues&&t.cues.length!==this.items.length)&&super.update()}setTrack(e){if(this.track_!==e){if(this.updateHandler_||(this.updateHandler_=this.update.bind(this)),this.track_){const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.removeEventListener("load",this.updateHandler_),this.track_.removeEventListener("cuechange",this.selectCurrentItem_),this.track_=null}if(this.track_=e,this.track_){this.track_.mode="hidden";const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.addEventListener("load",this.updateHandler_),this.track_.addEventListener("cuechange",this.selectCurrentItem_)}}}findChaptersTrack(){const e=this.player_.textTracks()||[];for(let t=e.length-1;t>=0;t--){const i=e[t];if(i.kind===this.kind_)return i}}getMenuCaption(){return this.track_&&this.track_.label?this.track_.label:this.localize(ki(this.kind_))}createMenu(){return this.options_.title=this.getMenuCaption(),super.createMenu()}createItems(){const e=[];if(!this.track_)return e;const t=this.track_.cues;if(!t)return e;for(let i=0,n=t.length;i-1&&(this.label_="captions",this.setIcon("captions")),this.menuButton_.controlText(ki(this.label_))}buildCSSClass(){return`vjs-subs-caps-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-subs-caps-button ${super.buildWrapperCSSClass()}`}createItems(){let e=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(e.push(new HT(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,QC),e}}VT.prototype.kinds_=["captions","subtitles"];VT.prototype.controlText_="Subtitles";ke.registerComponent("SubsCapsButton",VT);class ZC extends ch{constructor(e,t){const i=t.track,n=e.audioTracks();t.label=i.label||i.language||"Unknown",t.selected=i.enabled,super(e,t),this.track=i,this.addClass(`vjs-${i.kind}-menu-item`);const r=(...o)=>{this.handleTracksChange.apply(this,o)};n.addEventListener("change",r),this.on("dispose",()=>{n.removeEventListener("change",r)})}createEl(e,t,i){const n=super.createEl(e,t,i),r=n.querySelector(".vjs-menu-item-text");return["main-desc","descriptions"].indexOf(this.options_.track.kind)>=0&&(r.appendChild(gt("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(gt("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),n}handleClick(e){if(super.handleClick(e),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks){const t=this.player_.audioTracks();for(let i=0;ithis.update(r))}handleClick(e){super.handleClick(),this.player().playbackRate(this.rate)}update(e){this.selected(this.player().playbackRate()===this.rate)}}qT.prototype.contentElType="button";ke.registerComponent("PlaybackRateMenuItem",qT);class eD extends BT{constructor(e,t){super(e,t),this.menuButton_.el_.setAttribute("aria-describedby",this.labelElId_),this.updateVisibility(),this.updateLabel(),this.on(e,"loadstart",i=>this.updateVisibility(i)),this.on(e,"ratechange",i=>this.updateLabel(i)),this.on(e,"playbackrateschange",i=>this.handlePlaybackRateschange(i))}createEl(){const e=super.createEl();return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=gt("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),e.appendChild(this.labelEl_),e}dispose(){this.labelEl_=null,super.dispose()}buildCSSClass(){return`vjs-playback-rate ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-playback-rate ${super.buildWrapperCSSClass()}`}createItems(){const e=this.playbackRates(),t=[];for(let i=e.length-1;i>=0;i--)t.push(new qT(this.player(),{rate:e[i]+"x"}));return t}handlePlaybackRateschange(e){this.update()}playbackRates(){const e=this.player();return e.playbackRates&&e.playbackRates()||[]}playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0}updateVisibility(e){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")}updateLabel(e){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")}}eD.prototype.controlText_="Playback Rate";ke.registerComponent("PlaybackRateMenuButton",eD);class tD extends ke{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}ke.registerComponent("Spacer",tD);class v3 extends tD{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}ke.registerComponent("CustomControlSpacer",v3);class iD extends ke{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}iD.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};ke.registerComponent("ControlBar",iD);class sD extends dc{constructor(e,t){super(e,t),this.on(e,"error",i=>{this.open(i)})}buildCSSClass(){return`vjs-error-display ${super.buildCSSClass()}`}content(){const e=this.player().error();return e?this.localize(e.message):""}}sD.prototype.options_=Object.assign({},dc.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});ke.registerComponent("ErrorDisplay",sD);class nD extends ke{constructor(e,t={}){super(e,t),this.el_.setAttribute("aria-labelledby",this.selectLabelledbyIds)}createEl(){return this.selectLabelledbyIds=[this.options_.legendId,this.options_.labelId].join(" ").trim(),gt("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${Nn()}`)+"-"+t[1].replace(/\W+/g,""),n=gt("option",{id:i,value:this.localize(t[0]),textContent:this.localize(t[1])});return n.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),n}))}}ke.registerComponent("TextTrackSelect",nD);class bl extends ke{constructor(e,t={}){super(e,t);const i=gt("legend",{textContent:this.localize(this.options_.legendText),id:this.options_.legendId});this.el().appendChild(i);const n=this.options_.selects;for(const r of n){const o=this.options_.selectConfigs[r],u=o.className,c=o.id.replace("%s",this.options_.id_);let d=null;const f=`vjs_select_${Nn()}`;if(this.options_.type==="colors"){d=gt("span",{className:u});const g=gt("label",{id:c,className:"vjs-label",textContent:this.localize(o.label)});g.setAttribute("for",f),d.appendChild(g)}const m=new nD(e,{SelectOptions:o.options,legendId:this.options_.legendId,id:f,labelId:c});this.addChild(m),this.options_.type==="colors"&&(d.appendChild(m.el()),this.el().appendChild(d))}}createEl(){return gt("fieldset",{className:this.options_.className})}}ke.registerComponent("TextTrackFieldset",bl);class rD extends ke{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new bl(e,{id_:i,legendId:`captions-text-legend-${i}`,legendText:this.localize("Text"),className:"vjs-fg vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(n);const r=new bl(e,{id_:i,legendId:`captions-background-${i}`,legendText:this.localize("Text Background"),className:"vjs-bg vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(r);const o=new bl(e,{id_:i,legendId:`captions-window-${i}`,legendText:this.localize("Caption Area Background"),className:"vjs-window vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(o)}createEl(){return gt("div",{className:"vjs-track-settings-colors"})}}ke.registerComponent("TextTrackSettingsColors",rD);class aD extends ke{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new bl(e,{id_:i,legendId:`captions-font-size-${i}`,legendText:"Font Size",className:"vjs-font-percent vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(n);const r=new bl(e,{id_:i,legendId:`captions-edge-style-${i}`,legendText:this.localize("Text Edge Style"),className:"vjs-edge-style vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(r);const o=new bl(e,{id_:i,legendId:`captions-font-family-${i}`,legendText:this.localize("Font Family"),className:"vjs-font-family vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(o)}createEl(){return gt("div",{className:"vjs-track-settings-font"})}}ke.registerComponent("TextTrackSettingsFont",aD);class oD extends ke{constructor(e,t={}){super(e,t);const i=new ws(e,{controlText:this.localize("restore all settings to the default values"),className:"vjs-default-button"});i.el().classList.remove("vjs-control","vjs-button"),i.el().textContent=this.localize("Reset"),this.addChild(i);const n=this.localize("Done"),r=new ws(e,{controlText:n,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=n,this.addChild(r)}createEl(){return gt("div",{className:"vjs-track-settings-controls"})}}ke.registerComponent("TrackSettingsControls",oD);const Cy="vjs-text-track-settings",GE=["#000","Black"],VE=["#00F","Blue"],qE=["#0FF","Cyan"],zE=["#0F0","Green"],KE=["#F0F","Magenta"],YE=["#F00","Red"],WE=["#FFF","White"],XE=["#FF0","Yellow"],Dy=["1","Opaque"],wy=["0.5","Semi-Transparent"],QE=["0","Transparent"],po={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[GE,WE,YE,zE,VE,XE,KE,qE],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[Dy,wy,QE],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[WE,GE,YE,zE,VE,XE,KE,qE],className:"vjs-text-color"},edgeStyle:{selector:".vjs-edge-style > select",id:"",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Drop shadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"",label:"Font Family",options:[["proportionalSansSerif","Proportional Sans-Serif"],["monospaceSansSerif","Monospace Sans-Serif"],["proportionalSerif","Proportional Serif"],["monospaceSerif","Monospace Serif"],["casual","Casual"],["script","Script"],["small-caps","Small Caps"]]},fontPercent:{selector:".vjs-font-percent > select",id:"",label:"Font Size",options:[["0.50","50%"],["0.75","75%"],["1.00","100%"],["1.25","125%"],["1.50","150%"],["1.75","175%"],["2.00","200%"],["3.00","300%"],["4.00","400%"]],default:2,parser:s=>s==="1.00"?null:Number(s)},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Opacity",options:[Dy,wy],className:"vjs-text-opacity vjs-opacity"},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color",className:"vjs-window-color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Opacity",options:[QE,wy,Dy],className:"vjs-window-opacity vjs-opacity"}};po.windowColor.options=po.backgroundColor.options;function lD(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function T3(s,e){const t=s.options[s.options.selectedIndex].value;return lD(t,e)}function b3(s,e,t){if(e){for(let i=0;i{this.saveSettings(),this.close()}),this.on(this.$(".vjs-default-button"),["click","tap"],()=>{this.setDefaults(),this.updateDisplay()}),Bu(po,e=>{this.on(this.$(e.selector),"change",this.updateDisplay)})}dispose(){this.endDialog=null,super.dispose()}label(){return this.localize("Caption Settings Dialog")}description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")}buildCSSClass(){return super.buildCSSClass()+" vjs-text-track-settings"}getValues(){return QA(po,(e,t,i)=>{const n=T3(this.$(t.selector),t.parser);return n!==void 0&&(e[i]=n),e},{})}setValues(e){Bu(po,(t,i)=>{b3(this.$(t.selector),e[i],t.parser)})}setDefaults(){Bu(po,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(se.localStorage.getItem(Cy))}catch(t){It.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?se.localStorage.setItem(Cy,JSON.stringify(e)):se.localStorage.removeItem(Cy)}catch(t){It.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}ke.registerComponent("TextTrackSettings",_3);class x3 extends ke{constructor(e,t){let i=t.ResizeObserver||se.ResizeObserver;t.ResizeObserver===null&&(i=!1);const n=si({createEl:!i,reportTouchActivity:!1},t);super(e,n),this.ResizeObserver=t.ResizeObserver||se.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=bC(()=>{this.resizeHandler()},100,!1,this),i?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(e.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;const r=this.debouncedHandler_;let o=this.unloadListener_=function(){Ds(this,"resize",r),Ds(this,"unload",o),o=null};En(this.el_.contentWindow,"unload",o),En(this.el_.contentWindow,"resize",r)},this.one("load",this.loadListener_))}createEl(){return super.createEl("iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No content")},{"aria-hidden":"true"})}resizeHandler(){!this.player_||!this.player_.trigger||this.player_.trigger("playerresize")}dispose(){this.debouncedHandler_&&this.debouncedHandler_.cancel(),this.resizeObserver_&&(this.player_.el()&&this.resizeObserver_.unobserve(this.player_.el()),this.resizeObserver_.disconnect()),this.loadListener_&&this.off("load",this.loadListener_),this.el_&&this.el_.contentWindow&&this.unloadListener_&&this.unloadListener_.call(this.el_.contentWindow),this.ResizeObserver=null,this.resizeObserver=null,this.debouncedHandler_=null,this.loadListener_=null,super.dispose()}}ke.registerComponent("ResizeManager",x3);const S3={trackingThreshold:20,liveTolerance:15};class E3 extends ke{constructor(e,t){const i=si(S3,t,{createEl:!1});super(e,i),this.trackLiveHandler_=()=>this.trackLive_(),this.handlePlay_=n=>this.handlePlay(n),this.handleFirstTimeupdate_=n=>this.handleFirstTimeupdate(n),this.handleSeeked_=n=>this.handleSeeked(n),this.seekToLiveEdge_=n=>this.seekToLiveEdge(n),this.reset_(),this.on(this.player_,"durationchange",n=>this.handleDurationchange(n)),this.on(this.player_,"canplay",()=>this.toggleTracking())}trackLive_(){const e=this.player_.seekable();if(!e||!e.length)return;const t=Number(se.performance.now().toFixed(4)),i=this.lastTime_===-1?0:(t-this.lastTime_)/1e3;this.lastTime_=t,this.pastSeekEnd_=this.pastSeekEnd()+i;const n=this.liveCurrentTime(),r=this.player_.currentTime();let o=this.player_.paused()||this.seekedBehindLive_||Math.abs(n-r)>this.options_.liveTolerance;(!this.timeupdateSeen_||n===1/0)&&(o=!1),o!==this.behindLiveEdge_&&(this.behindLiveEdge_=o,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,Bn),this.trackLive_(),this.on(this.player_,["play","pause"],this.trackLiveHandler_),this.timeupdateSeen_?this.on(this.player_,"seeked",this.handleSeeked_):(this.one(this.player_,"play",this.handlePlay_),this.one(this.player_,"timeupdate",this.handleFirstTimeupdate_)))}handleFirstTimeupdate(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)}handleSeeked(){const e=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&e>2,this.nextSeekedFromUser_=!1,this.trackLive_()}handlePlay(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)}reset_(){this.lastTime_=-1,this.pastSeekEnd_=0,this.lastSeekEnd_=-1,this.behindLiveEdge_=!0,this.timeupdateSeen_=!1,this.seekedBehindLive_=!1,this.nextSeekedFromUser_=!1,this.clearInterval(this.trackingInterval_),this.trackingInterval_=null,this.off(this.player_,["play","pause"],this.trackLiveHandler_),this.off(this.player_,"seeked",this.handleSeeked_),this.off(this.player_,"play",this.handlePlay_),this.off(this.player_,"timeupdate",this.handleFirstTimeupdate_),this.off(this.player_,"timeupdate",this.seekToLiveEdge_)}nextSeekedFromUser(){this.nextSeekedFromUser_=!0}stopTracking(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))}seekableEnd(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.end(i));return t.length?t.sort()[t.length-1]:1/0}seekableStart(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.start(i));return t.length?t.sort()[0]:0}liveWindow(){const e=this.liveCurrentTime();return e===1/0?0:e-this.seekableStart()}isLive(){return this.isTracking()}atLiveEdge(){return!this.behindLiveEdge()}liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd()}pastSeekEnd(){const e=this.seekableEnd();return this.lastSeekEnd_!==-1&&e!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=e,this.pastSeekEnd_}behindLiveEdge(){return this.behindLiveEdge_}isTracking(){return typeof this.trackingInterval_=="number"}seekToLiveEdge(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))}dispose(){this.stopTracking(),super.dispose()}}ke.registerComponent("LiveTracker",E3);class A3 extends ke{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:gt("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${Nn()}`}),description:gt("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${Nn()}`})},gt("div",{className:"vjs-title-bar"},{},ZA(this.els))}updateDom_(){const e=this.player_.tech_,t=e&&e.el_,i={title:"aria-labelledby",description:"aria-describedby"};["title","description"].forEach(n=>{const r=this.state[n],o=this.els[n],u=i[n];Rm(o),r&&Co(o,r),t&&(t.removeAttribute(u),r&&t.setAttribute(u,o.id))}),this.state.title||this.state.description?this.show():this.hide()}update(e){this.setState(e)}dispose(){const e=this.player_.tech_,t=e&&e.el_;t&&(t.removeAttribute("aria-labelledby"),t.removeAttribute("aria-describedby")),super.dispose(),this.els=null}}ke.registerComponent("TitleBar",A3);const C3={initialDisplay:4e3,position:[],takeFocus:!1};class D3 extends ws{constructor(e,t){t=si(C3,t),super(e,t),this.controlText(t.controlText),this.hide(),this.on(this.player_,["useractive","userinactive"],i=>{this.removeClass("force-display")})}buildCSSClass(){return`vjs-transient-button focus-visible ${this.options_.position.map(e=>`vjs-${e}`).join(" ")}`}createEl(){const e=gt("button",{},{type:"button",class:this.buildCSSClass()},gt("span"));return this.controlTextEl_=e.querySelector("span"),e}show(){super.show(),this.addClass("force-display"),this.options_.takeFocus&&this.el().focus({preventScroll:!0}),this.forceDisplayTimeout=this.player_.setTimeout(()=>{this.removeClass("force-display")},this.options_.initialDisplay)}hide(){this.removeClass("force-display"),super.hide()}dispose(){this.player_.clearTimeout(this.forceDisplayTimeout),super.dispose()}}ke.registerComponent("TransientButton",D3);const wv=s=>{const e=s.el();if(e.hasAttribute("src"))return s.triggerSourceset(e.src),!0;const t=s.$$("source"),i=[];let n="";if(!t.length)return!1;for(let r=0;r{let t={};for(let i=0;iuD([s.el(),se.HTMLMediaElement.prototype,se.Element.prototype,w3],"innerHTML"),ZE=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=L3(s),n=r=>(...o)=>{const u=r.apply(e,o);return wv(s),u};["append","appendChild","insertAdjacentHTML"].forEach(r=>{e[r]&&(t[r]=e[r],e[r]=n(t[r]))}),Object.defineProperty(e,"innerHTML",si(i,{set:n(i.set)})),e.resetSourceWatch_=()=>{e.resetSourceWatch_=null,Object.keys(t).forEach(r=>{e[r]=t[r]}),Object.defineProperty(e,"innerHTML",i)},s.one("sourceset",e.resetSourceWatch_)},I3=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?kC(se.Element.prototype.getAttribute.call(this,"src")):""},set(s){return se.Element.prototype.setAttribute.call(this,"src",s),s}}),k3=s=>uD([s.el(),se.HTMLMediaElement.prototype,I3],"src"),R3=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=k3(s),i=e.setAttribute,n=e.load;Object.defineProperty(e,"src",si(t,{set:r=>{const o=t.set.call(e,r);return s.triggerSourceset(e.src),o}})),e.setAttribute=(r,o)=>{const u=i.call(e,r,o);return/src/i.test(r)&&s.triggerSourceset(e.src),u},e.load=()=>{const r=n.call(e);return wv(s)||(s.triggerSourceset(""),ZE(s)),r},e.currentSrc?s.triggerSourceset(e.currentSrc):wv(s)||ZE(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=n,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class et extends Et{constructor(e,t){super(e,t);const i=e.source;let n=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&this.el_.tagName==="VIDEO",i&&(this.el_.currentSrc!==i.src||e.tag&&e.tag.initNetworkState_===3)?this.setSource(i):this.handleLateInit_(this.el_),e.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){const r=this.el_.childNodes;let o=r.length;const u=[];for(;o--;){const c=r[o];c.nodeName.toLowerCase()==="track"&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(c),this.remoteTextTracks().addTrack(c.track),this.textTracks().addTrack(c.track),!n&&!this.el_.hasAttribute("crossorigin")&&Nm(c.src)&&(n=!0)):u.push(c))}for(let c=0;c{t=[];for(let r=0;re.removeEventListener("change",i));const n=()=>{for(let r=0;r{e.removeEventListener("change",i),e.removeEventListener("change",n),e.addEventListener("change",n)}),this.on("webkitendfullscreen",()=>{e.removeEventListener("change",i),e.addEventListener("change",i),e.removeEventListener("change",n)})}overrideNative_(e,t){if(t!==this[`featuresNative${e}Tracks`])return;const i=e.toLowerCase();this[`${i}TracksListeners_`]&&Object.keys(this[`${i}TracksListeners_`]).forEach(n=>{this.el()[`${i}Tracks`].removeEventListener(n,this[`${i}TracksListeners_`][n])}),this[`featuresNative${e}Tracks`]=!t,this[`${i}TracksListeners_`]=null,this.proxyNativeTracksForType_(i)}overrideNativeAudioTracks(e){this.overrideNative_("Audio",e)}overrideNativeVideoTracks(e){this.overrideNative_("Video",e)}proxyNativeTracksForType_(e){const t=Mn[e],i=this.el()[t.getterName],n=this[t.getterName]();if(!this[`featuresNative${t.capitalName}Tracks`]||!i||!i.addEventListener)return;const r={change:u=>{const c={type:"change",target:n,currentTarget:n,srcElement:n};n.trigger(c),e==="text"&&this[nc.remoteText.getterName]().trigger(c)},addtrack(u){n.addTrack(u.track)},removetrack(u){n.removeTrack(u.track)}},o=function(){const u=[];for(let c=0;c{const c=r[u];i.addEventListener(u,c),this.on("dispose",d=>i.removeEventListener(u,c))}),this.on("loadstart",o),this.on("dispose",u=>this.off("loadstart",o))}proxyNativeTracks_(){Mn.names.forEach(e=>{this.proxyNativeTracksForType_(e)})}createEl(){let e=this.options_.tag;if(!e||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(e){const i=e.cloneNode(!0);e.parentNode&&e.parentNode.insertBefore(i,e),et.disposeMediaElement(e),e=i}else{e=qe.createElement("video");const i=this.options_.tag&&fo(this.options_.tag),n=si({},i);(!zd||this.options_.nativeControlsForTouch!==!0)&&delete n.controls,oC(e,Object.assign(n,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&tc(e,"preload",this.options_.preload),this.options_.disablePictureInPicture!==void 0&&(e.disablePictureInPicture=this.options_.disablePictureInPicture);const t=["loop","muted","playsinline","autoplay"];for(let i=0;i=2&&t.push("loadeddata"),e.readyState>=3&&t.push("canplay"),e.readyState>=4&&t.push("canplaythrough"),this.ready(function(){t.forEach(function(i){this.trigger(i)},this)})}setScrubbing(e){this.isScrubbing_=e}scrubbing(){return this.isScrubbing_}setCurrentTime(e){try{this.isScrubbing_&&this.el_.fastSeek&&wm?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){It(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&ir&&Nr&&this.el_.currentTime===0){const e=()=>{this.el_.currentTime>0&&(this.el_.duration===1/0&&this.trigger("durationchange"),this.off("timeupdate",e))};return this.on("timeupdate",e),NaN}return this.el_.duration||NaN}width(){return this.el_.offsetWidth}height(){return this.el_.offsetHeight}proxyWebkitFullscreen_(){if(!("webkitDisplayingFullscreen"in this.el_))return;const e=function(){this.trigger("fullscreenchange",{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},t=function(){"webkitPresentationMode"in this.el_&&this.el_.webkitPresentationMode!=="picture-in-picture"&&(this.one("webkitendfullscreen",e),this.trigger("fullscreenchange",{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on("webkitbeginfullscreen",t),this.on("dispose",()=>{this.off("webkitbeginfullscreen",t),this.off("webkitendfullscreen",e)})}supportsFullScreen(){return typeof this.el_.webkitEnterFullScreen=="function"}enterFullScreen(){const e=this.el_;if(e.paused&&e.networkState<=e.HAVE_METADATA)wr(this.el_.play()),this.setTimeout(function(){e.pause();try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}},0);else try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}}exitFullScreen(){if(!this.el_.webkitDisplayingFullscreen){this.trigger("fullscreenerror",new Error("The video is not fullscreen"));return}this.el_.webkitExitFullScreen()}requestPictureInPicture(){return this.el_.requestPictureInPicture()}requestVideoFrameCallback(e){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(e):super.requestVideoFrameCallback(e)}cancelVideoFrameCallback(e){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(e):super.cancelVideoFrameCallback(e)}src(e){if(e===void 0)return this.el_.src;this.setSrc(e)}addSourceElement(e,t){if(!e)return It.error("Invalid source URL."),!1;const i={src:e};t&&(i.type=t);const n=gt("source",{},i);return this.el_.appendChild(n),!0}removeSourceElement(e){if(!e)return It.error("Source URL is required to remove the source element."),!1;const t=this.el_.querySelectorAll("source");for(const i of t)if(i.src===e)return this.el_.removeChild(i),!0;return It.warn(`No matching source element found with src: ${e}`),!1}reset(){et.resetMediaElement(this.el_)}currentSrc(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc}setControls(e){this.el_.controls=!!e}addTextTrack(e,t,i){return this.featuresNativeTextTracks?this.el_.addTextTrack(e,t,i):super.addTextTrack(e,t,i)}createRemoteTextTrack(e){if(!this.featuresNativeTextTracks)return super.createRemoteTextTrack(e);const t=qe.createElement("track");return e.kind&&(t.kind=e.kind),e.label&&(t.label=e.label),(e.language||e.srclang)&&(t.srclang=e.language||e.srclang),e.default&&(t.default=e.default),e.id&&(t.id=e.id),e.src&&(t.src=e.src),t}addRemoteTextTrack(e,t){const i=super.addRemoteTextTrack(e,t);return this.featuresNativeTextTracks&&this.el().appendChild(i),i}removeRemoteTextTrack(e){if(super.removeRemoteTextTrack(e),this.featuresNativeTextTracks){const t=this.$$("track");let i=t.length;for(;i--;)(e===t[i]||e===t[i].track)&&this.el().removeChild(t[i])}}getVideoPlaybackQuality(){if(typeof this.el().getVideoPlaybackQuality=="function")return this.el().getVideoPlaybackQuality();const e={};return typeof this.el().webkitDroppedFrameCount<"u"&&typeof this.el().webkitDecodedFrameCount<"u"&&(e.droppedVideoFrames=this.el().webkitDroppedFrameCount,e.totalVideoFrames=this.el().webkitDecodedFrameCount),se.performance&&(e.creationTime=se.performance.now()),e}}Em(et,"TEST_VID",function(){if(!lc())return;const s=qe.createElement("video"),e=qe.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});et.isSupported=function(){try{et.TEST_VID.volume=.5}catch{return!1}return!!(et.TEST_VID&&et.TEST_VID.canPlayType)};et.canPlayType=function(s){return et.TEST_VID.canPlayType(s)};et.canPlaySource=function(s,e){return et.canPlayType(s.type)};et.canControlVolume=function(){try{const s=et.TEST_VID.volume;et.TEST_VID.volume=s/2+.1;const e=s!==et.TEST_VID.volume;return e&&Cs?(se.setTimeout(()=>{et&&et.prototype&&(et.prototype.featuresVolumeControl=s!==et.TEST_VID.volume)}),!1):e}catch{return!1}};et.canMuteVolume=function(){try{const s=et.TEST_VID.muted;return et.TEST_VID.muted=!s,et.TEST_VID.muted?tc(et.TEST_VID,"muted","muted"):Im(et.TEST_VID,"muted","muted"),s!==et.TEST_VID.muted}catch{return!1}};et.canControlPlaybackRate=function(){if(ir&&Nr&&Am<58)return!1;try{const s=et.TEST_VID.playbackRate;return et.TEST_VID.playbackRate=s/2+.1,s!==et.TEST_VID.playbackRate}catch{return!1}};et.canOverrideAttributes=function(){try{const s=()=>{};Object.defineProperty(qe.createElement("video"),"src",{get:s,set:s}),Object.defineProperty(qe.createElement("audio"),"src",{get:s,set:s}),Object.defineProperty(qe.createElement("video"),"innerHTML",{get:s,set:s}),Object.defineProperty(qe.createElement("audio"),"innerHTML",{get:s,set:s})}catch{return!1}return!0};et.supportsNativeTextTracks=function(){return wm||Cs&&Nr};et.supportsNativeVideoTracks=function(){return!!(et.TEST_VID&&et.TEST_VID.videoTracks)};et.supportsNativeAudioTracks=function(){return!!(et.TEST_VID&&et.TEST_VID.audioTracks)};et.Events=["loadstart","suspend","abort","error","emptied","stalled","loadedmetadata","loadeddata","canplay","canplaythrough","playing","waiting","seeking","seeked","ended","durationchange","timeupdate","progress","play","pause","ratechange","resize","volumechange"];[["featuresMuteControl","canMuteVolume"],["featuresPlaybackRate","canControlPlaybackRate"],["featuresSourceset","canOverrideAttributes"],["featuresNativeTextTracks","supportsNativeTextTracks"],["featuresNativeVideoTracks","supportsNativeVideoTracks"],["featuresNativeAudioTracks","supportsNativeAudioTracks"]].forEach(function([s,e]){Em(et.prototype,s,()=>et[e](),!0)});et.prototype.featuresVolumeControl=et.canControlVolume();et.prototype.movingMediaElementInDOM=!Cs;et.prototype.featuresFullscreenResize=!0;et.prototype.featuresProgressEvents=!0;et.prototype.featuresTimeupdateEvents=!0;et.prototype.featuresVideoFrameCallback=!!(et.TEST_VID&&et.TEST_VID.requestVideoFrameCallback);et.disposeMediaElement=function(s){if(s){for(s.parentNode&&s.parentNode.removeChild(s);s.hasChildNodes();)s.removeChild(s.firstChild);s.removeAttribute("src"),typeof s.load=="function"&&(function(){try{s.load()}catch{}})()}};et.resetMediaElement=function(s){if(!s)return;const e=s.querySelectorAll("source");let t=e.length;for(;t--;)s.removeChild(e[t]);s.removeAttribute("src"),typeof s.load=="function"&&(function(){try{s.load()}catch{}})()};["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach(function(s){et.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){et.prototype["set"+ki(s)]=function(e){this.el_[s]=e,e?this.el_.setAttribute(s,s):this.el_.removeAttribute(s)}});["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach(function(s){et.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){et.prototype["set"+ki(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){et.prototype[s]=function(){return this.el_[s]()}});Et.withSourceHandlers(et);et.nativeSourceHandler={};et.nativeSourceHandler.canPlayType=function(s){try{return et.TEST_VID.canPlayType(s)}catch{return""}};et.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return et.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=IT(s.src);return et.nativeSourceHandler.canPlayType(`video/${t}`)}return""};et.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};et.nativeSourceHandler.dispose=function(){};et.registerSourceHandler(et.nativeSourceHandler);Et.registerTech("Html5",et);const cD=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],Ly={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},Lv=["tiny","xsmall","small","medium","large","xlarge","huge"],yp={};Lv.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;yp[s]=`vjs-layout-${e}`});const O3={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let vi=class Lu extends ke{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${Nn()}`,t=Object.assign(Lu.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const o=e.closest("[lang]");o&&(t.language=o.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=o=>this.documentFullscreenChange_(o),this.boundFullWindowOnEscKey_=o=>this.fullWindowOnEscKey(o),this.boundUpdateStyleEl_=o=>this.updateStyleEl_(o),this.boundApplyInitTime_=o=>this.applyInitTime_(o),this.boundUpdateCurrentBreakpoint_=o=>this.updateCurrentBreakpoint_(o),this.boundHandleTechClick_=o=>this.handleTechClick_(o),this.boundHandleTechDoubleClick_=o=>this.handleTechDoubleClick_(o),this.boundHandleTechTouchStart_=o=>this.handleTechTouchStart_(o),this.boundHandleTechTouchMove_=o=>this.handleTechTouchMove_(o),this.boundHandleTechTouchEnd_=o=>this.handleTechTouchEnd_(o),this.boundHandleTechTap_=o=>this.handleTechTap_(o),this.boundUpdatePlayerHeightOnAudioOnlyMode_=o=>this.updatePlayerHeightOnAudioOnlyMode_(o),this.isFullscreen_=!1,this.log=WA(this.id_),this.fsApi_=Rp,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={controlBarHeight:null,playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(this.tag=e,this.tagAttributes=e&&fo(e),this.language(this.options_.language),t.languages){const o={};Object.getOwnPropertyNames(t.languages).forEach(function(u){o[u.toLowerCase()]=t.languages[u]}),this.languages_=o}else this.languages_=Lu.prototype.options_.languages;this.resetCache_(),this.poster_=t.poster||"",this.controls_=!!t.controls,e.controls=!1,e.removeAttribute("controls"),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],e.hasAttribute("autoplay")?this.autoplay(!0):this.autoplay(this.options_.autoplay),t.plugins&&Object.keys(t.plugins).forEach(o=>{if(typeof this[o]!="function")throw new Error(`plugin "${o}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),AT(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(En(qe,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const n=si(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(o=>{this[o](t.plugins[o])}),t.debug&&this.debug(!0),this.options_.playerOptions=n,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const u=new se.DOMParser().parseFromString(i3,"image/svg+xml");if(u.querySelector("parsererror"))It.warn("Failed to load SVG Icons. Falling back to Font Icons."),this.options_.experimentalSvgIcons=null;else{const d=u.documentElement;d.style.display="none",this.el_.appendChild(d),this.addClass("vjs-svg-icons-enabled")}}this.initChildren(),this.isAudio(e.nodeName.toLowerCase()==="audio"),this.controls()?this.addClass("vjs-controls-enabled"):this.addClass("vjs-controls-disabled"),this.el_.setAttribute("role","region"),this.isAudio()?this.el_.setAttribute("aria-label",this.localize("Audio Player")):this.el_.setAttribute("aria-label",this.localize("Video Player")),this.isAudio()&&this.addClass("vjs-audio"),t.spatialNavigation&&t.spatialNavigation.enabled&&(this.spatialNavigation=new s3(this),this.addClass("vjs-spatial-navigation-enabled")),zd&&this.addClass("vjs-touch-enabled"),Cs||this.addClass("vjs-workinghover"),Lu.players[this.id_]=this;const r=vv.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",o=>this.listenForUserActivity_(o)),this.on("keydown",o=>this.handleKeyDown(o)),this.on("languagechange",o=>this.handleLanguagechange(o)),this.breakpoints(this.options_.breakpoints),this.responsive(this.options_.responsive),this.on("ready",()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)})}dispose(){this.trigger("dispose"),this.off("dispose"),Ds(qe,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),Ds(qe,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),Lu.players[this.id_]=null,this.tag&&this.tag.player&&(this.tag.player=null),this.el_&&this.el_.player&&(this.el_.player=null),this.tech_&&(this.tech_.dispose(),this.isPosterFromTech_=!1,this.poster_=""),this.playerElIngest_&&(this.playerElIngest_=null),this.tag&&(this.tag=null),ZN(this),Ns.names.forEach(e=>{const t=Ns[e],i=this[t.getterName]();i&&i.off&&i.off()}),super.dispose({restoreEl:this.options_.restoreEl})}createEl(){let e=this.tag,t,i=this.playerElIngest_=e.parentNode&&e.parentNode.hasAttribute&&e.parentNode.hasAttribute("data-vjs-player");const n=this.tag.tagName.toLowerCase()==="video-js";i?t=this.el_=e.parentNode:n||(t=this.el_=super.createEl("div"));const r=fo(e);if(n){for(t=this.el_=e,e=this.tag=qe.createElement("video");t.children.length;)e.appendChild(t.firstChild);Bd(t,"video-js")||vl(t,"video-js"),t.appendChild(e),i=this.playerElIngest_=t,Object.keys(t).forEach(c=>{try{e[c]=t[c]}catch{}})}e.setAttribute("tabindex","-1"),r.tabindex="-1",Nr&&Cm&&(e.setAttribute("role","application"),r.role="application"),e.removeAttribute("width"),e.removeAttribute("height"),"width"in r&&delete r.width,"height"in r&&delete r.height,Object.getOwnPropertyNames(r).forEach(function(c){n&&c==="class"||t.setAttribute(c,r[c]),n&&e.setAttribute(c,r[c])}),e.playerId=e.id,e.id+="_html5_api",e.className="vjs-tech",e.player=t.player=this,this.addClass("vjs-paused");const o=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(c=>sC[c]).map(c=>"vjs-device-"+c.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...o),se.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=vC("vjs-styles-dimensions");const c=So(".vjs-styles-defaults"),d=So("head");d.insertBefore(this.styleEl_,c?c.nextSibling:d.firstChild)}this.fill_=!1,this.fluid_=!1,this.width(this.options_.width),this.height(this.options_.height),this.fill(this.options_.fill),this.fluid(this.options_.fluid),this.aspectRatio(this.options_.aspectRatio),this.crossOrigin(this.options_.crossOrigin||this.options_.crossorigin);const u=e.getElementsByTagName("a");for(let c=0;c"u")return this.techGet_("crossOrigin");if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){It.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.techCall_("setCrossOrigin",e),this.posterImage&&this.posterImage.crossOrigin(e)}width(e){return this.dimension("width",e)}height(e){return this.dimension("height",e)}dimension(e,t){const i=e+"_";if(t===void 0)return this[i]||0;if(t===""||t==="auto"){this[i]=void 0,this.updateStyleEl_();return}const n=parseFloat(t);if(isNaN(n)){It.error(`Improper value "${t}" supplied for for ${e}`);return}this[i]=n,this.updateStyleEl_()}fluid(e){if(e===void 0)return!!this.fluid_;this.fluid_=!!e,va(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),IN(this,()=>{this.on(["playerreset","resize"],this.boundUpdateStyleEl_)})):this.removeClass("vjs-fluid"),this.updateStyleEl_()}fill(e){if(e===void 0)return!!this.fill_;this.fill_=!!e,e?(this.addClass("vjs-fill"),this.fluid(!1)):this.removeClass("vjs-fill")}aspectRatio(e){if(e===void 0)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(e))throw new Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");this.aspectRatio_=e,this.fluid(!0),this.updateStyleEl_()}updateStyleEl_(){if(se.VIDEOJS_NO_DYNAMIC_STYLE===!0){const u=typeof this.width_=="number"?this.width_:this.options_.width,c=typeof this.height_=="number"?this.height_:this.options_.height,d=this.tech_&&this.tech_.el();d&&(u>=0&&(d.width=u),c>=0&&(d.height=c));return}let e,t,i,n;this.aspectRatio_!==void 0&&this.aspectRatio_!=="auto"?i=this.aspectRatio_:this.videoWidth()>0?i=this.videoWidth()+":"+this.videoHeight():i="16:9";const r=i.split(":"),o=r[1]/r[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/o:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*o,/^[^a-zA-Z]/.test(this.id())?n="dimensions-"+this.id():n=this.id()+"-dimensions",this.addClass(n),TC(this.styleEl_,` - .${n} { - width: ${e}px; - height: ${t}px; - } - - .${n}.vjs-fluid:not(.vjs-audio-only-mode) { - padding-top: ${o*100}%; - } - `)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=ki(e),n=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(Et.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=i,this.isReady_=!1;let r=this.autoplay();(typeof this.autoplay()=="string"||this.autoplay()===!0&&this.options_.normalizeAutoplay)&&(r=!1);const o={source:t,autoplay:r,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:`${this.id()}_${n}_api`,playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,disablePictureInPicture:this.options_.disablePictureInPicture,muted:this.options_.muted,poster:this.poster(),language:this.language(),playerElIngest:this.playerElIngest_||!1,"vtt.js":this.options_["vtt.js"],canOverridePoster:!!this.options_.techCanOverridePoster,enableSourceset:this.options_.enableSourceset};Ns.names.forEach(c=>{const d=Ns[c];o[d.getterName]=this[d.privateName]}),Object.assign(o,this.options_[i]),Object.assign(o,this.options_[n]),Object.assign(o,this.options_[e.toLowerCase()]),this.tag&&(o.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(o.startTime=this.cache_.currentTime);const u=Et.getTech(e);if(!u)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new u(o),this.tech_.ready(di(this,this.handleTechReady_),!0),Cv.jsonToTextTracks(this.textTracksJson_||[],this.tech_),cD.forEach(c=>{this.on(this.tech_,c,d=>this[`handleTech${ki(c)}_`](d))}),Object.keys(Ly).forEach(c=>{this.on(this.tech_,c,d=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${Ly[c]}_`].bind(this),event:d});return}this[`handleTech${Ly[c]}_`](d)})}),this.on(this.tech_,"loadstart",c=>this.handleTechLoadStart_(c)),this.on(this.tech_,"sourceset",c=>this.handleTechSourceset_(c)),this.on(this.tech_,"waiting",c=>this.handleTechWaiting_(c)),this.on(this.tech_,"ended",c=>this.handleTechEnded_(c)),this.on(this.tech_,"seeking",c=>this.handleTechSeeking_(c)),this.on(this.tech_,"play",c=>this.handleTechPlay_(c)),this.on(this.tech_,"pause",c=>this.handleTechPause_(c)),this.on(this.tech_,"durationchange",c=>this.handleTechDurationChange_(c)),this.on(this.tech_,"fullscreenchange",(c,d)=>this.handleTechFullscreenChange_(c,d)),this.on(this.tech_,"fullscreenerror",(c,d)=>this.handleTechFullscreenError_(c,d)),this.on(this.tech_,"enterpictureinpicture",c=>this.handleTechEnterPictureInPicture_(c)),this.on(this.tech_,"leavepictureinpicture",c=>this.handleTechLeavePictureInPicture_(c)),this.on(this.tech_,"error",c=>this.handleTechError_(c)),this.on(this.tech_,"posterchange",c=>this.handleTechPosterChange_(c)),this.on(this.tech_,"textdata",c=>this.handleTechTextData_(c)),this.on(this.tech_,"ratechange",c=>this.handleTechRateChange_(c)),this.on(this.tech_,"loadedmetadata",this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_("controls")),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode!==this.el()&&(i!=="Html5"||!this.tag)&&bv(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){Ns.names.forEach(e=>{const t=Ns[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=Cv.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1}tech(e){return e===void 0&&It.warn(`Using the tech directly can be dangerous. I hope you know what you're doing. -See https://github.com/videojs/video.js/issues/2617 for more info. -`),this.tech_}version(){return{"video.js":vv}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,"click",this.boundHandleTechClick_),this.on(this.tech_,"dblclick",this.boundHandleTechDoubleClick_),this.on(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.on(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.on(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.on(this.tech_,"tap",this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,"tap",this.boundHandleTechTap_),this.off(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.off(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.off(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.off(this.tech_,"click",this.boundHandleTechClick_),this.off(this.tech_,"dblclick",this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass("vjs-ended","vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()?(this.hasStarted(!1),this.trigger("loadstart")):this.trigger("loadstart"),this.manualAutoplay_(this.autoplay()===!0&&this.options_.normalizeAutoplay?"play":this.autoplay())}manualAutoplay_(e){if(!this.tech_||typeof e!="string")return;const t=()=>{const n=this.muted();this.muted(!0);const r=()=>{this.muted(n)};this.playTerminatedQueue_.push(r);const o=this.play();if(Ud(o))return o.catch(u=>{throw r(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${u||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),Ud(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!Ud(i))return i.then(()=>{this.trigger({type:"autoplay-success",autoplay:e})}).catch(()=>{this.trigger({type:"autoplay-failure",autoplay:e})})}updateSourceCaches_(e=""){let t=e,i="";typeof t!="string"&&(t=e.src,i=e.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],t&&!i&&(i=t3(this,t)),this.cache_.source=si({},e,{src:t,type:i});const n=this.cache_.sources.filter(c=>c.src&&c.src===t),r=[],o=this.$$("source"),u=[];for(let c=0;cthis.updateSourceCaches_(r);const i=this.currentSource().src,n=e.src;i&&!/^blob:/.test(i)&&/^blob:/.test(n)&&(!this.lastSource_||this.lastSource_.tech!==n&&this.lastSource_.player!==i)&&(t=()=>{}),t(n),e.src||this.tech_.any(["sourceset","loadstart"],r=>{if(r.type==="sourceset")return;const o=this.techGet_("currentSrc");this.lastSource_.tech=o,this.updateSourceCaches_(o)})}this.lastSource_={player:this.currentSource().src,tech:e.src},this.trigger({src:e.src,type:"sourceset"})}hasStarted(e){if(e===void 0)return this.hasStarted_;e!==this.hasStarted_&&(this.hasStarted_=e,this.hasStarted_?this.addClass("vjs-has-started"):this.removeClass("vjs-has-started"))}handleTechPlay_(){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")}handleTechRateChange_(){this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0&&(this.queuedCallbacks_.forEach(e=>e.callback(e.event)),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")}handleTechWaiting_(){this.addClass("vjs-waiting"),this.trigger("waiting");const e=this.currentTime(),t=()=>{e!==this.currentTime()&&(this.removeClass("vjs-waiting"),this.off("timeupdate",t))};this.on("timeupdate",t)}handleTechCanPlay_(){this.removeClass("vjs-waiting"),this.trigger("canplay")}handleTechCanPlayThrough_(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")}handleTechPlaying_(){this.removeClass("vjs-waiting"),this.trigger("playing")}handleTechSeeking_(){this.addClass("vjs-seeking"),this.trigger("seeking")}handleTechSeeked_(){this.removeClass("vjs-seeking","vjs-ended"),this.trigger("seeked")}handleTechPause_(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")}handleTechEnded_(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")}handleTechDurationChange_(){this.duration(this.techGet_("duration"))}handleTechClick_(e){this.controls_&&(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.click===void 0||this.options_.userActions.click!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.click=="function"?this.options_.userActions.click.call(this,e):this.paused()?wr(this.play()):this.pause())}handleTechDoubleClick_(e){if(!this.controls_)return;Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"),i=>i.contains(e.target))||(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.doubleClick===void 0||this.options_.userActions.doubleClick!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.doubleClick=="function"?this.options_.userActions.doubleClick.call(this,e):this.isInPictureInPicture()&&!qe.pictureInPictureElement?this.exitPictureInPicture():this.isFullscreen()?this.exitFullscreen():this.requestFullscreen())}handleTechTap_(){this.userActive(!this.userActive())}handleTechTouchStart_(){this.userWasActive=this.userActive()}handleTechTouchMove_(){this.userWasActive&&this.reportUserActivity()}handleTechTouchEnd_(e){e.cancelable&&e.preventDefault()}toggleFullscreenClass_(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")}documentFullscreenChange_(e){const t=e.target.player;if(t&&t!==this)return;const i=this.el();let n=qe[this.fsApi_.fullscreenElement]===i;!n&&i.matches&&(n=i.matches(":"+this.fsApi_.fullscreen)),this.isFullscreen(n)}handleTechFullscreenChange_(e,t){t&&(t.nativeIOSFullscreen&&(this.addClass("vjs-ios-native-fs"),this.tech_.one("webkitendfullscreen",()=>{this.removeClass("vjs-ios-native-fs")})),this.isFullscreen(t.isFullscreen))}handleTechFullscreenError_(e,t){this.trigger("fullscreenerror",t)}togglePictureInPictureClass_(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")}handleTechEnterPictureInPicture_(e){this.isInPictureInPicture(!0)}handleTechLeavePictureInPicture_(e){this.isInPictureInPicture(!1)}handleTechError_(){const e=this.tech_.error();e&&this.error(e)}handleTechTextData_(){let e=null;arguments.length>1&&(e=arguments[1]),this.trigger("textdata",e)}getCache(){return this.cache_}resetCache_(){this.cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:"",source:{},sources:[],playbackRates:[],volume:1}}techCall_(e,t){this.ready(function(){if(e in XN)return YN(this.middleware_,this.tech_,e,t);if(e in BE)return NE(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw It(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in WN)return KN(this.middleware_,this.tech_,e);if(e in BE)return NE(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(It(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(It(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(It(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=wr){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(wm||Cs);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=o=>{this.play_()},this.one(["ready","loadstart"],this.waitToPlay_),!t&&i&&this.load();return}const n=this.techGet_("play");i&&this.hasClass("vjs-ended")&&this.resetProgressBar_(),n===null?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(n)}runPlayTerminatedQueue_(){const e=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],e.forEach(function(t){t()})}runPlayCallbacks_(e){const t=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],t.forEach(function(i){i(e)})}pause(){this.techCall_("pause")}paused(){return this.techGet_("paused")!==!1}played(){return this.techGet_("played")||tr(0,0)}scrubbing(e){if(typeof e>"u")return this.scrubbing_;this.scrubbing_=!!e,this.techCall_("setScrubbing",this.scrubbing_),e?this.addClass("vjs-scrubbing"):this.removeClass("vjs-scrubbing")}currentTime(e){if(e===void 0)return this.cache_.currentTime=this.techGet_("currentTime")||0,this.cache_.currentTime;if(e<0&&(e=0),!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=e,this.off("canplay",this.boundApplyInitTime_),this.one("canplay",this.boundApplyInitTime_);return}this.techCall_("setCurrentTime",e),this.cache_.initTime=0,isFinite(e)&&(this.cache_.currentTime=Number(e))}applyInitTime_(){this.currentTime(this.cache_.initTime)}duration(e){if(e===void 0)return this.cache_.duration!==void 0?this.cache_.duration:NaN;e=parseFloat(e),e<0&&(e=1/0),e!==this.cache_.duration&&(this.cache_.duration=e,e===1/0?this.addClass("vjs-live"):this.removeClass("vjs-live"),isNaN(e)||this.trigger("durationchange"))}remainingTime(){return this.duration()-this.currentTime()}remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())}buffered(){let e=this.techGet_("buffered");return(!e||!e.length)&&(e=tr(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=tr(0,0)),e}seeking(){return this.techGet_("seeking")}ended(){return this.techGet_("ended")}networkState(){return this.techGet_("networkState")}readyState(){return this.techGet_("readyState")}bufferedPercent(){return wC(this.buffered(),this.duration())}bufferedEnd(){const e=this.buffered(),t=this.duration();let i=e.end(e.length-1);return i>t&&(i=t),i}volume(e){let t;if(e!==void 0){t=Math.max(0,Math.min(1,e)),this.cache_.volume=t,this.techCall_("setVolume",t),t>0&&this.lastVolume_(t);return}return t=parseFloat(this.techGet_("volume")),isNaN(t)?1:t}muted(e){if(e!==void 0){this.techCall_("setMuted",e);return}return this.techGet_("muted")||!1}defaultMuted(e){return e!==void 0&&this.techCall_("setDefaultMuted",e),this.techGet_("defaultMuted")||!1}lastVolume_(e){if(e!==void 0&&e!==0){this.cache_.lastVolume=e;return}return this.cache_.lastVolume}supportsFullScreen(){return this.techGet_("supportsFullScreen")||!1}isFullscreen(e){if(e!==void 0){const t=this.isFullscreen_;this.isFullscreen_=!!e,this.isFullscreen_!==t&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),this.toggleFullscreenClass_();return}return this.isFullscreen_}requestFullscreen(e){this.isInPictureInPicture()&&this.exitPictureInPicture();const t=this;return new Promise((i,n)=>{function r(){t.off("fullscreenerror",u),t.off("fullscreenchange",o)}function o(){r(),i()}function u(d,f){r(),n(f)}t.one("fullscreenchange",o),t.one("fullscreenerror",u);const c=t.requestFullscreenHelper_(e);c&&(c.then(r,r),c.then(i,n))})}requestFullscreenHelper_(e){let t;if(this.fsApi_.prefixed||(t=this.options_.fullscreen&&this.options_.fullscreen.options||{},e!==void 0&&(t=e)),this.fsApi_.requestFullscreen){const i=this.el_[this.fsApi_.requestFullscreen](t);return i&&i.then(()=>this.isFullscreen(!0),()=>this.isFullscreen(!1)),i}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()}exitFullscreen(){const e=this;return new Promise((t,i)=>{function n(){e.off("fullscreenerror",o),e.off("fullscreenchange",r)}function r(){n(),t()}function o(c,d){n(),i(d)}e.one("fullscreenchange",r),e.one("fullscreenerror",o);const u=e.exitFullscreenHelper_();u&&(u.then(n,n),u.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=qe[this.fsApi_.exitFullscreen]();return e&&wr(e.then(()=>this.isFullscreen(!1))),e}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()}enterFullWindow(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=qe.documentElement.style.overflow,En(qe,"keydown",this.boundFullWindowOnEscKey_),qe.documentElement.style.overflow="hidden",vl(qe.body,"vjs-full-window"),this.trigger("enterFullWindow")}fullWindowOnEscKey(e){e.key==="Escape"&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,Ds(qe,"keydown",this.boundFullWindowOnEscKey_),qe.documentElement.style.overflow=this.docOrigOverflow,Lm(qe.body,"vjs-full-window"),this.trigger("exitFullWindow")}disablePictureInPicture(e){if(e===void 0)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",e),this.options_.disablePictureInPicture=e,this.trigger("disablepictureinpicturechanged")}isInPictureInPicture(e){if(e!==void 0){this.isInPictureInPicture_=!!e,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_}requestPictureInPicture(){if(this.options_.enableDocumentPictureInPicture&&se.documentPictureInPicture){const e=qe.createElement(this.el().tagName);return e.classList=this.el().classList,e.classList.add("vjs-pip-container"),this.posterImage&&e.appendChild(this.posterImage.el().cloneNode(!0)),this.titleBar&&e.appendChild(this.titleBar.el().cloneNode(!0)),e.appendChild(gt("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),se.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(mC(t),this.el_.parentNode.insertBefore(e,this.el_),t.document.body.appendChild(this.el_),t.document.body.classList.add("vjs-pip-window"),this.player_.isInPictureInPicture(!0),this.player_.trigger({type:"enterpictureinpicture",pipWindow:t}),t.addEventListener("pagehide",i=>{const n=i.target.querySelector(".video-js");e.parentNode.replaceChild(n,e),this.player_.isInPictureInPicture(!1),this.player_.trigger("leavepictureinpicture")}),t))}return"pictureInPictureEnabled"in qe&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(se.documentPictureInPicture&&se.documentPictureInPicture.window)return se.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in qe)return qe.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(n=>{const r=n.tagName.toLowerCase();if(n.isContentEditable)return!0;const o=["button","checkbox","hidden","radio","reset","submit"];return r==="input"?o.indexOf(n.type)===-1:["textarea"].indexOf(r)!==-1})(this.el_.ownerDocument.activeElement)||(typeof t.hotkeys=="function"?t.hotkeys.call(this,e):this.handleHotkeys(e))}handleHotkeys(e){const t=this.options_.userActions?this.options_.userActions.hotkeys:{},{fullscreenKey:i=o=>e.key.toLowerCase()==="f",muteKey:n=o=>e.key.toLowerCase()==="m",playPauseKey:r=o=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const o=ke.getComponent("FullscreenToggle");qe[this.fsApi_.fullscreenEnabled]!==!1&&o.prototype.handleClick.call(this,e)}else n.call(this,e)?(e.preventDefault(),e.stopPropagation(),ke.getComponent("MuteToggle").prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),ke.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,n=this.options_.techOrder;i[u,Et.getTech(u)]).filter(([u,c])=>c?c.isSupported():(It.error(`The "${u}" tech is undefined. Skipped browser support check for that tech.`),!1)),i=function(u,c,d){let f;return u.some(m=>c.some(g=>{if(f=d(m,g),f)return!0})),f};let n;const r=u=>(c,d)=>u(d,c),o=([u,c],d)=>{if(c.canPlaySource(d,this.options_[u.toLowerCase()]))return{source:d,tech:u}};return this.options_.sourceOrder?n=i(e,t,r(o)):n=i(t,e,o),n||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=PC(e);if(!i.length){this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0);return}if(this.changingSrc_=!0,t||(this.cache_.sources=i),this.updateSourceCaches_(i[0]),qN(this,i[0],(n,r)=>{if(this.middleware_=r,t||(this.cache_.sources=i),this.updateSourceCaches_(n),this.src_(n)){if(i.length>1)return this.handleSrc_(i.slice(1));this.changingSrc_=!1,this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0),this.triggerReady();return}zN(r,this.tech_)}),i.length>1){const n=()=>{this.error(null),this.handleSrc_(i.slice(1),!0)},r=()=>{this.off("error",n)};this.one("error",n),this.one("playing",r),this.resetRetryOnError_=()=>{this.off("error",n),this.off("playing",r)}}}src(e){return this.handleSrc_(e,!1)}src_(e){const t=this.selectSource([e]);return t?EC(t.tech,this.techName_)?(this.ready(function(){this.tech_.constructor.prototype.hasOwnProperty("setSource")?this.techCall_("setSource",e):this.techCall_("src",e.src),this.changingSrc_=!1},!0),!1):(this.changingSrc_=!0,this.loadTech_(t.tech,t.source),this.tech_.ready(()=>{this.changingSrc_=!1}),!1):!0}addSourceElement(e,t){return this.tech_?this.tech_.addSourceElement(e,t):!1}removeSourceElement(e){return this.tech_?this.tech_.removeSourceElement(e):!1}load(){if(this.tech_&&this.tech_.vhs){this.src(this.currentSource());return}this.techCall_("load")}reset(){if(this.paused())this.doReset_();else{const e=this.play();wr(e.then(()=>this.doReset_()))}}doReset_(){this.tech_&&this.tech_.clearTracks("text"),this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),this.error(null),this.titleBar&&this.titleBar.update({title:void 0,description:void 0}),va(this)&&this.trigger("playerreset")}resetControlBarUI_(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()}resetProgressBar_(){this.currentTime(0);const{currentTimeDisplay:e,durationDisplay:t,progressControl:i,remainingTimeDisplay:n}=this.controlBar||{},{seekBar:r}=i||{};e&&e.updateContent(),t&&t.updateContent(),n&&n.updateContent(),r&&(r.update(),r.loadProgressBar&&r.loadProgressBar.update())}resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()}resetVolumeBar_(){this.volume(1),this.trigger("volumechange")}currentSources(){const e=this.currentSource(),t=[];return Object.keys(e).length!==0&&t.push(e),this.cache_.sources||t}currentSource(){return this.cache_.source||{}}currentSrc(){return this.currentSource()&&this.currentSource().src||""}currentType(){return this.currentSource()&&this.currentSource().type||""}preload(e){if(e!==void 0){this.techCall_("setPreload",e),this.options_.preload=e;return}return this.techGet_("preload")}autoplay(e){if(e===void 0)return this.options_.autoplay||!1;let t;typeof e=="string"&&/(any|play|muted)/.test(e)||e===!0&&this.options_.normalizeAutoplay?(this.options_.autoplay=e,this.manualAutoplay_(typeof e=="string"?e:"play"),t=!1):e?this.options_.autoplay=!0:this.options_.autoplay=!1,t=typeof t>"u"?this.options_.autoplay:t,this.tech_&&this.techCall_("setAutoplay",t)}playsinline(e){return e!==void 0&&(this.techCall_("setPlaysinline",e),this.options_.playsinline=e),this.techGet_("playsinline")}loop(e){if(e!==void 0){this.techCall_("setLoop",e),this.options_.loop=e;return}return this.techGet_("loop")}poster(e){if(e===void 0)return this.poster_;e||(e=""),e!==this.poster_&&(this.poster_=e,this.techCall_("setPoster",e),this.isPosterFromTech_=!1,this.trigger("posterchange"))}handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){const e=this.tech_.poster()||"";e!==this.poster_&&(this.poster_=e,this.isPosterFromTech_=!0,this.trigger("posterchange"))}}controls(e){if(e===void 0)return!!this.controls_;e=!!e,this.controls_!==e&&(this.controls_=e,this.usingNativeControls()&&this.techCall_("setControls",e),this.controls_?(this.removeClass("vjs-controls-disabled"),this.addClass("vjs-controls-enabled"),this.trigger("controlsenabled"),this.usingNativeControls()||this.addTechControlsListeners_()):(this.removeClass("vjs-controls-enabled"),this.addClass("vjs-controls-disabled"),this.trigger("controlsdisabled"),this.usingNativeControls()||this.removeTechControlsListeners_()))}usingNativeControls(e){if(e===void 0)return!!this.usingNativeControls_;e=!!e,this.usingNativeControls_!==e&&(this.usingNativeControls_=e,this.usingNativeControls_?(this.addClass("vjs-using-native-controls"),this.trigger("usingnativecontrols")):(this.removeClass("vjs-using-native-controls"),this.trigger("usingcustomcontrols")))}error(e){if(e===void 0)return this.error_||null;if(xo("beforeerror").forEach(t=>{const i=t(this,e);if(!(Mr(i)&&!Array.isArray(i)||typeof i=="string"||typeof i=="number"||i===null)){this.log.error("please return a value that MediaError expects in beforeerror hooks");return}e=i}),this.options_.suppressNotSupportedError&&e&&e.code===4){const t=function(){this.error(e)};this.options_.suppressNotSupportedError=!1,this.any(["click","touchstart"],t),this.one("loadstart",function(){this.off(["click","touchstart"],t)});return}if(e===null){this.error_=null,this.removeClass("vjs-error"),this.errorDisplay&&this.errorDisplay.close();return}this.error_=new Ei(e),this.addClass("vjs-error"),It.error(`(CODE:${this.error_.code} ${Ei.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),xo("error").forEach(t=>t(this,this.error_))}reportUserActivity(e){this.userActivity_=!0}userActive(e){if(e===void 0)return this.userActive_;if(e=!!e,e!==this.userActive_){if(this.userActive_=e,this.userActive_){this.userActivity_=!0,this.removeClass("vjs-user-inactive"),this.addClass("vjs-user-active"),this.trigger("useractive");return}this.tech_&&this.tech_.one("mousemove",function(t){t.stopPropagation(),t.preventDefault()}),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}}listenForUserActivity_(){let e,t,i;const n=di(this,this.reportUserActivity),r=function(m){(m.screenX!==t||m.screenY!==i)&&(t=m.screenX,i=m.screenY,n())},o=function(){n(),this.clearInterval(e),e=this.setInterval(n,250)},u=function(m){n(),this.clearInterval(e)};this.on("mousedown",o),this.on("mousemove",r),this.on("mouseup",u),this.on("mouseleave",u);const c=this.getChild("controlBar");c&&!Cs&&!ir&&(c.on("mouseenter",function(m){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),c.on("mouseleave",function(m){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on("keydown",n),this.on("keyup",n);let d;const f=function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(d);const m=this.options_.inactivityTimeout;m<=0||(d=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},m))};this.setInterval(f,250)}playbackRate(e){if(e!==void 0){this.techCall_("setPlaybackRate",e);return}return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_("playbackRate"):1}defaultPlaybackRate(e){return e!==void 0?this.techCall_("setDefaultPlaybackRate",e):this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_("defaultPlaybackRate"):1}isAudio(e){if(e!==void 0){this.isAudio_=!!e;return}return!!this.isAudio_}updatePlayerHeightOnAudioOnlyMode_(){const e=this.getChild("ControlBar");!e||this.audioOnlyCache_.controlBarHeight===e.currentHeight()||(this.audioOnlyCache_.controlBarHeight=e.currentHeight(),this.height(this.audioOnlyCache_.controlBarHeight))}enableAudioOnlyUI_(){this.addClass("vjs-audio-only-mode");const e=this.children(),t=this.getChild("ControlBar"),i=t&&t.currentHeight();e.forEach(n=>{n!==t&&n.el_&&!n.hasClass("vjs-hidden")&&(n.hide(),this.audioOnlyCache_.hiddenChildren.push(n))}),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.audioOnlyCache_.controlBarHeight=i,this.on("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.height(i),this.trigger("audioonlymodechange")}disableAudioOnlyUI_(){this.removeClass("vjs-audio-only-mode"),this.off("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.audioOnlyCache_.hiddenChildren.forEach(e=>e.show()),this.height(this.audioOnlyCache_.playerHeight),this.trigger("audioonlymodechange")}audioOnlyMode(e){if(typeof e!="boolean"||e===this.audioOnlyMode_)return this.audioOnlyMode_;if(this.audioOnlyMode_=e,e){const t=[];return this.isInPictureInPicture()&&t.push(this.exitPictureInPicture()),this.isFullscreen()&&t.push(this.exitFullscreen()),this.audioPosterMode()&&t.push(this.audioPosterMode(!1)),Promise.all(t).then(()=>this.enableAudioOnlyUI_())}return Promise.resolve().then(()=>this.disableAudioOnlyUI_())}enablePosterModeUI_(){(this.tech_&&this.tech_).hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}disablePosterModeUI_(){(this.tech_&&this.tech_).show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}audioPosterMode(e){return typeof e!="boolean"||e===this.audioPosterMode_?this.audioPosterMode_:(this.audioPosterMode_=e,e?this.audioOnlyMode()?this.audioOnlyMode(!1).then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.disablePosterModeUI_()}))}addTextTrack(e,t,i){if(this.tech_)return this.tech_.addTextTrack(e,t,i)}addRemoteTextTrack(e,t){if(this.tech_)return this.tech_.addRemoteTextTrack(e,t)}removeRemoteTextTrack(e={}){let{track:t}=e;if(t||(t=e),this.tech_)return this.tech_.removeRemoteTextTrack(t)}getVideoPlaybackQuality(){return this.techGet_("getVideoPlaybackQuality")}videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0}videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0}language(e){if(e===void 0)return this.language_;this.language_!==String(e).toLowerCase()&&(this.language_=String(e).toLowerCase(),va(this)&&this.trigger("languagechange"))}languages(){return si(Lu.prototype.options_.languages,this.languages_)}toJSON(){const e=si(this.options_),t=e.tracks;e.tracks=[];for(let i=0;i{this.removeChild(i)}),i.open(),i}updateCurrentBreakpoint_(){if(!this.responsive())return;const e=this.currentBreakpoint(),t=this.currentWidth();for(let i=0;ithis.addRemoteTextTrack(m,!1)),this.titleBar&&this.titleBar.update({title:f,description:o||n||""}),this.ready(t)}getMedia(){if(!this.cache_.media){const e=this.poster(),t=this.currentSources(),i=Array.prototype.map.call(this.remoteTextTracks(),r=>({kind:r.kind,label:r.label,language:r.language,src:r.src})),n={src:t,textTracks:i};return e&&(n.poster=e,n.artwork=[{src:n.poster,type:Hp(n.poster)}]),n}return si(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=fo(e),n=i["data-setup"];if(Bd(e,"vjs-fill")&&(i.fill=!0),Bd(e,"vjs-fluid")&&(i.fluid=!0),n!==null)try{Object.assign(i,JSON.parse(n||"{}"))}catch(r){It.error("data-setup",r)}if(Object.assign(t,i),e.hasChildNodes()){const r=e.childNodes;for(let o=0,u=r.length;otypeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}};vi.prototype.videoTracks=()=>{};vi.prototype.audioTracks=()=>{};vi.prototype.textTracks=()=>{};vi.prototype.remoteTextTracks=()=>{};vi.prototype.remoteTextTrackEls=()=>{};Ns.names.forEach(function(s){const e=Ns[s];vi.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});vi.prototype.crossorigin=vi.prototype.crossOrigin;vi.players={};const xd=se.navigator;vi.prototype.options_={techOrder:Et.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:xd&&(xd.languages&&xd.languages[0]||xd.userLanguage||xd.language)||"en",languages:{},notSupportedMessage:"No compatible source was found for this media.",normalizeAutoplay:!1,fullscreen:{options:{navigationUI:"hide"}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,spatialNavigation:{enabled:!1,horizontalSeek:!1},enableSmoothSeeking:!1,disableSeekWhileScrubbingOnMobile:!1,disableSeekWhileScrubbingOnSTV:!1};cD.forEach(function(s){vi.prototype[`handleTech${ki(s)}_`]=function(){return this.trigger(s)}});ke.registerComponent("Player",vi);const Gp="plugin",$u="activePlugins_",Ru={},Vp=s=>Ru.hasOwnProperty(s),vp=s=>Vp(s)?Ru[s]:void 0,dD=(s,e)=>{s[$u]=s[$u]||{},s[$u][e]=!0},qp=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},P3=function(s,e){const t=function(){qp(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return dD(this,s),qp(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},JE=(s,e)=>(e.prototype.name=s,function(...t){qp(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,qp(this,i.getEventHash()),i});class rn{constructor(e){if(this.constructor===rn)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),AT(this),delete this.trigger,SC(this,this.constructor.defaultState),dD(e,this.name),this.dispose=this.dispose.bind(this),e.on("dispose",this.dispose)}version(){return this.constructor.VERSION}getEventHash(e={}){return e.name=this.name,e.plugin=this.constructor,e.instance=this,e}trigger(e,t={}){return cc(this.eventBusEl_,e,this.getEventHash(t))}handleStateChanged(e){}dispose(){const{name:e,player:t}=this;this.trigger("dispose"),this.off(),t.off("dispose",this.dispose),t[$u][e]=!1,this.player=this.state=null,t[e]=JE(e,Ru[e])}static isBasic(e){const t=typeof e=="string"?vp(e):e;return typeof t=="function"&&!rn.prototype.isPrototypeOf(t.prototype)}static registerPlugin(e,t){if(typeof e!="string")throw new Error(`Illegal plugin name, "${e}", must be a string, was ${typeof e}.`);if(Vp(e))It.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(vi.prototype.hasOwnProperty(e))throw new Error(`Illegal plugin name, "${e}", cannot share a name with an existing player method!`);if(typeof t!="function")throw new Error(`Illegal plugin for "${e}", must be a function, was ${typeof t}.`);return Ru[e]=t,e!==Gp&&(rn.isBasic(t)?vi.prototype[e]=P3(e,t):vi.prototype[e]=JE(e,t)),t}static deregisterPlugin(e){if(e===Gp)throw new Error("Cannot de-register base plugin.");Vp(e)&&(delete Ru[e],delete vi.prototype[e])}static getPlugins(e=Object.keys(Ru)){let t;return e.forEach(i=>{const n=vp(i);n&&(t=t||{},t[i]=n)}),t}static getPluginVersion(e){const t=vp(e);return t&&t.VERSION||""}}rn.getPlugin=vp;rn.BASE_PLUGIN_NAME=Gp;rn.registerPlugin(Gp,rn);vi.prototype.usingPlugin=function(s){return!!this[$u]&&this[$u][s]===!0};vi.prototype.hasPlugin=function(s){return!!Vp(s)};function M3(s,e){let t=!1;return function(...i){return t||It.warn(s),t=!0,e.apply(this,i)}}function sr(s,e,t,i){return M3(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var N3={NetworkBadStatus:"networkbadstatus",NetworkRequestFailed:"networkrequestfailed",NetworkRequestAborted:"networkrequestaborted",NetworkRequestTimeout:"networkrequesttimeout",NetworkBodyParserFailed:"networkbodyparserfailed",StreamingHlsPlaylistParserError:"streaminghlsplaylistparsererror",StreamingDashManifestParserError:"streamingdashmanifestparsererror",StreamingContentSteeringParserError:"streamingcontentsteeringparsererror",StreamingVttParserError:"streamingvttparsererror",StreamingFailedToSelectNextSegment:"streamingfailedtoselectnextsegment",StreamingFailedToDecryptSegment:"streamingfailedtodecryptsegment",StreamingFailedToTransmuxSegment:"streamingfailedtotransmuxsegment",StreamingFailedToAppendSegment:"streamingfailedtoappendsegment",StreamingCodecsChangeError:"streamingcodecschangeerror"};const hD=s=>s.indexOf("#")===0?s.slice(1):s;function Te(s,e,t){let i=Te.getPlayer(s);if(i)return e&&It.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const n=typeof s=="string"?So("#"+hD(s)):s;if(!uc(n))throw new TypeError("The element or ID supplied is not valid. (videojs)");const o=("getRootNode"in n?n.getRootNode()instanceof se.ShadowRoot:!1)?n.getRootNode():n.ownerDocument.body;(!n.ownerDocument.defaultView||!o.contains(n))&&It.warn("The element supplied is not included in the DOM"),e=e||{},e.restoreEl===!0&&(e.restoreEl=(n.parentNode&&n.parentNode.hasAttribute&&n.parentNode.hasAttribute("data-vjs-player")?n.parentNode:n).cloneNode(!0)),xo("beforesetup").forEach(c=>{const d=c(n,si(e));if(!Mr(d)||Array.isArray(d)){It.error("please return an object in beforesetup hooks");return}e=si(e,d)});const u=ke.getComponent("Player");return i=new u(n,e,t),xo("setup").forEach(c=>c(i)),i}Te.hooks_=ma;Te.hooks=xo;Te.hook=gN;Te.hookOnce=yN;Te.removeHook=YA;if(se.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&lc()){let s=So(".vjs-styles-defaults");if(!s){s=vC("vjs-styles-defaults");const e=So("head");e&&e.insertBefore(s,e.firstChild),TC(s,` - .video-js { - width: 300px; - height: 150px; - } - - .vjs-fluid:not(.vjs-audio-only-mode) { - padding-top: 56.25% - } - `)}}xv(1,Te);Te.VERSION=vv;Te.options=vi.prototype.options_;Te.getPlayers=()=>vi.players;Te.getPlayer=s=>{const e=vi.players;let t;if(typeof s=="string"){const i=hD(s),n=e[i];if(n)return n;t=So("#"+i)}else t=s;if(uc(t)){const{player:i,playerId:n}=t;if(i||e[n])return i||e[n]}};Te.getAllPlayers=()=>Object.keys(vi.players).map(s=>vi.players[s]).filter(Boolean);Te.players=vi.players;Te.getComponent=ke.getComponent;Te.registerComponent=(s,e)=>(Et.isTech(e)&&It.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),ke.registerComponent.call(ke,s,e));Te.getTech=Et.getTech;Te.registerTech=Et.registerTech;Te.use=VN;Object.defineProperty(Te,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(Te.middleware,"TERMINATOR",{value:jp,writeable:!1,enumerable:!0});Te.browser=sC;Te.obj=bN;Te.mergeOptions=sr(9,"videojs.mergeOptions","videojs.obj.merge",si);Te.defineLazyProperty=sr(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",Em);Te.bind=sr(9,"videojs.bind","native Function.prototype.bind",di);Te.registerPlugin=rn.registerPlugin;Te.deregisterPlugin=rn.deregisterPlugin;Te.plugin=(s,e)=>(It.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),rn.registerPlugin(s,e));Te.getPlugins=rn.getPlugins;Te.getPlugin=rn.getPlugin;Te.getPluginVersion=rn.getPluginVersion;Te.addLanguage=function(s,e){return s=(""+s).toLowerCase(),Te.options.languages=si(Te.options.languages,{[s]:e}),Te.options.languages[s]};Te.log=It;Te.createLogger=WA;Te.time=MN;Te.createTimeRange=sr(9,"videojs.createTimeRange","videojs.time.createTimeRanges",tr);Te.createTimeRanges=sr(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",tr);Te.formatTime=sr(9,"videojs.formatTime","videojs.time.formatTime",El);Te.setFormatTime=sr(9,"videojs.setFormatTime","videojs.time.setFormatTime",CC);Te.resetFormatTime=sr(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",DC);Te.parseUrl=sr(9,"videojs.parseUrl","videojs.url.parseUrl",LT);Te.isCrossOrigin=sr(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",Nm);Te.EventTarget=An;Te.any=ET;Te.on=En;Te.one=Pm;Te.off=Ds;Te.trigger=cc;Te.xhr=OA;Te.TrackList=Al;Te.TextTrack=lh;Te.TextTrackList=DT;Te.AudioTrack=RC;Te.AudioTrackList=LC;Te.VideoTrack=OC;Te.VideoTrackList=IC;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{Te[s]=function(){return It.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),gC[s].apply(null,arguments)}});Te.computedStyle=sr(9,"videojs.computedStyle","videojs.dom.computedStyle",sc);Te.dom=gC;Te.fn=LN;Te.num=d3;Te.str=ON;Te.url=HN;Te.Error=N3;class B3{constructor(e){let t=this;return t.id=e.id,t.label=t.id,t.width=e.width,t.height=e.height,t.bitrate=e.bandwidth,t.frameRate=e.frameRate,t.enabled_=e.enabled,Object.defineProperty(t,"enabled",{get(){return t.enabled_()},set(i){t.enabled_(i)}}),t}}class zp extends Te.EventTarget{constructor(){super();let e=this;return e.levels_=[],e.selectedIndex_=-1,Object.defineProperty(e,"selectedIndex",{get(){return e.selectedIndex_}}),Object.defineProperty(e,"length",{get(){return e.levels_.length}}),e[Symbol.iterator]=()=>e.levels_.values(),e}addQualityLevel(e){let t=this.getQualityLevelById(e.id);if(t)return t;const i=this.levels_.length;return t=new B3(e),""+i in this||Object.defineProperty(this,i,{get(){return this.levels_[i]}}),this.levels_.push(t),this.trigger({qualityLevel:t,type:"addqualitylevel"}),t}removeQualityLevel(e){let t=null;for(let i=0,n=this.length;ii&&this.selectedIndex_--;break}return t&&this.trigger({qualityLevel:e,type:"removequalitylevel"}),t}getQualityLevelById(e){for(let t=0,i=this.length;ti,s.qualityLevels.VERSION=fD,i},pD=function(s){return F3(this,Te.obj.merge({},s))};Te.registerPlugin("qualityLevels",pD);pD.VERSION=fD;const en=bm,Kp=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,$n=s=>Te.log.debug?Te.log.debug.bind(Te,"VHS:",`${s} >`):function(){};function Kt(...s){const e=Te.obj||Te;return(e.merge||e.mergeOptions).apply(e,s)}function ds(...s){const e=Te.time||Te;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function U3(s){if(s.length===0)return"Buffered Ranges are empty";let e=`Buffered Ranges: -`;for(let t=0;t ${n}. Duration (${n-i}) -`}return e}const Lr=1/30,Ir=Lr*3,mD=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},Yf=function(s,e){return mD(s,function(t){return t-Lr>=e})},$3=function(s){if(s.length<2)return ds();const e=[];for(let t=1;t{const e=[];if(!s||!s.length)return"";for(let t=0;t "+s.end(t));return e.join(", ")},H3=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},gl=s=>{const e=[];for(let t=0;tr)){if(e>n&&e<=r){t+=r-e;continue}t+=r-n}}return t},KT=(s,e)=>{if(!e.preload)return e.duration;let t=0;return(e.parts||[]).forEach(function(i){t+=i.duration}),(e.preloadHints||[]).forEach(function(i){i.type==="PART"&&(t+=s.partTargetDuration)}),t},Iv=s=>(s.segments||[]).reduce((e,t,i)=>(t.parts?t.parts.forEach(function(n,r){e.push({duration:n.duration,segmentIndex:i,partIndex:r,part:n,segment:t})}):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e),[]),yD=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},vD=({preloadSegment:s})=>{if(!s)return;const{parts:e,preloadHints:t}=s;let i=(t||[]).reduce((n,r)=>n+(r.type==="PART"?1:0),0);return i+=e&&e.length?e.length:0,i},TD=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=yD(e).length>0;return t&&e.serverControl&&e.serverControl.partHoldBack?e.serverControl.partHoldBack:t&&e.partTargetDuration?e.partTargetDuration*3:e.serverControl&&e.serverControl.holdBack?e.serverControl.holdBack:e.targetDuration?e.targetDuration*3:0},V3=function(s,e){let t=0,i=e-s.mediaSequence,n=s.segments[i];if(n){if(typeof n.start<"u")return{result:n.start,precise:!0};if(typeof n.end<"u")return{result:n.end-n.duration,precise:!0}}for(;i--;){if(n=s.segments[i],typeof n.end<"u")return{result:t+n.end,precise:!0};if(t+=KT(s,n),typeof n.start<"u")return{result:t+n.start,precise:!0}}return{result:t,precise:!1}},q3=function(s,e){let t=0,i,n=e-s.mediaSequence;for(;n"u"&&(e=s.mediaSequence+s.segments.length),e"u"){if(s.totalDuration)return s.totalDuration;if(!s.endList)return se.Infinity}return bD(s,e,t)},$d=function({defaultDuration:s,durationList:e,startIndex:t,endIndex:i}){let n=0;if(t>i&&([t,i]=[i,t]),t<0){for(let r=t;r0)for(let d=c-1;d>=0;d--){const f=u[d];if(o+=f.duration,r){if(o<0)continue}else if(o+Lr<=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n-$d({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e}}if(c<0){for(let d=c;d<0;d++)if(o-=s.targetDuration,o<0)return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e};c=0}for(let d=c;dLr,g=o===0,v=m&&o+Lr>=0;if(!((g||v)&&d!==u.length-1)){if(r){if(o>0)continue}else if(o-Lr>=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n+$d({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}}return{segmentIndex:u[u.length-1].segmentIndex,partIndex:u[u.length-1].partIndex,startTime:e}},SD=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},YT=function(s){return s.excludeUntil&&s.excludeUntil===1/0},$m=function(s){const e=SD(s);return!s.disabled&&!e},Y3=function(s){return s.disabled},W3=function(s){for(let e=0;e{if(s.playlists.length===1)return!0;const t=e.attributes.BANDWIDTH||Number.MAX_VALUE;return s.playlists.filter(i=>$m(i)?(i.attributes.BANDWIDTH||0)!s&&!e||!s&&e||s&&!e?!1:!!(s===e||s.id&&e.id&&s.id===e.id||s.resolvedUri&&e.resolvedUri&&s.resolvedUri===e.resolvedUri||s.uri&&e.uri&&s.uri===e.uri),e1=function(s,e){const t=s&&s.mediaGroups&&s.mediaGroups.AUDIO||{};let i=!1;for(const n in t){for(const r in t[n])if(i=e(t[n][r]),i)break;if(i)break}return!!i},hh=s=>{if(!s||!s.playlists||!s.playlists.length)return e1(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;eNA(r))||e1(s,r=>WT(t,r))))return!1}return!0};var tn={liveEdgeDelay:TD,duration:_D,seekable:z3,getMediaInfoForTime:K3,isEnabled:$m,isDisabled:Y3,isExcluded:SD,isIncompatible:YT,playlistEnd:xD,isAes:W3,hasAttribute:ED,estimateSegmentRequestTime:X3,isLowestEnabledRendition:kv,isAudioOnly:hh,playlistMatch:WT,segmentDurationWithParts:KT};const{log:AD}=Te,ju=(s,e)=>`${s}-${e}`,CD=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,Q3=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:n=[],llhls:r})=>{const o=new FP;s&&o.on("warn",s),e&&o.on("info",e),i.forEach(d=>o.addParser(d)),n.forEach(d=>o.addTagMapper(d)),o.push(t),o.end();const u=o.manifest;if(r||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(d){u.hasOwnProperty(d)&&delete u[d]}),u.segments&&u.segments.forEach(function(d){["parts","preloadHints"].forEach(function(f){d.hasOwnProperty(f)&&delete d[f]})})),!u.targetDuration){let d=10;u.segments&&u.segments.length&&(d=u.segments.reduce((f,m)=>Math.max(f,m.duration),0)),s&&s({message:`manifest has no targetDuration defaulting to ${d}`}),u.targetDuration=d}const c=yD(u);if(c.length&&!u.partTargetDuration){const d=c.reduce((f,m)=>Math.max(f,m.duration),0);s&&(s({message:`manifest has no partTargetDuration defaulting to ${d}`}),AD.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),u.partTargetDuration=d}return u},pc=(s,e)=>{s.mediaGroups&&["AUDIO","SUBTITLES"].forEach(t=>{if(s.mediaGroups[t])for(const i in s.mediaGroups[t])for(const n in s.mediaGroups[t][i]){const r=s.mediaGroups[t][i][n];e(r,t,i,n)}})},DD=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},Z3=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];DD({playlist:t,id:ju(e,t.uri)}),t.resolvedUri=en(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||AD.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},J3=s=>{pc(s,e=>{e.uri&&(e.resolvedUri=en(s.uri,e.uri))})},e5=(s,e)=>{const t=ju(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:se.location.href,resolvedUri:se.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},wD=(s,e,t=CD)=>{s.uri=e;for(let n=0;n{if(!n.playlists||!n.playlists.length){if(i&&r==="AUDIO"&&!n.uri)for(let c=0;c(n.set(r.id,r),n),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(this.offset_===null)return[];const e={},t=[];this.pendingDateRanges_.forEach((i,n)=>{if(!this.processedDateRanges_.has(n)&&(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),!!i.class))if(e[i.class]){const r=e[i.class].push(i);i.classListIndex=r-1}else e[i.class]=[i],i.classListIndex=0});for(const i of t){const n=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&n[i.classListIndex+1]?i.endTime=n[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((i,n)=>{i.startDate.getTime(){const n=e.status<200||e.status>299,r=e.status>=400&&e.status<=499,o={uri:e.uri,requestType:s},u=n&&!r||i;if(t&&r)o.error=$i({},t),o.errorType=Te.Error.NetworkRequestFailed;else if(e.aborted)o.errorType=Te.Error.NetworkRequestAborted;else if(e.timedout)o.errorType=Te.Error.NetworkRequestTimeout;else if(u){const c=i?Te.Error.NetworkBodyParserFailed:Te.Error.NetworkBadStatus;o.errorType=c,o.status=e.status,o.headers=e.headers}return o},t5=$n("CodecUtils"),ID=function(s){const e=s.attributes||{};if(e.CODECS)return Ar(e.CODECS)},kD=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},i5=(s,e)=>{if(!kD(s,e))return!0;const t=e.attributes||{},i=s.mediaGroups.AUDIO[t.AUDIO];for(const n in i)if(!i[n].uri&&!i[n].playlists)return!0;return!1},Wd=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:n})=>{e[t]=e[t]||[],e[t].push(MA(`${i}${n}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){t5(`multiple ${t} codecs found as attributes: ${e[t].join(", ")}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),e[t]=null;return}e[t]=e[t][0]}),e},i1=function(s){let e=0;return s.audio&&e++,s.video&&e++,e},jd=function(s,e){const t=e.attributes||{},i=Wd(ID(e)||[]);if(kD(s,e)&&!i.audio&&!i5(s,e)){const n=Wd($P(s,t.AUDIO)||[]);n.audio&&(i.audio=n.audio)}return i},{EventTarget:s5}=Te,n5=(s,e)=>{if(e.endList||!e.serverControl)return s;const t={};if(e.serverControl.canBlockReload){const{preloadSegment:i}=e;let n=e.mediaSequence+e.segments.length;if(i){const r=i.parts||[],o=vD(e)-1;o>-1&&o!==r.length-1&&(t._HLS_part=o),(o>-1||r.length)&&n--}t._HLS_msn=n}if(e.serverControl&&e.serverControl.canSkipUntil&&(t._HLS_skip=e.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(t).length){const i=new se.URL(s);["_HLS_skip","_HLS_msn","_HLS_part"].forEach(function(n){t.hasOwnProperty(n)&&i.searchParams.set(n,t[n])}),s=i.toString()}return s},r5=(s,e)=>{if(!s)return e;const t=Kt(s,e);if(s.preloadHints&&!e.preloadHints&&delete t.preloadHints,s.parts&&!e.parts)delete t.parts;else if(s.parts&&e.parts)for(let i=0;i{const i=s.slice(),n=e.slice();t=t||0;const r=[];let o;for(let u=0;u{!s.resolvedUri&&s.uri&&(s.resolvedUri=en(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=en(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=en(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=en(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=en(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=en(e,t.uri))})},OD=function(s){const e=s.segments||[],t=s.preloadSegment;if(t&&t.parts&&t.parts.length){if(t.preloadHints){for(let i=0;is===e||s.segments&&e.segments&&s.segments.length===e.segments.length&&s.endList===e.endList&&s.mediaSequence===e.mediaSequence&&s.preloadSegment===e.preloadSegment,Rv=(s,e,t=PD)=>{const i=Kt(s,{}),n=i.playlists[e.id];if(!n||t(n,e))return null;e.segments=OD(e);const r=Kt(n,e);if(r.preloadSegment&&!e.preloadSegment&&delete r.preloadSegment,n.segments){if(e.skip){e.segments=e.segments||[];for(let o=0;o{RD(o,r.resolvedUri)});for(let o=0;o{if(o.playlists)for(let f=0;f{const t=s.segments||[],i=t[t.length-1],n=i&&i.parts&&i.parts[i.parts.length-1],r=n&&n.duration||i&&i.duration;return e&&r?r*1e3:(s.partTargetDuration||s.targetDuration||10)*500},s1=(s,e,t)=>{if(!s)return;const i=[];return s.forEach(n=>{if(!n.attributes)return;const{BANDWIDTH:r,RESOLUTION:o,CODECS:u}=n.attributes;i.push({id:n.id,bandwidth:r,resolution:o,codecs:u})}),{type:e,isLive:t,renditions:i}};let Pu=class extends s5{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=$n("PlaylistLoader");const{withCredentials:n=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=n,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;const r=t.options_;this.customTagParsers=r&&r.customTagParsers||[],this.customTagMappers=r&&r.customTagMappers||[],this.llhls=r&&r.llhls,this.dateRangesStorage_=new t1,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){const e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);const t=this.dateRangesStorage_.getDateRangesToProcess();!t.length||!this.addDateRangesToTextTrack_||this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if(this.state!=="HAVE_METADATA")return;const e=this.media();let t=en(this.main.uri,e.uri);this.llhls&&(t=n5(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials,requestType:"hls-playlist"},(i,n)=>{if(this.request){if(i)return this.playlistRequestError(this.request,this.media(),"HAVE_METADATA");this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}})}playlistRequestError(e,t,i){const{uri:n,id:r}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[r],status:e.status,message:`HLS playlist request error at URL: ${n}.`,responseText:e.responseText,code:e.status>=500?4:2,metadata:_l({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=Q3({onwarn:({message:n})=>this.logger_(`m3u8-parser warn for ${e}: ${n}`),oninfo:({message:n})=>this.logger_(`m3u8-parser info for ${e}: ${n}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls});return!i.playlists||!i.playlists.length||this.excludeAudioOnlyVariants(i.playlists),i}catch(i){this.error=i,this.error.metadata={errorType:Te.Error.StreamingHlsPlaylistParserError,error:i}}}excludeAudioOnlyVariants(e){const t=i=>{const n=i.attributes||{},{width:r,height:o}=n.RESOLUTION||{};if(r&&o)return!0;const u=ID(i)||[];return!!Wd(u).video};e.some(t)&&e.forEach(i=>{t(i)||(i.excludeUntil=1/0)})}haveMetadata({playlistString:e,playlistObject:t,url:i,id:n}){this.request=null,this.state="HAVE_METADATA";const r={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:r});const o=t||this.parseManifest_({url:i,manifestString:e});o.lastRequest=Date.now(),DD({playlist:o,uri:i,id:n});const u=Rv(this.main,o);this.targetDuration=o.partTargetDuration||o.targetDuration,this.pendingMedia_=null,u?(this.main=u,this.media_=this.main.playlists[n]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(Ov(this.media(),!!u)),r.parsedPlaylist=s1(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),se.clearTimeout(this.mediaUpdateTimeout),se.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new t1,this.off()}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);if(typeof e=="string"){if(!this.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.main.playlists[e]}if(se.clearTimeout(this.finalRenditionTimeout),t){const u=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=se.setTimeout(this.media.bind(this,e,!1),u);return}const i=this.state,n=!this.media_||e.id!==this.media_.id,r=this.main.playlists[e.id];if(r&&r.endList||e.endList&&e.segments.length){this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,n&&(this.trigger("mediachanging"),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange"));return}if(this.updateMediaUpdateTimeout_(Ov(e,!0)),!n)return;if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e;const o={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:o}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(u,c)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=Kp(e.resolvedUri,c),u)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:o}),this.haveMetadata({playlistString:c.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(se.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),this.state==="HAVE_NOTHING"&&(this.started=!1),this.state==="SWITCHING_MEDIA"?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":this.state==="HAVE_CURRENT_METADATA"&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(se.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=se.setTimeout(()=>{this.mediaUpdateTimeout=null,this.load()},i);return}if(!this.started){this.start();return}t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist")}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(se.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=se.setTimeout(()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)},e))}start(){if(this.started=!0,typeof this.src=="object"){this.src.uri||(this.src.uri=se.location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);return}const e={playlistInfo:{type:"multivariant",uri:this.src}};this.trigger({type:"playlistrequeststart",metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,i)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:i.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:i.responseText,code:2,metadata:_l({requestType:i.requestType,request:i,error:t})},this.state==="HAVE_NOTHING"&&(this.started=!1),this.trigger("error");this.trigger({type:"playlistrequestcomplete",metadata:e}),this.src=Kp(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const n=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=s1(n.playlists,e.playlistInfo.type,!1),this.trigger({type:"playlistparsecomplete",metadata:e}),this.setupInitialPlaylist(n)})}srcUri(){return typeof this.src=="string"?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists){this.main=e,wD(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=OD(i),i.segments.forEach(n=>{RD(n,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||se.location.href;this.main=e5(e,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){const i=this.main,n=e.ID;let r=i.playlists.length;for(;r--;){const o=i.playlists[r];if(o.attributes["PATHWAY-ID"]===n){const u=o.resolvedUri,c=o.id;if(t){const d=this.createCloneURI_(o.resolvedUri,e),f=ju(n,d),m=this.createCloneAttributes_(n,o.attributes),g=this.createClonePlaylist_(o,f,e,m);i.playlists[r]=g,i.playlists[f]=g,i.playlists[d]=g}else i.playlists.splice(r,1);delete i.playlists[c],delete i.playlists[u]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,n=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!i.mediaGroups[r]||!i.mediaGroups[r][n])){for(const o in i.mediaGroups[r])if(o===n){for(const u in i.mediaGroups[r][o])i.mediaGroups[r][o][u].playlists.forEach((d,f)=>{const m=i.playlists[d.id],g=m.id,v=m.resolvedUri;delete i.playlists[g],delete i.playlists[v]});delete i.mediaGroups[r][o]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,n=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),o=ju(e.ID,r),u=this.createCloneAttributes_(e.ID,t.attributes),c=this.createClonePlaylist_(t,o,e,u);i.playlists[n]=c,i.playlists[o]=c,i.playlists[r]=c,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],n=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!n.mediaGroups[r]||n.mediaGroups[r][t]))for(const o in n.mediaGroups[r]){if(o===i)n.mediaGroups[r][t]={};else continue;for(const u in n.mediaGroups[r][o]){const c=n.mediaGroups[r][o][u];n.mediaGroups[r][t][u]=$i({},c);const d=n.mediaGroups[r][t][u],f=this.createCloneURI_(c.resolvedUri,e);d.resolvedUri=f,d.uri=f,d.playlists=[],c.playlists.forEach((m,g)=>{const v=n.playlists[m.id],b=CD(r,t,u),_=ju(t,b);if(v&&!n.playlists[_]){const E=this.createClonePlaylist_(v,_,e),L=E.resolvedUri;n.playlists[_]=E,n.playlists[L]=E}d.playlists[g]=this.createClonePlaylist_(m,_,e)})}}})}createClonePlaylist_(e,t,i,n){const r=this.createCloneURI_(e.resolvedUri,i),o={resolvedUri:r,uri:r,id:t};return e.segments&&(o.segments=[]),n&&(o.attributes=n),Kt(e,o)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const n=t["URI-REPLACEMENT"].PARAMS;for(const r of Object.keys(n))i.searchParams.set(r,n[r]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(n=>{t[n]&&(i[n]=e)}),i}getKeyIdSet(e){const t=new Set;if(!e||!e.contentProtection)return t;for(const i in e.contentProtection)if(e.contentProtection[i]&&e.contentProtection[i].attributes&&e.contentProtection[i].attributes.keyId){const n=e.contentProtection[i].attributes.keyId;t.add(n.toLowerCase())}return t}};const Pv=function(s,e,t,i){const n=s.responseType==="arraybuffer"?s.response:s.responseText;!e&&n&&(s.responseTime=Date.now(),s.roundTripTime=s.responseTime-s.requestTime,s.bytesReceived=n.byteLength||n.length,s.bandwidth||(s.bandwidth=Math.floor(s.bytesReceived/s.roundTripTime*8*1e3))),t.headers&&(s.responseHeaders=t.headers),e&&e.code==="ETIMEDOUT"&&(s.timedout=!0),!e&&!s.aborted&&t.statusCode!==200&&t.statusCode!==206&&t.statusCode!==0&&(e=new Error("XHR Failed with a response of: "+(s&&(n||s.responseText)))),i(e,s)},o5=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},l5=(s,e,t,i)=>{!s||!s.size||s.forEach(n=>{n(e,t,i)})},MD=function(){const s=function e(t,i){t=Kt({timeout:45e3},t);const n=e.beforeRequest||Te.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||Te.Vhs.xhr._requestCallbackSet||new Set,o=e._responseCallbackSet||Te.Vhs.xhr._responseCallbackSet;n&&typeof n=="function"&&(Te.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(n));const u=Te.Vhs.xhr.original===!0?Te.xhr:Te.Vhs.xhr,c=o5(r,t);r.delete(n);const d=u(c||t,function(m,g){return l5(o,d,m,g),Pv(d,m,g,i)}),f=d.abort;return d.abort=function(){return d.aborted=!0,f.apply(d,arguments)},d.uri=t.uri,d.requestType=t.requestType,d.requestTime=Date.now(),d};return s.original=!0,s},u5=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=se.BigInt(s.offset)+se.BigInt(s.length)-se.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},Mv=function(s){const e={};return s.byterange&&(e.Range=u5(s.byterange)),e},c5=function(s,e){return s.start(e)+"-"+s.end(e)},d5=function(s,e){const t=s.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},h5=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},ND=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];FA(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},Yp=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},BD=function(s){return s.resolvedUri},FD=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",n,r;for(let o=0;oFD(s),p5=s=>{let e="",t;for(t=0;t{if(!e.dateTimeObject)return null;const t=e.videoTimingInfo.transmuxerPrependedSeconds,n=e.videoTimingInfo.transmuxedPresentationStart+t,r=s-n;return new Date(e.dateTimeObject.getTime()+r*1e3)},y5=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,v5=(s,e)=>{let t;try{t=new Date(s)}catch{return null}if(!e||!e.segments||e.segments.length===0)return null;let i=e.segments[0];if(tu?null:(t>new Date(r)&&(i=n),{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:tn.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},T5=(s,e)=>{if(!e||!e.segments||e.segments.length===0)return null;let t=0,i;for(let r=0;rt){if(s>t+n.duration*UD)return null;i=n}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:t-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},b5=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const n=t.getTime();return(i.getTime()-n)/1e3},_5=s=>{if(!s.segments||s.segments.length===0)return!1;for(let e=0;e{if(!t)throw new Error("getProgramTime: callback must be provided");if(!s||e===void 0)return t({message:"getProgramTime: playlist and time must be provided"});const i=T5(e,s);if(!i)return t({message:"valid programTime was not found"});if(i.type==="estimate")return t({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:i.estimatedStart});const n={mediaSeconds:e},r=g5(e,i.segment);return r&&(n.programDateTime=r.toISOString()),t(null,n)},$D=({programTime:s,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:n=!0,tech:r,callback:o})=>{if(!o)throw new Error("seekToProgramTime: callback must be provided");if(typeof s>"u"||!e||!i)return o({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!r.hasStarted_)return o({message:"player must be playing a live stream to start buffering"});if(!_5(e))return o({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const u=v5(s,e);if(!u)return o({message:`${s} was not found in the stream`});const c=u.segment,d=b5(c.dateTimeObject,s);if(u.type==="estimate"){if(t===0)return o({message:`${s} is not buffered yet. Try again`});i(u.estimatedStart+d),r.one("seeked",()=>{$D({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:n,tech:r,callback:o})});return}const f=c.start+d,m=()=>o(null,r.currentTime());r.one("seeked",m),n&&r.pause(),i(f)},ky=(s,e)=>{if(s.readyState===4)return e()},S5=(s,e,t,i)=>{let n=[],r,o=!1;const u=function(m,g,v,b){return g.abort(),o=!0,t(m,g,v,b)},c=function(m,g){if(o)return;if(m)return m.metadata=_l({requestType:i,request:g,error:m}),u(m,g,"",n);const v=g.responseText.substring(n&&n.byteLength||0,g.responseText.length);if(n=XP(n,UA(v,!0)),r=r||wd(n),n.length<10||r&&n.lengthu(m,g,"",n));const b=TT(n);return b==="ts"&&n.length<188?ky(g,()=>u(m,g,"",n)):!b&&n.length<376?ky(g,()=>u(m,g,"",n)):u(null,g,b,n)},f=e({uri:s,beforeSend(m){m.overrideMimeType("text/plain; charset=x-user-defined"),m.addEventListener("progress",function({total:g,loaded:v}){return Pv(m,null,{statusCode:m.status},c)})}},function(m,g){return Pv(f,m,g,c)});return f},{EventTarget:E5}=Te,n1=function(s,e){if(!PD(s,e)||s.sidx&&e.sidx&&(s.sidx.offset!==e.sidx.offset||s.sidx.length!==e.sidx.length))return!1;if(!s.sidx&&e.sidx||s.sidx&&!e.sidx||s.segments&&!e.segments||!s.segments&&e.segments)return!1;if(!s.segments&&!e.segments)return!0;for(let t=0;t{const n=i.attributes.NAME||t;return`placeholder-uri-${s}-${e}-${n}`},C5=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:n})=>{const r=YM(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:n});return wD(r,e,A5),r},D5=(s,e)=>{pc(s,(t,i,n,r)=>{(!e.mediaGroups[i][n]||!(r in e.mediaGroups[i][n]))&&delete s.mediaGroups[i][n][r]})},w5=(s,e,t)=>{let i=!0,n=Kt(s,{duration:e.duration,minimumUpdatePeriod:e.minimumUpdatePeriod,timelineStarts:e.timelineStarts});for(let r=0;r{if(r.playlists&&r.playlists.length){const d=r.playlists[0].id,f=Rv(n,r.playlists[0],n1);f&&(n=f,c in n.mediaGroups[o][u]||(n.mediaGroups[o][u][c]=r),n.mediaGroups[o][u][c].playlists[0]=n.playlists[d],i=!1)}}),D5(n,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:n},L5=(s,e)=>(!s.map&&!e.map||!!(s.map&&e.map&&s.map.byterange.offset===e.map.byterange.offset&&s.map.byterange.length===e.map.byterange.length))&&s.uri===e.uri&&s.byterange.offset===e.byterange.offset&&s.byterange.length===e.byterange.length,r1=(s,e)=>{const t={};for(const i in s){const r=s[i].sidx;if(r){const o=xm(r);if(!e[o])break;const u=e[o].sidxInfo;L5(u,r)&&(t[o]=e[o])}}return t},I5=(s,e)=>{let i=r1(s.playlists,e);return pc(s,(n,r,o,u)=>{if(n.playlists&&n.playlists.length){const c=n.playlists;i=Kt(i,r1(c,e))}}),i};class Nv extends E5{constructor(e,t,i={},n){super(),this.isPaused_=!0,this.mainPlaylistLoader_=n||this,n||(this.isMain_=!0);const{withCredentials:r=!1}=i;if(this.vhs_=t,this.withCredentials=r,this.addMetadataToTextTrack=i.addMetadataToTextTrack,!e)throw new Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",()=>{this.refreshXml_()}),this.on("mediaupdatetimeout",()=>{this.refreshMedia_(this.media().id)}),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=$n("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}get isPaused(){return this.isPaused_}requestErrored_(e,t,i){if(!this.request)return!0;if(this.request=null,e)return this.error=typeof e=="object"&&!(e instanceof Error)?e:{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2,metadata:e.metadata},i&&(this.state=i),this.trigger("error"),!0}addSidxSegments_(e,t,i){const n=e.sidx&&xm(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n]){se.clearTimeout(this.mediaRequest_),this.mediaRequest_=se.setTimeout(()=>i(!1),0);return}const r=Kp(e.sidx.resolvedUri),o=(c,d)=>{if(this.requestErrored_(c,d,t))return;const f=this.mainPlaylistLoader_.sidxMapping_,{requestType:m}=d;let g;try{g=JM(dt(d.response).subarray(8))}catch(v){v.metadata=_l({requestType:m,request:d,parseFailure:!0}),this.requestErrored_(v,d,t);return}return f[n]={sidxInfo:e.sidx,sidx:g},gT(e,g,e.sidx.resolvedUri),i(!0)},u="dash-sidx";this.request=S5(r,this.vhs_.xhr,(c,d,f,m)=>{if(c)return o(c,d);if(!f||f!=="mp4"){const b=f||"unknown";return o({status:d.status,message:`Unsupported ${b} container type for sidx segment at URL: ${r}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},d)}const{offset:g,length:v}=e.sidx.byterange;if(m.length>=v+g)return o(c,{response:m.subarray(g,g+v),status:d.status,uri:d.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:Mv({byterange:e.sidx.byterange})},o)},u)}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},se.clearTimeout(this.minimumUpdatePeriodTimeout_),se.clearTimeout(this.mediaRequest_),se.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);const t=this.state;if(typeof e=="string"){if(!this.mainPlaylistLoader_.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}const i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList){this.state="HAVE_METADATA",this.media_=e,i&&(this.trigger("mediachanging"),this.trigger("mediachange"));return}i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,n=>{this.haveMetadata({startingState:t,playlist:e})}))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,se.clearTimeout(this.mediaRequest_),this.mediaRequest_=null,this.refreshMedia_(t.id),e==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.isPaused_=!0,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),se.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(se.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){this.isPaused_=!1,se.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=se.setTimeout(()=>this.load(),i);return}if(!this.started){this.start();return}t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist")}start(){if(this.started=!0,!this.isMain_){se.clearTimeout(this.mediaRequest_),this.mediaRequest_=se.setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),!this.hasPendingRequest()&&!this.media_&&this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){const t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(i,n)=>{if(i){const{requestType:o}=n;i.metadata=_l({requestType:o,request:n,error:i})}if(this.requestErrored_(i,n)){this.state==="HAVE_NOTHING"&&(this.started=!1);return}this.trigger({type:"manifestrequestcomplete",metadata:t});const r=n.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=n.responseText,n.responseHeaders&&n.responseHeaders.date?this.mainLoaded_=Date.parse(n.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=Kp(this.mainPlaylistLoader_.srcUrl,n),r){this.handleMain_(),this.syncClientServerClock_(()=>e(n,r));return}return e(n,r)})}syncClientServerClock_(e){const t=WM(this.mainPlaylistLoader_.mainXml_);if(t===null)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e();if(t.method==="DIRECT")return this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e();this.request=this.vhs_.xhr({uri:en(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,n)=>{if(!this.request)return;if(i){const{requestType:o}=n;return this.error.metadata=_l({requestType:o,request:n,error:i}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}let r;t.method==="HEAD"?!n.responseHeaders||!n.responseHeaders.date?r=this.mainLoaded_:r=Date.parse(n.responseHeaders.date):r=Date.parse(n.responseText),this.mainPlaylistLoader_.clientOffset_=r-Date.now(),e()})}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){se.clearTimeout(this.mediaRequest_),this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main,t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestparsestart",metadata:t});let i;try{i=C5({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e})}catch(r){this.error=r,this.error.metadata={errorType:Te.Error.StreamingDashManifestParserError,error:r},this.trigger("error")}e&&(i=w5(e,i,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=i||e;const n=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(n&&n!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=n),(!e||i&&i.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(i),i){const{duration:r,endList:o}=i,u=[];i.playlists.forEach(d=>{u.push({id:d.id,bandwidth:d.attributes.BANDWIDTH,resolution:d.attributes.RESOLUTION,codecs:d.attributes.CODECS})});const c={duration:r,isLive:!o,renditions:u};t.parsedManifest=c,this.trigger({type:"manifestparsecomplete",metadata:t})}return!!i}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(se.clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;if(t===0&&(e.media()?t=e.media().targetDuration*1e3:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),typeof t!="number"||t<=0){t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`);return}this.createMUPTimeout_(t)}createMUPTimeout_(e){const t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=se.setTimeout(()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)},e)}refreshXml_(){this.requestMain_((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=I5(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,i=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(e){if(!e)throw new Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const t=this.mainPlaylistLoader_.main.playlists,i=!this.media_||this.media_!==t[e];if(i?this.media_=t[e]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){const n=()=>{this.media().endList||(this.mediaUpdateTimeout=se.setTimeout(()=>{this.trigger("mediaupdatetimeout"),n()},Ov(this.media(),!!i)))};n()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){const t=this.mainPlaylistLoader_.main.eventStream.map(i=>({cueTime:i.start,frames:[{data:i.messageData}]}));this.addMetadataToTextTrack("EventStream",t,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const n=e.contentProtection[i].attributes["cenc:default_KID"];n&&t.add(n.replace(/-/g,"").toLowerCase())}return t}}}var us={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};const k5=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(S){var C,A,D,P;if(C=y[S],!!C)if(arguments.length===2)for(D=C.length,A=0;A"u")){for(y in ee)ee.hasOwnProperty(y)&&(ee[y]=[y.charCodeAt(0),y.charCodeAt(1),y.charCodeAt(2),y.charCodeAt(3)]);le=new Uint8Array([105,115,111,109]),Y=new Uint8Array([97,118,99,49]),ae=new Uint8Array([0,0,0,1]),Q=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),te=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),oe={video:Q,audio:te},ie=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),$=new Uint8Array([0,0,0,0,0,0,0,0]),he=new Uint8Array([0,0,0,0,0,0,0,0]),Ce=he,be=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ue=he,de=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),u=function(y){var S=[],C=0,A,D,P;for(A=1;A>>1,y.samplingfrequencyindex<<7|y.channelcount<<3,6,1,2]))},f=function(){return u(ee.ftyp,le,ae,le,Y)},V=function(y){return u(ee.hdlr,oe[y])},m=function(y){return u(ee.mdat,y)},U=function(y){var S=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,y.duration>>>24&255,y.duration>>>16&255,y.duration>>>8&255,y.duration&255,85,196,0,0]);return y.samplerate&&(S[12]=y.samplerate>>>24&255,S[13]=y.samplerate>>>16&255,S[14]=y.samplerate>>>8&255,S[15]=y.samplerate&255),u(ee.mdhd,S)},F=function(y){return u(ee.mdia,U(y),V(y.type),v(y))},g=function(y){return u(ee.mfhd,new Uint8Array([0,0,0,0,(y&4278190080)>>24,(y&16711680)>>16,(y&65280)>>8,y&255]))},v=function(y){return u(ee.minf,y.type==="video"?u(ee.vmhd,de):u(ee.smhd,$),c(),q(y))},b=function(y,S){for(var C=[],A=S.length;A--;)C[A]=R(S[A]);return u.apply(null,[ee.moof,g(y)].concat(C))},_=function(y){for(var S=y.length,C=[];S--;)C[S]=I(y[S]);return u.apply(null,[ee.moov,L(4294967295)].concat(C).concat(E(y)))},E=function(y){for(var S=y.length,C=[];S--;)C[S]=K(y[S]);return u.apply(null,[ee.mvex].concat(C))},L=function(y){var S=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(y&4278190080)>>24,(y&16711680)>>16,(y&65280)>>8,y&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return u(ee.mvhd,S)},B=function(y){var S=y.samples||[],C=new Uint8Array(4+S.length),A,D;for(D=0;D>>8),P.push(A[Z].byteLength&255),P=P.concat(Array.prototype.slice.call(A[Z]));for(Z=0;Z>>8),W.push(D[Z].byteLength&255),W=W.concat(Array.prototype.slice.call(D[Z]));if(J=[ee.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(C.width&65280)>>8,C.width&255,(C.height&65280)>>8,C.height&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u(ee.avcC,new Uint8Array([1,C.profileIdc,C.profileCompatibility,C.levelIdc,255].concat([A.length],P,[D.length],W))),u(ee.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],C.sarRatio){var ne=C.sarRatio[0],pe=C.sarRatio[1];J.push(u(ee.pasp,new Uint8Array([(ne&4278190080)>>24,(ne&16711680)>>16,(ne&65280)>>8,ne&255,(pe&4278190080)>>24,(pe&16711680)>>16,(pe&65280)>>8,pe&255])))}return u.apply(null,J)},S=function(C){return u(ee.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(C.channelcount&65280)>>8,C.channelcount&255,(C.samplesize&65280)>>8,C.samplesize&255,0,0,0,0,(C.samplerate&65280)>>8,C.samplerate&255,0,0]),d(C))}})(),w=function(y){var S=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(y.id&4278190080)>>24,(y.id&16711680)>>16,(y.id&65280)>>8,y.id&255,0,0,0,0,(y.duration&4278190080)>>24,(y.duration&16711680)>>16,(y.duration&65280)>>8,y.duration&255,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(y.width&65280)>>8,y.width&255,0,0,(y.height&65280)>>8,y.height&255,0,0]);return u(ee.tkhd,S)},R=function(y){var S,C,A,D,P,W,Z;return S=u(ee.tfhd,new Uint8Array([0,0,0,58,(y.id&4278190080)>>24,(y.id&16711680)>>16,(y.id&65280)>>8,y.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),W=Math.floor(y.baseMediaDecodeTime/o),Z=Math.floor(y.baseMediaDecodeTime%o),C=u(ee.tfdt,new Uint8Array([1,0,0,0,W>>>24&255,W>>>16&255,W>>>8&255,W&255,Z>>>24&255,Z>>>16&255,Z>>>8&255,Z&255])),P=92,y.type==="audio"?(A=X(y,P),u(ee.traf,S,C,A)):(D=B(y),A=X(y,D.length+P),u(ee.traf,S,C,A,D))},I=function(y){return y.duration=y.duration||4294967295,u(ee.trak,w(y),F(y))},K=function(y){var S=new Uint8Array([0,0,0,0,(y.id&4278190080)>>24,(y.id&16711680)>>16,(y.id&65280)>>8,y.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return y.type!=="video"&&(S[S.length-1]=0),u(ee.trex,S)},(function(){var y,S,C;C=function(A,D){var P=0,W=0,Z=0,J=0;return A.length&&(A[0].duration!==void 0&&(P=1),A[0].size!==void 0&&(W=2),A[0].flags!==void 0&&(Z=4),A[0].compositionTimeOffset!==void 0&&(J=8)),[0,0,P|W|Z|J,1,(A.length&4278190080)>>>24,(A.length&16711680)>>>16,(A.length&65280)>>>8,A.length&255,(D&4278190080)>>>24,(D&16711680)>>>16,(D&65280)>>>8,D&255]},S=function(A,D){var P,W,Z,J,ne,pe;for(J=A.samples||[],D+=20+16*J.length,Z=C(J,D),W=new Uint8Array(Z.length+J.length*16),W.set(Z),P=Z.length,pe=0;pe>>24,W[P++]=(ne.duration&16711680)>>>16,W[P++]=(ne.duration&65280)>>>8,W[P++]=ne.duration&255,W[P++]=(ne.size&4278190080)>>>24,W[P++]=(ne.size&16711680)>>>16,W[P++]=(ne.size&65280)>>>8,W[P++]=ne.size&255,W[P++]=ne.flags.isLeading<<2|ne.flags.dependsOn,W[P++]=ne.flags.isDependedOn<<6|ne.flags.hasRedundancy<<4|ne.flags.paddingValue<<1|ne.flags.isNonSyncSample,W[P++]=ne.flags.degradationPriority&61440,W[P++]=ne.flags.degradationPriority&15,W[P++]=(ne.compositionTimeOffset&4278190080)>>>24,W[P++]=(ne.compositionTimeOffset&16711680)>>>16,W[P++]=(ne.compositionTimeOffset&65280)>>>8,W[P++]=ne.compositionTimeOffset&255;return u(ee.trun,W)},y=function(A,D){var P,W,Z,J,ne,pe;for(J=A.samples||[],D+=20+8*J.length,Z=C(J,D),P=new Uint8Array(Z.length+J.length*8),P.set(Z),W=Z.length,pe=0;pe>>24,P[W++]=(ne.duration&16711680)>>>16,P[W++]=(ne.duration&65280)>>>8,P[W++]=ne.duration&255,P[W++]=(ne.size&4278190080)>>>24,P[W++]=(ne.size&16711680)>>>16,P[W++]=(ne.size&65280)>>>8,P[W++]=ne.size&255;return u(ee.trun,P)},X=function(A,D){return A.type==="audio"?y(A,D):S(A,D)}})();var Ee={ftyp:f,mdat:m,moof:b,moov:_,initSegment:function(y){var S=f(),C=_(y),A;return A=new Uint8Array(S.byteLength+C.byteLength),A.set(S),A.set(C,S.byteLength),A}},je=function(y){var S,C,A=[],D=[];for(D.byteLength=0,D.nalCount=0,D.duration=0,A.byteLength=0,S=0;S1&&(S=y.shift(),y.byteLength-=S.byteLength,y.nalCount-=S.nalCount,y[0][0].dts=S.dts,y[0][0].pts=S.pts,y[0][0].duration+=S.duration),y},lt=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},Me=function(y,S){var C=lt();return C.dataOffset=S,C.compositionTimeOffset=y.pts-y.dts,C.duration=y.duration,C.size=4*y.length,C.size+=y.byteLength,y.keyFrame&&(C.flags.dependsOn=2,C.flags.isNonSyncSample=0),C},Je=function(y,S){var C,A,D,P,W,Z=S||0,J=[];for(C=0;CTi.ONE_SECOND_IN_TS/2))){for(ne=Ls()[y.samplerate],ne||(ne=S[0].data),pe=0;pe=C?y:(S.minSegmentDts=1/0,y.filter(function(A){return A.dts>=C?(S.minSegmentDts=Math.min(S.minSegmentDts,A.dts),S.minSegmentPts=S.minSegmentDts,!0):!1}))},Ae=function(y){var S,C,A=[];for(S=0;S=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(y),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},Gt.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},Gt.prototype.addText=function(y){this.rows[this.rowIdx]+=y},Gt.prototype.backspace=function(){if(!this.isEmpty()){var y=this.rows[this.rowIdx];this.rows[this.rowIdx]=y.substr(0,y.length-1)}};var Bt=function(y,S,C){this.serviceNum=y,this.text="",this.currentWindow=new Gt(-1),this.windows=[],this.stream=C,typeof S=="string"&&this.createTextDecoder(S)};Bt.prototype.init=function(y,S){this.startPts=y;for(var C=0;C<8;C++)this.windows[C]=new Gt(C),typeof S=="function"&&(this.windows[C].beforeRowOverflow=S)},Bt.prototype.setCurrentWindow=function(y){this.currentWindow=this.windows[y]},Bt.prototype.createTextDecoder=function(y){if(typeof TextDecoder>"u")this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(y)}catch(S){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+y+" encoding. "+S})}};var Ot=function(y){y=y||{},Ot.prototype.init.call(this);var S=this,C=y.captionServices||{},A={},D;Object.keys(C).forEach(P=>{D=C[P],/^SERVICE/.test(P)&&(A[P]=D.encoding)}),this.serviceEncodings=A,this.current708Packet=null,this.services={},this.push=function(P){P.type===3?(S.new708Packet(),S.add708Bytes(P)):(S.current708Packet===null&&S.new708Packet(),S.add708Bytes(P))}};Ot.prototype=new Oi,Ot.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Ot.prototype.add708Bytes=function(y){var S=y.ccData,C=S>>>8,A=S&255;this.current708Packet.ptsVals.push(y.pts),this.current708Packet.data.push(C),this.current708Packet.data.push(A)},Ot.prototype.push708Packet=function(){var y=this.current708Packet,S=y.data,C=null,A=null,D=0,P=S[D++];for(y.seq=P>>6,y.sizeCode=P&63;D>5,A=P&31,C===7&&A>0&&(P=S[D++],C=P),this.pushServiceBlock(C,D,A),A>0&&(D+=A-1)},Ot.prototype.pushServiceBlock=function(y,S,C){var A,D=S,P=this.current708Packet.data,W=this.services[y];for(W||(W=this.initService(y,D));D("0"+(Ze&255).toString(16)).slice(-2)).join("")}if(D?(Le=[Z,J],y++):Le=[Z],S.textDecoder_&&!A)pe=S.textDecoder_.decode(new Uint8Array(Le));else if(D){const Re=Ke(Le);pe=String.fromCharCode(parseInt(Re,16))}else pe=Is(W|Z);return ne.pendingNewLine&&!ne.isEmpty()&&ne.newLine(this.getPts(y)),ne.pendingNewLine=!1,ne.addText(pe),y},Ot.prototype.multiByteCharacter=function(y,S){var C=this.current708Packet.data,A=C[y+1],D=C[y+2];return Mi(A)&&Mi(D)&&(y=this.handleText(++y,S,{isMultiByte:!0})),y},Ot.prototype.setCurrentWindow=function(y,S){var C=this.current708Packet.data,A=C[y],D=A&7;return S.setCurrentWindow(D),y},Ot.prototype.defineWindow=function(y,S){var C=this.current708Packet.data,A=C[y],D=A&7;S.setCurrentWindow(D);var P=S.currentWindow;return A=C[++y],P.visible=(A&32)>>5,P.rowLock=(A&16)>>4,P.columnLock=(A&8)>>3,P.priority=A&7,A=C[++y],P.relativePositioning=(A&128)>>7,P.anchorVertical=A&127,A=C[++y],P.anchorHorizontal=A,A=C[++y],P.anchorPoint=(A&240)>>4,P.rowCount=A&15,A=C[++y],P.columnCount=A&63,A=C[++y],P.windowStyle=(A&56)>>3,P.penStyle=A&7,P.virtualRowCount=P.rowCount+1,y},Ot.prototype.setWindowAttributes=function(y,S){var C=this.current708Packet.data,A=C[y],D=S.currentWindow.winAttr;return A=C[++y],D.fillOpacity=(A&192)>>6,D.fillRed=(A&48)>>4,D.fillGreen=(A&12)>>2,D.fillBlue=A&3,A=C[++y],D.borderType=(A&192)>>6,D.borderRed=(A&48)>>4,D.borderGreen=(A&12)>>2,D.borderBlue=A&3,A=C[++y],D.borderType+=(A&128)>>5,D.wordWrap=(A&64)>>6,D.printDirection=(A&48)>>4,D.scrollDirection=(A&12)>>2,D.justify=A&3,A=C[++y],D.effectSpeed=(A&240)>>4,D.effectDirection=(A&12)>>2,D.displayEffect=A&3,y},Ot.prototype.flushDisplayed=function(y,S){for(var C=[],A=0;A<8;A++)S.windows[A].visible&&!S.windows[A].isEmpty()&&C.push(S.windows[A].getText());S.endPts=y,S.text=C.join(` - -`),this.pushCaption(S),S.startPts=y},Ot.prototype.pushCaption=function(y){y.text!==""&&(this.trigger("data",{startPts:y.startPts,endPts:y.endPts,text:y.text,stream:"cc708_"+y.serviceNum}),y.text="",y.startPts=y.endPts)},Ot.prototype.displayWindows=function(y,S){var C=this.current708Packet.data,A=C[++y],D=this.getPts(y);this.flushDisplayed(D,S);for(var P=0;P<8;P++)A&1<>4,D.offset=(A&12)>>2,D.penSize=A&3,A=C[++y],D.italics=(A&128)>>7,D.underline=(A&64)>>6,D.edgeType=(A&56)>>3,D.fontStyle=A&7,y},Ot.prototype.setPenColor=function(y,S){var C=this.current708Packet.data,A=C[y],D=S.currentWindow.penColor;return A=C[++y],D.fgOpacity=(A&192)>>6,D.fgRed=(A&48)>>4,D.fgGreen=(A&12)>>2,D.fgBlue=A&3,A=C[++y],D.bgOpacity=(A&192)>>6,D.bgRed=(A&48)>>4,D.bgGreen=(A&12)>>2,D.bgBlue=A&3,A=C[++y],D.edgeRed=(A&48)>>4,D.edgeGreen=(A&12)>>2,D.edgeBlue=A&3,y},Ot.prototype.setPenLocation=function(y,S){var C=this.current708Packet.data,A=C[y],D=S.currentWindow.penLoc;return S.currentWindow.pendingNewLine=!0,A=C[++y],D.row=A&15,A=C[++y],D.column=A&63,y},Ot.prototype.reset=function(y,S){var C=this.getPts(y);return this.flushDisplayed(C,S),this.initService(S.serviceNum,y)};var Cn={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},jr=function(y){return y===null?"":(y=Cn[y]||y,String.fromCharCode(y))},wl=14,fh=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],on=function(){for(var y=[],S=wl+1;S--;)y.push({text:"",indent:0,offset:0});return y},Jt=function(y,S){Jt.prototype.init.call(this),this.field_=y||0,this.dataChannel_=S||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(C){var A,D,P,W,Z;if(A=C.ccData&32639,A===this.lastControlCode_){this.lastControlCode_=null;return}if((A&61440)===4096?this.lastControlCode_=A:A!==this.PADDING_&&(this.lastControlCode_=null),P=A>>>8,W=A&255,A!==this.PADDING_)if(A===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(A===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(C.pts),this.flushDisplayed(C.pts),D=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=D,this.startPts_=C.pts;else if(A===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(C.pts);else if(A===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(C.pts);else if(A===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(C.pts);else if(A===this.CARRIAGE_RETURN_)this.clearFormatting(C.pts),this.flushDisplayed(C.pts),this.shiftRowsUp_(),this.startPts_=C.pts;else if(A===this.BACKSPACE_)this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(A===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(C.pts),this.displayed_=on();else if(A===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=on();else if(A===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(C.pts),this.displayed_=on()),this.mode_="paintOn",this.startPts_=C.pts;else if(this.isSpecialCharacter(P,W))P=(P&3)<<8,Z=jr(P|W),this[this.mode_](C.pts,Z),this.column_++;else if(this.isExtCharacter(P,W))this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),P=(P&3)<<8,Z=jr(P|W),this[this.mode_](C.pts,Z),this.column_++;else if(this.isMidRowCode(P,W))this.clearFormatting(C.pts),this[this.mode_](C.pts," "),this.column_++,(W&14)===14&&this.addFormatting(C.pts,["i"]),(W&1)===1&&this.addFormatting(C.pts,["u"]);else if(this.isOffsetControlCode(P,W)){const ne=W&3;this.nonDisplayed_[this.row_].offset=ne,this.column_+=ne}else if(this.isPAC(P,W)){var J=fh.indexOf(A&7968);if(this.mode_==="rollUp"&&(J-this.rollUpRows_+1<0&&(J=this.rollUpRows_-1),this.setRollUp(C.pts,J)),J!==this.row_&&J>=0&&J<=14&&(this.clearFormatting(C.pts),this.row_=J),W&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(C.pts,["u"]),(A&16)===16){const ne=(A&14)>>1;this.column_=ne*4,this.nonDisplayed_[this.row_].indent+=ne}this.isColorPAC(W)&&(W&14)===14&&this.addFormatting(C.pts,["i"])}else this.isNormalChar(P)&&(W===0&&(W=null),Z=jr(P),Z+=jr(W),this[this.mode_](C.pts,Z),this.column_+=Z.length)}};Jt.prototype=new Oi,Jt.prototype.flushDisplayed=function(y){const S=A=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+A+"."})},C=[];this.displayed_.forEach((A,D)=>{if(A&&A.text&&A.text.length){try{A.text=A.text.trim()}catch{S(D)}A.text.length&&C.push({text:A.text,line:D+1,position:10+Math.min(70,A.indent*10)+A.offset*2.5})}else A==null&&S(D)}),C.length&&this.trigger("data",{startPts:this.startPts_,endPts:y,content:C,stream:this.name_})},Jt.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=on(),this.nonDisplayed_=on(),this.lastControlCode_=null,this.column_=0,this.row_=wl,this.rollUpRows_=2,this.formatting_=[]},Jt.prototype.setConstants=function(){this.dataChannel_===0?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):this.dataChannel_===1&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=this.CONTROL_|32,this.END_OF_CAPTION_=this.CONTROL_|47,this.ROLL_UP_2_ROWS_=this.CONTROL_|37,this.ROLL_UP_3_ROWS_=this.CONTROL_|38,this.ROLL_UP_4_ROWS_=this.CONTROL_|39,this.CARRIAGE_RETURN_=this.CONTROL_|45,this.RESUME_DIRECT_CAPTIONING_=this.CONTROL_|41,this.BACKSPACE_=this.CONTROL_|33,this.ERASE_DISPLAYED_MEMORY_=this.CONTROL_|44,this.ERASE_NON_DISPLAYED_MEMORY_=this.CONTROL_|46},Jt.prototype.isSpecialCharacter=function(y,S){return y===this.EXT_&&S>=48&&S<=63},Jt.prototype.isExtCharacter=function(y,S){return(y===this.EXT_+1||y===this.EXT_+2)&&S>=32&&S<=63},Jt.prototype.isMidRowCode=function(y,S){return y===this.EXT_&&S>=32&&S<=47},Jt.prototype.isOffsetControlCode=function(y,S){return y===this.OFFSET_&&S>=33&&S<=35},Jt.prototype.isPAC=function(y,S){return y>=this.BASE_&&y=64&&S<=127},Jt.prototype.isColorPAC=function(y){return y>=64&&y<=79||y>=96&&y<=127},Jt.prototype.isNormalChar=function(y){return y>=32&&y<=127},Jt.prototype.setRollUp=function(y,S){if(this.mode_!=="rollUp"&&(this.row_=wl,this.mode_="rollUp",this.flushDisplayed(y),this.nonDisplayed_=on(),this.displayed_=on()),S!==void 0&&S!==this.row_)for(var C=0;C"},"");this[this.mode_](y,C)},Jt.prototype.clearFormatting=function(y){if(this.formatting_.length){var S=this.formatting_.reverse().reduce(function(C,A){return C+""},"");this.formatting_=[],this[this.mode_](y,S)}},Jt.prototype.popOn=function(y,S){var C=this.nonDisplayed_[this.row_].text;C+=S,this.nonDisplayed_[this.row_].text=C},Jt.prototype.rollUp=function(y,S){var C=this.displayed_[this.row_].text;C+=S,this.displayed_[this.row_].text=C},Jt.prototype.shiftRowsUp_=function(){var y;for(y=0;yS&&(C=-1);Math.abs(S-y)>Hi;)y+=C*xa;return y},Gn=function(y){var S,C;Gn.prototype.init.call(this),this.type_=y||mc,this.push=function(A){if(A.type==="metadata"){this.trigger("data",A);return}this.type_!==mc&&A.type!==this.type_||(C===void 0&&(C=A.dts),A.dts=Ll(A.dts,C),A.pts=Ll(A.pts,C),S=A.dts,this.trigger("data",A))},this.flush=function(){C=S,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){C=void 0,S=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};Gn.prototype=new Do;var Gr={TimestampRolloverStream:Gn,handleRollover:Ll},Vm=(y,S,C)=>{if(!y)return-1;for(var A=C;A";y.data[0]===Il.Utf8&&(C=wo(y.data,0,S),!(C<0)&&(y.mimeType=ks(y.data,S,C),S=C+1,y.pictureType=y.data[S],S++,A=wo(y.data,0,S),!(A<0)&&(y.description=nr(y.data,S,A),S=A+1,y.mimeType===D?y.url=ks(y.data,S,y.data.length):y.pictureData=y.data.subarray(S,y.data.length))))},"T*":function(y){y.data[0]===Il.Utf8&&(y.value=nr(y.data,1,y.data.length).replace(/\0*$/,""),y.values=y.value.split("\0"))},TXXX:function(y){var S;y.data[0]===Il.Utf8&&(S=wo(y.data,0,1),S!==-1&&(y.description=nr(y.data,1,S),y.value=nr(y.data,S+1,y.data.length).replace(/\0*$/,""),y.data=y.value))},"W*":function(y){y.url=ks(y.data,0,y.data.length).replace(/\0.*$/,"")},WXXX:function(y){var S;y.data[0]===Il.Utf8&&(S=wo(y.data,0,1),S!==-1&&(y.description=nr(y.data,1,S),y.url=ks(y.data,S+1,y.data.length).replace(/\0.*$/,"")))},PRIV:function(y){var S;for(S=0;S>>2;Ze*=4,Ze+=Re[7]&3,pe.timeStamp=Ze,Z.pts===void 0&&Z.dts===void 0&&(Z.pts=pe.timeStamp,Z.dts=pe.timeStamp),this.trigger("timestamp",pe)}Z.frames.push(pe),J+=10,J+=ne}while(J>>4>1&&(W+=D[W]+1),P.pid===0)P.type="pat",y(D.subarray(W),P),this.trigger("data",P);else if(P.pid===this.pmtPid)for(P.type="pmt",y(D.subarray(W),P),this.trigger("data",P);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([D,W,P]):this.processPes_(D,W,P)},this.processPes_=function(D,P,W){W.pid===this.programMapTable.video?W.streamType=ns.H264_STREAM_TYPE:W.pid===this.programMapTable.audio?W.streamType=ns.ADTS_STREAM_TYPE:W.streamType=this.programMapTable["timed-metadata"][W.pid],W.type="pes",W.data=D.subarray(P),this.trigger("data",W)}},Dn.prototype=new Ol,Dn.STREAM_TYPES={h264:27,adts:15},Pl=function(){var y=this,S=!1,C={data:[],size:0},A={data:[],size:0},D={data:[],size:0},P,W=function(J,ne){var pe;const Le=J[0]<<16|J[1]<<8|J[2];ne.data=new Uint8Array,Le===1&&(ne.packetLength=6+(J[4]<<8|J[5]),ne.dataAlignmentIndicator=(J[6]&4)!==0,pe=J[7],pe&192&&(ne.pts=(J[9]&14)<<27|(J[10]&255)<<20|(J[11]&254)<<12|(J[12]&255)<<5|(J[13]&254)>>>3,ne.pts*=4,ne.pts+=(J[13]&6)>>>1,ne.dts=ne.pts,pe&64&&(ne.dts=(J[14]&14)<<27|(J[15]&255)<<20|(J[16]&254)<<12|(J[17]&255)<<5|(J[18]&254)>>>3,ne.dts*=4,ne.dts+=(J[18]&6)>>>1)),ne.data=J.subarray(9+J[8]))},Z=function(J,ne,pe){var Le=new Uint8Array(J.size),Ke={type:ne},Re=0,Ze=0,vt=!1,Ni;if(!(!J.data.length||J.size<9)){for(Ke.trackId=J.data[0].pid,Re=0;Re>5,J=((S[D+6]&3)+1)*1024,ne=J*Vn/Fl[(S[D+2]&60)>>>2],S.byteLength-D>>6&3)+1,channelcount:(S[D+2]&1)<<2|(S[D+3]&192)>>>6,samplerate:Fl[(S[D+2]&60)>>>2],samplingfrequencyindex:(S[D+2]&60)>>>2,samplesize:16,data:S.subarray(D+7+W,D+P)}),C++,D+=P}typeof pe=="number"&&(this.skipWarn_(pe,D),pe=null),S=S.subarray(D)}},this.flush=function(){C=0,this.trigger("done")},this.reset=function(){S=void 0,this.trigger("reset")},this.endTimeline=function(){S=void 0,this.trigger("endedtimeline")}},Ea.prototype=new Bl;var Aa=Ea,qr;qr=function(y){var S=y.byteLength,C=0,A=0;this.length=function(){return 8*S},this.bitsAvailable=function(){return 8*S+A},this.loadWord=function(){var D=y.byteLength-S,P=new Uint8Array(4),W=Math.min(4,S);if(W===0)throw new Error("no bytes available");P.set(y.subarray(D,D+W)),C=new DataView(P.buffer).getUint32(0),A=W*8,S-=W},this.skipBits=function(D){var P;A>D?(C<<=D,A-=D):(D-=A,P=Math.floor(D/8),D-=P*8,S-=P,this.loadWord(),C<<=D,A-=D)},this.readBits=function(D){var P=Math.min(A,D),W=C>>>32-P;return A-=P,A>0?C<<=P:S>0&&this.loadWord(),P=D-P,P>0?W<>>D)!==0)return C<<=D,A-=D,D;return this.loadWord(),D+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var D=this.skipLeadingZeros();return this.readBits(D+1)-1},this.readExpGolomb=function(){var D=this.readUnsignedExpGolomb();return 1&D?1+D>>>1:-1*(D>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var yh=qr,Ul=t,vh=yh,ar,Us,$l;Us=function(){var y=0,S,C;Us.prototype.init.call(this),this.push=function(A){var D;C?(D=new Uint8Array(C.byteLength+A.data.byteLength),D.set(C),D.set(A.data,C.byteLength),C=D):C=A.data;for(var P=C.byteLength;y3&&this.trigger("data",C.subarray(y+3)),C=null,y=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},Us.prototype=new Ul,$l={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},ar=function(){var y=new Us,S,C,A,D,P,W,Z;ar.prototype.init.call(this),S=this,this.push=function(J){J.type==="video"&&(C=J.trackId,A=J.pts,D=J.dts,y.push(J))},y.on("data",function(J){var ne={trackId:C,pts:A,dts:D,data:J,nalUnitTypeCode:J[0]&31};switch(ne.nalUnitTypeCode){case 5:ne.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:ne.nalUnitType="sei_rbsp",ne.escapedRBSP=P(J.subarray(1));break;case 7:ne.nalUnitType="seq_parameter_set_rbsp",ne.escapedRBSP=P(J.subarray(1)),ne.config=W(ne.escapedRBSP);break;case 8:ne.nalUnitType="pic_parameter_set_rbsp";break;case 9:ne.nalUnitType="access_unit_delimiter_rbsp";break}S.trigger("data",ne)}),y.on("done",function(){S.trigger("done")}),y.on("partialdone",function(){S.trigger("partialdone")}),y.on("reset",function(){S.trigger("reset")}),y.on("endedtimeline",function(){S.trigger("endedtimeline")}),this.flush=function(){y.flush()},this.partialFlush=function(){y.partialFlush()},this.reset=function(){y.reset()},this.endTimeline=function(){y.endTimeline()},Z=function(J,ne){var pe=8,Le=8,Ke,Re;for(Ke=0;Ke>4;return C=C>=0?C:0,D?C+20:C+10},Oo=function(y,S){return y.length-S<10||y[S]!==73||y[S+1]!==68||y[S+2]!==51?S:(S+=jl(y,S),Oo(y,S))},Th=function(y){var S=Oo(y,0);return y.length>=S+2&&(y[S]&255)===255&&(y[S+1]&240)===240&&(y[S+1]&22)===16},Po=function(y){return y[0]<<21|y[1]<<14|y[2]<<7|y[3]},Hl=function(y,S,C){var A,D="";for(A=S;A>5,A=y[S+4]<<3,D=y[S+3]&6144;return D|A|C},zr=function(y,S){return y[S]===73&&y[S+1]===68&&y[S+2]===51?"timed-metadata":y[S]&!0&&(y[S+1]&240)===240?"audio":null},Gl=function(y){for(var S=0;S+5>>2]}return null},Mo=function(y){var S,C,A,D;S=10,y[5]&64&&(S+=4,S+=Po(y.subarray(10,14)));do{if(C=Po(y.subarray(S+4,S+8)),C<1)return null;if(D=String.fromCharCode(y[S],y[S+1],y[S+2],y[S+3]),D==="PRIV"){A=y.subarray(S+10,S+C+10);for(var P=0;P>>2;return J*=4,J+=Z[7]&3,J}break}}S+=10,S+=C}while(S=3;){if(y[D]===73&&y[D+1]===68&&y[D+2]===51){if(y.length-D<10||(A=Vl.parseId3TagSize(y,D),D+A>y.length))break;W={type:"timed-metadata",data:y.subarray(D,D+A)},this.trigger("data",W),D+=A;continue}else if((y[D]&255)===255&&(y[D+1]&240)===240){if(y.length-D<7||(A=Vl.parseAdtsSize(y,D),D+A>y.length))break;Z={type:"audio",data:y.subarray(D,D+A),pts:S,dts:S},this.trigger("data",Z),D+=A;continue}D++}P=y.length-D,P>0?y=y.subarray(D):y=new Uint8Array},this.reset=function(){y=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){y=new Uint8Array,this.trigger("endedtimeline")}},lr.prototype=new Tc;var ql=lr,_h=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],Km=_h,Ym=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],Wm=Ym,Ca=t,No=Ee,Bo=ut,zl=ht,ln=re,qn=zm,Fo=$t,xh=Aa,Xm=Ro.H264Stream,Qm=ql,Zm=vc.isLikelyAacData,bc=$t.ONE_SECOND_IN_TS,Sh=Km,Eh=Wm,Kl,Da,Yl,Kr,Jm=function(y,S){S.stream=y,this.trigger("log",S)},Ah=function(y,S){for(var C=Object.keys(S),A=0;A=-1e4&&pe<=J&&(!Le||ne>pe)&&(Le=Re,ne=pe)));return Le?Le.gop:null},this.alignGopsAtStart_=function(Z){var J,ne,pe,Le,Ke,Re,Ze,vt;for(Ke=Z.byteLength,Re=Z.nalCount,Ze=Z.duration,J=ne=0;Jpe.pts){J++;continue}ne++,Ke-=Le.byteLength,Re-=Le.nalCount,Ze-=Le.duration}return ne===0?Z:ne===Z.length?null:(vt=Z.slice(ne),vt.byteLength=Ke,vt.duration=Ze,vt.nalCount=Re,vt.pts=vt[0].pts,vt.dts=vt[0].dts,vt)},this.alignGopsAtEnd_=function(Z){var J,ne,pe,Le,Ke,Re;for(J=D.length-1,ne=Z.length-1,Ke=null,Re=!1;J>=0&&ne>=0;){if(pe=D[J],Le=Z[ne],pe.pts===Le.pts){Re=!0;break}if(pe.pts>Le.pts){J--;continue}J===D.length-1&&(Ke=ne),ne--}if(!Re&&Ke===null)return null;var Ze;if(Re?Ze=ne:Ze=Ke,Ze===0)return Z;var vt=Z.slice(Ze),Ni=vt.reduce(function(Rs,gr){return Rs.byteLength+=gr.byteLength,Rs.duration+=gr.duration,Rs.nalCount+=gr.nalCount,Rs},{byteLength:0,duration:0,nalCount:0});return vt.byteLength=Ni.byteLength,vt.duration=Ni.duration,vt.nalCount=Ni.nalCount,vt.pts=vt[0].pts,vt.dts=vt[0].dts,vt},this.alignGopsWith=function(Z){D=Z}},Kl.prototype=new Ca,Kr=function(y,S){this.numberOfTracks=0,this.metadataStream=S,y=y||{},typeof y.remux<"u"?this.remuxTracks=!!y.remux:this.remuxTracks=!0,typeof y.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=y.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,Kr.prototype.init.call(this),this.push=function(C){if(C.content||C.text)return this.pendingCaptions.push(C);if(C.frames)return this.pendingMetadata.push(C);this.pendingTracks.push(C.track),this.pendingBytes+=C.boxes.byteLength,C.track.type==="video"&&(this.videoTrack=C.track,this.pendingBoxes.push(C.boxes)),C.track.type==="audio"&&(this.audioTrack=C.track,this.pendingBoxes.unshift(C.boxes))}},Kr.prototype=new Ca,Kr.prototype.flush=function(y){var S=0,C={captions:[],captionStreams:{},metadata:[],info:{}},A,D,P,W=0,Z;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(W=this.videoTrack.timelineStartInfo.pts,Eh.forEach(function(J){C.info[J]=this.videoTrack[J]},this)):this.audioTrack&&(W=this.audioTrack.timelineStartInfo.pts,Sh.forEach(function(J){C.info[J]=this.audioTrack[J]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?C.type=this.pendingTracks[0].type:C.type="combined",this.emittedTracks+=this.pendingTracks.length,P=No.initSegment(this.pendingTracks),C.initSegment=new Uint8Array(P.byteLength),C.initSegment.set(P),C.data=new Uint8Array(this.pendingBytes),Z=0;Z=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},Kr.prototype.setRemux=function(y){this.remuxTracks=y},Yl=function(y){var S=this,C=!0,A,D;Yl.prototype.init.call(this),y=y||{},this.baseMediaDecodeTime=y.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var P={};this.transmuxPipeline_=P,P.type="aac",P.metadataStream=new qn.MetadataStream,P.aacStream=new Qm,P.audioTimestampRolloverStream=new qn.TimestampRolloverStream("audio"),P.timedMetadataTimestampRolloverStream=new qn.TimestampRolloverStream("timed-metadata"),P.adtsStream=new xh,P.coalesceStream=new Kr(y,P.metadataStream),P.headOfPipeline=P.aacStream,P.aacStream.pipe(P.audioTimestampRolloverStream).pipe(P.adtsStream),P.aacStream.pipe(P.timedMetadataTimestampRolloverStream).pipe(P.metadataStream).pipe(P.coalesceStream),P.metadataStream.on("timestamp",function(W){P.aacStream.setTimestamp(W.timeStamp)}),P.aacStream.on("data",function(W){W.type!=="timed-metadata"&&W.type!=="audio"||P.audioSegmentStream||(D=D||{timelineStartInfo:{baseMediaDecodeTime:S.baseMediaDecodeTime},codec:"adts",type:"audio"},P.coalesceStream.numberOfTracks++,P.audioSegmentStream=new Da(D,y),P.audioSegmentStream.on("log",S.getLogTrigger_("audioSegmentStream")),P.audioSegmentStream.on("timingInfo",S.trigger.bind(S,"audioTimingInfo")),P.adtsStream.pipe(P.audioSegmentStream).pipe(P.coalesceStream),S.trigger("trackinfo",{hasAudio:!!D,hasVideo:!!A}))}),P.coalesceStream.on("data",this.trigger.bind(this,"data")),P.coalesceStream.on("done",this.trigger.bind(this,"done")),Ah(this,P)},this.setupTsPipeline=function(){var P={};this.transmuxPipeline_=P,P.type="ts",P.metadataStream=new qn.MetadataStream,P.packetStream=new qn.TransportPacketStream,P.parseStream=new qn.TransportParseStream,P.elementaryStream=new qn.ElementaryStream,P.timestampRolloverStream=new qn.TimestampRolloverStream,P.adtsStream=new xh,P.h264Stream=new Xm,P.captionStream=new qn.CaptionStream(y),P.coalesceStream=new Kr(y,P.metadataStream),P.headOfPipeline=P.packetStream,P.packetStream.pipe(P.parseStream).pipe(P.elementaryStream).pipe(P.timestampRolloverStream),P.timestampRolloverStream.pipe(P.h264Stream),P.timestampRolloverStream.pipe(P.adtsStream),P.timestampRolloverStream.pipe(P.metadataStream).pipe(P.coalesceStream),P.h264Stream.pipe(P.captionStream).pipe(P.coalesceStream),P.elementaryStream.on("data",function(W){var Z;if(W.type==="metadata"){for(Z=W.tracks.length;Z--;)!A&&W.tracks[Z].type==="video"?(A=W.tracks[Z],A.timelineStartInfo.baseMediaDecodeTime=S.baseMediaDecodeTime):!D&&W.tracks[Z].type==="audio"&&(D=W.tracks[Z],D.timelineStartInfo.baseMediaDecodeTime=S.baseMediaDecodeTime);A&&!P.videoSegmentStream&&(P.coalesceStream.numberOfTracks++,P.videoSegmentStream=new Kl(A,y),P.videoSegmentStream.on("log",S.getLogTrigger_("videoSegmentStream")),P.videoSegmentStream.on("timelineStartInfo",function(J){D&&!y.keepOriginalTimestamps&&(D.timelineStartInfo=J,P.audioSegmentStream.setEarliestDts(J.dts-S.baseMediaDecodeTime))}),P.videoSegmentStream.on("processedGopsInfo",S.trigger.bind(S,"gopInfo")),P.videoSegmentStream.on("segmentTimingInfo",S.trigger.bind(S,"videoSegmentTimingInfo")),P.videoSegmentStream.on("baseMediaDecodeTime",function(J){D&&P.audioSegmentStream.setVideoBaseMediaDecodeTime(J)}),P.videoSegmentStream.on("timingInfo",S.trigger.bind(S,"videoTimingInfo")),P.h264Stream.pipe(P.videoSegmentStream).pipe(P.coalesceStream)),D&&!P.audioSegmentStream&&(P.coalesceStream.numberOfTracks++,P.audioSegmentStream=new Da(D,y),P.audioSegmentStream.on("log",S.getLogTrigger_("audioSegmentStream")),P.audioSegmentStream.on("timingInfo",S.trigger.bind(S,"audioTimingInfo")),P.audioSegmentStream.on("segmentTimingInfo",S.trigger.bind(S,"audioSegmentTimingInfo")),P.adtsStream.pipe(P.audioSegmentStream).pipe(P.coalesceStream)),S.trigger("trackinfo",{hasAudio:!!D,hasVideo:!!A})}}),P.coalesceStream.on("data",this.trigger.bind(this,"data")),P.coalesceStream.on("id3Frame",function(W){W.dispatchType=P.metadataStream.dispatchType,S.trigger("id3Frame",W)}),P.coalesceStream.on("caption",this.trigger.bind(this,"caption")),P.coalesceStream.on("done",this.trigger.bind(this,"done")),Ah(this,P)},this.setBaseMediaDecodeTime=function(P){var W=this.transmuxPipeline_;y.keepOriginalTimestamps||(this.baseMediaDecodeTime=P),D&&(D.timelineStartInfo.dts=void 0,D.timelineStartInfo.pts=void 0,ln.clearDtsInfo(D),W.audioTimestampRolloverStream&&W.audioTimestampRolloverStream.discontinuity()),A&&(W.videoSegmentStream&&(W.videoSegmentStream.gopCache_=[]),A.timelineStartInfo.dts=void 0,A.timelineStartInfo.pts=void 0,ln.clearDtsInfo(A),W.captionStream.reset()),W.timestampRolloverStream&&W.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(P){D&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(P)},this.setRemux=function(P){var W=this.transmuxPipeline_;y.remux=P,W&&W.coalesceStream&&W.coalesceStream.setRemux(P)},this.alignGopsWith=function(P){A&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(P)},this.getLogTrigger_=function(P){var W=this;return function(Z){Z.stream=P,W.trigger("log",Z)}},this.push=function(P){if(C){var W=Zm(P);W&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!W&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),C=!1}this.transmuxPipeline_.headOfPipeline.push(P)},this.flush=function(){C=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}},Yl.prototype=new Ca;var eg={Transmuxer:Yl},tg=function(y){return y>>>0},ig=function(y){return("00"+y.toString(16)).slice(-2)},wa={toUnsigned:tg,toHexString:ig},Uo=function(y){var S="";return S+=String.fromCharCode(y[0]),S+=String.fromCharCode(y[1]),S+=String.fromCharCode(y[2]),S+=String.fromCharCode(y[3]),S},wh=Uo,Lh=wa.toUnsigned,Ih=wh,_c=function(y,S){var C=[],A,D,P,W,Z;if(!S.length)return null;for(A=0;A1?A+D:y.byteLength,P===S[0]&&(S.length===1?C.push(y.subarray(A+8,W)):(Z=_c(y.subarray(A+8,W),S.slice(1)),Z.length&&(C=C.concat(Z)))),A=W;return C},Wl=_c,kh=wa.toUnsigned,La=r.getUint64,sg=function(y){var S={version:y[0],flags:new Uint8Array(y.subarray(1,4))};return S.version===1?S.baseMediaDecodeTime=La(y.subarray(4)):S.baseMediaDecodeTime=kh(y[4]<<24|y[5]<<16|y[6]<<8|y[7]),S},xc=sg,ng=function(y){var S=new DataView(y.buffer,y.byteOffset,y.byteLength),C={version:y[0],flags:new Uint8Array(y.subarray(1,4)),trackId:S.getUint32(4)},A=C.flags[2]&1,D=C.flags[2]&2,P=C.flags[2]&8,W=C.flags[2]&16,Z=C.flags[2]&32,J=C.flags[0]&65536,ne=C.flags[0]&131072,pe;return pe=8,A&&(pe+=4,C.baseDataOffset=S.getUint32(12),pe+=4),D&&(C.sampleDescriptionIndex=S.getUint32(pe),pe+=4),P&&(C.defaultSampleDuration=S.getUint32(pe),pe+=4),W&&(C.defaultSampleSize=S.getUint32(pe),pe+=4),Z&&(C.defaultSampleFlags=S.getUint32(pe)),J&&(C.durationIsEmpty=!0),!A&&ne&&(C.baseDataOffsetIsMoof=!0),C},Sc=ng,Rh=function(y){return{isLeading:(y[0]&12)>>>2,dependsOn:y[0]&3,isDependedOn:(y[1]&192)>>>6,hasRedundancy:(y[1]&48)>>>4,paddingValue:(y[1]&14)>>>1,isNonSyncSample:y[1]&1,degradationPriority:y[2]<<8|y[3]}},$o=Rh,Ia=$o,rg=function(y){var S={version:y[0],flags:new Uint8Array(y.subarray(1,4)),samples:[]},C=new DataView(y.buffer,y.byteOffset,y.byteLength),A=S.flags[2]&1,D=S.flags[2]&4,P=S.flags[1]&1,W=S.flags[1]&2,Z=S.flags[1]&4,J=S.flags[1]&8,ne=C.getUint32(4),pe=8,Le;for(A&&(S.dataOffset=C.getInt32(pe),pe+=4),D&&ne&&(Le={flags:Ia(y.subarray(pe,pe+4))},pe+=4,P&&(Le.duration=C.getUint32(pe),pe+=4),W&&(Le.size=C.getUint32(pe),pe+=4),J&&(S.version===1?Le.compositionTimeOffset=C.getInt32(pe):Le.compositionTimeOffset=C.getUint32(pe),pe+=4),S.samples.push(Le),ne--);ne--;)Le={},P&&(Le.duration=C.getUint32(pe),pe+=4),W&&(Le.size=C.getUint32(pe),pe+=4),Z&&(Le.flags=Ia(y.subarray(pe,pe+4)),pe+=4),J&&(S.version===1?Le.compositionTimeOffset=C.getInt32(pe):Le.compositionTimeOffset=C.getUint32(pe),pe+=4),S.samples.push(Le);return S},jo=rg,Ec={tfdt:xc,trun:jo},Ac={parseTfdt:Ec.tfdt,parseTrun:Ec.trun},Cc=function(y){for(var S=0,C=String.fromCharCode(y[S]),A="";C!=="\0";)A+=C,S++,C=String.fromCharCode(y[S]);return A+=C,A},Dc={uint8ToCString:Cc},Ho=Dc.uint8ToCString,Oh=r.getUint64,Ph=function(y){var S=4,C=y[0],A,D,P,W,Z,J,ne,pe;if(C===0){A=Ho(y.subarray(S)),S+=A.length,D=Ho(y.subarray(S)),S+=D.length;var Le=new DataView(y.buffer);P=Le.getUint32(S),S+=4,Z=Le.getUint32(S),S+=4,J=Le.getUint32(S),S+=4,ne=Le.getUint32(S),S+=4}else if(C===1){var Le=new DataView(y.buffer);P=Le.getUint32(S),S+=4,W=Oh(y.subarray(S)),S+=8,J=Le.getUint32(S),S+=4,ne=Le.getUint32(S),S+=4,A=Ho(y.subarray(S)),S+=A.length,D=Ho(y.subarray(S)),S+=D.length}pe=new Uint8Array(y.subarray(S,y.byteLength));var Ke={scheme_id_uri:A,value:D,timescale:P||1,presentation_time:W,presentation_time_delta:Z,event_duration:J,id:ne,message_data:pe};return og(C,Ke)?Ke:void 0},ag=function(y,S,C,A){return y||y===0?y/S:A+C/S},og=function(y,S){var C=S.scheme_id_uri!=="\0",A=y===0&&Mh(S.presentation_time_delta)&&C,D=y===1&&Mh(S.presentation_time)&&C;return!(y>1)&&A||D},Mh=function(y){return y!==void 0||y!==null},lg={parseEmsgBox:Ph,scaleTime:ag},Go;typeof window<"u"?Go=window:typeof s<"u"?Go=s:typeof self<"u"?Go=self:Go={};var xs=Go,ur=wa.toUnsigned,ka=wa.toHexString,pi=Wl,Yr=wh,Xl=lg,wc=Sc,ug=jo,Ra=xc,Lc=r.getUint64,Oa,Ql,Ic,cr,Wr,Vo,kc,zn=xs,Nh=kl.parseId3Frames;Oa=function(y){var S={},C=pi(y,["moov","trak"]);return C.reduce(function(A,D){var P,W,Z,J,ne;return P=pi(D,["tkhd"])[0],!P||(W=P[0],Z=W===0?12:20,J=ur(P[Z]<<24|P[Z+1]<<16|P[Z+2]<<8|P[Z+3]),ne=pi(D,["mdia","mdhd"])[0],!ne)?null:(W=ne[0],Z=W===0?12:20,A[J]=ur(ne[Z]<<24|ne[Z+1]<<16|ne[Z+2]<<8|ne[Z+3]),A)},S)},Ql=function(y,S){var C;C=pi(S,["moof","traf"]);var A=C.reduce(function(D,P){var W=pi(P,["tfhd"])[0],Z=ur(W[4]<<24|W[5]<<16|W[6]<<8|W[7]),J=y[Z]||9e4,ne=pi(P,["tfdt"])[0],pe=new DataView(ne.buffer,ne.byteOffset,ne.byteLength),Le;ne[0]===1?Le=Lc(ne.subarray(4,12)):Le=pe.getUint32(4);let Ke;return typeof Le=="bigint"?Ke=Le/zn.BigInt(J):typeof Le=="number"&&!isNaN(Le)&&(Ke=Le/J),Ke11?(D.codec+=".",D.codec+=ka(Re[9]),D.codec+=ka(Re[10]),D.codec+=ka(Re[11])):D.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(D.codec)?(Re=Ke.subarray(28),Ze=Yr(Re.subarray(4,8)),Ze==="esds"&&Re.length>20&&Re[19]!==0?(D.codec+="."+ka(Re[19]),D.codec+="."+ka(Re[20]>>>2&63).replace(/^0/,"")):D.codec="mp4a.40.2"):D.codec=D.codec.toLowerCase())}var vt=pi(A,["mdia","mdhd"])[0];vt&&(D.timescale=Vo(vt)),C.push(D)}),C},kc=function(y,S=0){var C=pi(y,["emsg"]);return C.map(A=>{var D=Xl.parseEmsgBox(new Uint8Array(A)),P=Nh(D.message_data);return{cueTime:Xl.scaleTime(D.presentation_time,D.timescale,D.presentation_time_delta,S),duration:Xl.scaleTime(D.event_duration,D.timescale),frames:P}})};var Pa={findBox:pi,parseType:Yr,timescale:Oa,startTime:Ql,compositionStartTime:Ic,videoTrackIds:cr,tracks:Wr,getTimescaleFromMediaHeader:Vo,getEmsgID3:kc};const{parseTrun:Bh}=Ac,{findBox:Fh}=Pa;var Uh=xs,cg=function(y){var S=Fh(y,["moof","traf"]),C=Fh(y,["mdat"]),A=[];return C.forEach(function(D,P){var W=S[P];A.push({mdat:D,traf:W})}),A},$h=function(y,S,C){var A=S,D=C.defaultSampleDuration||0,P=C.defaultSampleSize||0,W=C.trackId,Z=[];return y.forEach(function(J){var ne=Bh(J),pe=ne.samples;pe.forEach(function(Le){Le.duration===void 0&&(Le.duration=D),Le.size===void 0&&(Le.size=P),Le.trackId=W,Le.dts=A,Le.compositionTimeOffset===void 0&&(Le.compositionTimeOffset=0),typeof A=="bigint"?(Le.pts=A+Uh.BigInt(Le.compositionTimeOffset),A+=Uh.BigInt(Le.duration)):(Le.pts=A+Le.compositionTimeOffset,A+=Le.duration)}),Z=Z.concat(pe)}),Z},Rc={getMdatTrafPairs:cg,parseSamples:$h},Oc=ji.discardEmulationPreventionBytes,un=Hr.CaptionStream,Ma=Wl,$s=xc,Na=Sc,{getMdatTrafPairs:Pc,parseSamples:Zl}=Rc,Jl=function(y,S){for(var C=y,A=0;A0?$s(pe[0]).baseMediaDecodeTime:0,Ke=Ma(W,["trun"]),Re,Ze;S===ne&&Ke.length>0&&(Re=Zl(Ke,Le,J),Ze=Mc(P,Re,ne),C[ne]||(C[ne]={seiNals:[],logs:[]}),C[ne].seiNals=C[ne].seiNals.concat(Ze.seiNals),C[ne].logs=C[ne].logs.concat(Ze.logs))}),C},jh=function(y,S,C){var A;if(S===null)return null;A=Xr(y,S);var D=A[S]||{};return{seiNals:D.seiNals,logs:D.logs,timescale:C}},eu=function(){var y=!1,S,C,A,D,P,W;this.isInitialized=function(){return y},this.init=function(Z){S=new un,y=!0,W=Z?Z.isPartial:!1,S.on("data",function(J){J.startTime=J.startPts/D,J.endTime=J.endPts/D,P.captions.push(J),P.captionStreams[J.stream]=!0}),S.on("log",function(J){P.logs.push(J)})},this.isNewInit=function(Z,J){return Z&&Z.length===0||J&&typeof J=="object"&&Object.keys(J).length===0?!1:A!==Z[0]||D!==J[A]},this.parse=function(Z,J,ne){var pe;if(this.isInitialized()){if(!J||!ne)return null;if(this.isNewInit(J,ne))A=J[0],D=ne[A];else if(A===null||!D)return C.push(Z),null}else return null;for(;C.length>0;){var Le=C.shift();this.parse(Le,J,ne)}return pe=jh(Z,A,D),pe&&pe.logs&&(P.logs=P.logs.concat(pe.logs)),pe===null||!pe.seiNals?P.logs.length?{logs:P.logs,captions:[],captionStreams:[]}:null:(this.pushNals(pe.seiNals),this.flushStream(),P)},this.pushNals=function(Z){if(!this.isInitialized()||!Z||Z.length===0)return null;Z.forEach(function(J){S.push(J)})},this.flushStream=function(){if(!this.isInitialized())return null;W?S.partialFlush():S.flush()},this.clearParsedCaptions=function(){P.captions=[],P.captionStreams={},P.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;S.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){C=[],A=null,D=null,P?this.clearParsedCaptions():P={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},Ba=eu;const{parseTfdt:dg}=Ac,Di=Wl,{getTimescaleFromMediaHeader:Nc}=Pa,{parseSamples:Kn,getMdatTrafPairs:Hh}=Rc;var dr=function(){let y=9e4;this.init=function(S){const C=Di(S,["moov","trak","mdia","mdhd"])[0];C&&(y=Nc(C))},this.parseSegment=function(S){const C=[],A=Hh(S);let D=0;return A.forEach(function(P){const W=P.mdat,Z=P.traf,J=Di(Z,["tfdt"])[0],ne=Di(Z,["tfhd"])[0],pe=Di(Z,["trun"]);if(J&&(D=dg(J).baseMediaDecodeTime),pe.length&&ne){const Le=Kn(pe,D,ne);let Ke=0;Le.forEach(function(Re){const Ze="utf-8",vt=new TextDecoder(Ze),Ni=W.slice(Ke,Ke+Re.size);if(Di(Ni,["vtte"])[0]){Ke+=Re.size;return}Di(Ni,["vttc"]).forEach(function(Yo){const ci=Di(Yo,["payl"])[0],Qr=Di(Yo,["sttg"])[0],Yn=Re.pts/y,yr=(Re.pts+Re.duration)/y;let Yt,wn;if(ci)try{Yt=vt.decode(ci)}catch(rs){console.error(rs)}if(Qr)try{wn=vt.decode(Qr)}catch(rs){console.error(rs)}Re.duration&&Yt&&C.push({cueText:Yt,start:Yn,end:yr,settings:wn})}),Ke+=Re.size})}}),C}},qo=Hn,Fc=function(y){var S=y[1]&31;return S<<=8,S|=y[2],S},Fa=function(y){return!!(y[1]&64)},zo=function(y){var S=0;return(y[3]&48)>>>4>1&&(S+=y[4]+1),S},js=function(y,S){var C=Fc(y);return C===0?"pat":C===S?"pmt":S?"pes":null},Ua=function(y){var S=Fa(y),C=4+zo(y);return S&&(C+=y[C]+1),(y[C+10]&31)<<8|y[C+11]},$a=function(y){var S={},C=Fa(y),A=4+zo(y);if(C&&(A+=y[A]+1),!!(y[A+5]&1)){var D,P,W;D=(y[A+1]&15)<<8|y[A+2],P=3+D-4,W=(y[A+10]&15)<<8|y[A+11];for(var Z=12+W;Z=y.byteLength)return null;var A=null,D;return D=y[C+7],D&192&&(A={},A.pts=(y[C+9]&14)<<27|(y[C+10]&255)<<20|(y[C+11]&254)<<12|(y[C+12]&255)<<5|(y[C+13]&254)>>>3,A.pts*=4,A.pts+=(y[C+13]&6)>>>1,A.dts=A.pts,D&64&&(A.dts=(y[C+14]&14)<<27|(y[C+15]&255)<<20|(y[C+16]&254)<<12|(y[C+17]&255)<<5|(y[C+18]&254)>>>3,A.dts*=4,A.dts+=(y[C+18]&6)>>>1)),A},Ss=function(y){switch(y){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},Hs=function(y){for(var S=4+zo(y),C=y.subarray(S),A=0,D=0,P=!1,W;D3&&(W=Ss(C[D+3]&31),W==="slice_layer_without_partitioning_rbsp_idr"&&(P=!0)),P},hr={parseType:js,parsePat:Ua,parsePmt:$a,parsePayloadUnitStartIndicator:Fa,parsePesType:tu,parsePesTime:Ko,videoPacketContainsKeyFrame:Hs},cn=Hn,ps=Gr.handleRollover,Lt={};Lt.ts=hr,Lt.aac=vc;var fr=$t.ONE_SECOND_IN_TS,Xi=188,Gs=71,Gh=function(y,S){for(var C=0,A=Xi,D,P;A=0;){if(y[A]===Gs&&(y[D]===Gs||D===y.byteLength)){if(P=y.subarray(A,D),W=Lt.ts.parseType(P,S.pid),W==="pes"&&(Z=Lt.ts.parsePesType(P,S.table),J=Lt.ts.parsePayloadUnitStartIndicator(P),Z==="audio"&&J&&(ne=Lt.ts.parsePesTime(P),ne&&(ne.type="audio",C.audio.push(ne),pe=!0))),pe)break;A-=Xi,D-=Xi;continue}A--,D--}},ri=function(y,S,C){for(var A=0,D=Xi,P,W,Z,J,ne,pe,Le,Ke,Re=!1,Ze={data:[],size:0};D=0;){if(y[A]===Gs&&y[D]===Gs){if(P=y.subarray(A,D),W=Lt.ts.parseType(P,S.pid),W==="pes"&&(Z=Lt.ts.parsePesType(P,S.table),J=Lt.ts.parsePayloadUnitStartIndicator(P),Z==="video"&&J&&(ne=Lt.ts.parsePesTime(P),ne&&(ne.type="video",C.video.push(ne),Re=!0))),Re)break;A-=Xi,D-=Xi;continue}A--,D--}},Pt=function(y,S){if(y.audio&&y.audio.length){var C=S;(typeof C>"u"||isNaN(C))&&(C=y.audio[0].dts),y.audio.forEach(function(P){P.dts=ps(P.dts,C),P.pts=ps(P.pts,C),P.dtsTime=P.dts/fr,P.ptsTime=P.pts/fr})}if(y.video&&y.video.length){var A=S;if((typeof A>"u"||isNaN(A))&&(A=y.video[0].dts),y.video.forEach(function(P){P.dts=ps(P.dts,A),P.pts=ps(P.pts,A),P.dtsTime=P.dts/fr,P.ptsTime=P.pts/fr}),y.firstKeyFrame){var D=y.firstKeyFrame;D.dts=ps(D.dts,A),D.pts=ps(D.pts,A),D.dtsTime=D.dts/fr,D.ptsTime=D.pts/fr}}},pr=function(y){for(var S=!1,C=0,A=null,D=null,P=0,W=0,Z;y.length-W>=3;){var J=Lt.aac.parseType(y,W);switch(J){case"timed-metadata":if(y.length-W<10){S=!0;break}if(P=Lt.aac.parseId3TagSize(y,W),P>y.length){S=!0;break}D===null&&(Z=y.subarray(W,W+P),D=Lt.aac.parseAacTimestamp(Z)),W+=P;break;case"audio":if(y.length-W<7){S=!0;break}if(P=Lt.aac.parseAdtsSize(y,W),P>y.length){S=!0;break}A===null&&(Z=y.subarray(W,W+P),A=Lt.aac.parseSampleRate(Z)),C++,W+=P;break;default:W++;break}if(S)return null}if(A===null||D===null)return null;var ne=fr/A,pe={audio:[{type:"audio",dts:D,pts:D},{type:"audio",dts:D+C*1024*ne,pts:D+C*1024*ne}]};return pe},Vs=function(y){var S={pid:null,table:null},C={};Gh(y,S);for(var A in S.table)if(S.table.hasOwnProperty(A)){var D=S.table[A];switch(D){case cn.H264_STREAM_TYPE:C.video=[],ri(y,S,C),C.video.length===0&&delete C.video;break;case cn.ADTS_STREAM_TYPE:C.audio=[],Gi(y,S,C),C.audio.length===0&&delete C.audio;break}}return C},Uc=function(y,S){var C=Lt.aac.isLikelyAacData(y),A;return C?A=pr(y):A=Vs(y),!A||!A.audio&&!A.video?null:(Pt(A,S),A)},mr={inspect:Uc,parseAudioPes_:Gi};const Vh=function(y,S){S.on("data",function(C){const A=C.initSegment;C.initSegment={data:A.buffer,byteOffset:A.byteOffset,byteLength:A.byteLength};const D=C.data;C.data=D.buffer,y.postMessage({action:"data",segment:C,byteOffset:D.byteOffset,byteLength:D.byteLength},[C.data])}),S.on("done",function(C){y.postMessage({action:"done"})}),S.on("gopInfo",function(C){y.postMessage({action:"gopInfo",gopInfo:C})}),S.on("videoSegmentTimingInfo",function(C){const A={start:{decode:$t.videoTsToSeconds(C.start.dts),presentation:$t.videoTsToSeconds(C.start.pts)},end:{decode:$t.videoTsToSeconds(C.end.dts),presentation:$t.videoTsToSeconds(C.end.pts)},baseMediaDecodeTime:$t.videoTsToSeconds(C.baseMediaDecodeTime)};C.prependedContentDuration&&(A.prependedContentDuration=$t.videoTsToSeconds(C.prependedContentDuration)),y.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:A})}),S.on("audioSegmentTimingInfo",function(C){const A={start:{decode:$t.videoTsToSeconds(C.start.dts),presentation:$t.videoTsToSeconds(C.start.pts)},end:{decode:$t.videoTsToSeconds(C.end.dts),presentation:$t.videoTsToSeconds(C.end.pts)},baseMediaDecodeTime:$t.videoTsToSeconds(C.baseMediaDecodeTime)};C.prependedContentDuration&&(A.prependedContentDuration=$t.videoTsToSeconds(C.prependedContentDuration)),y.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:A})}),S.on("id3Frame",function(C){y.postMessage({action:"id3Frame",id3Frame:C})}),S.on("caption",function(C){y.postMessage({action:"caption",caption:C})}),S.on("trackinfo",function(C){y.postMessage({action:"trackinfo",trackInfo:C})}),S.on("audioTimingInfo",function(C){y.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:$t.videoTsToSeconds(C.start),end:$t.videoTsToSeconds(C.end)}})}),S.on("videoTimingInfo",function(C){y.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:$t.videoTsToSeconds(C.start),end:$t.videoTsToSeconds(C.end)}})}),S.on("log",function(C){y.postMessage({action:"log",log:C})})};class $c{constructor(S,C){this.options=C||{},this.self=S,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new eg.Transmuxer(this.options),Vh(this.self,this.transmuxer)}pushMp4Captions(S){this.captionParser||(this.captionParser=new Ba,this.captionParser.init());const C=new Uint8Array(S.data,S.byteOffset,S.byteLength),A=this.captionParser.parse(C,S.trackIds,S.timescales);this.self.postMessage({action:"mp4Captions",captions:A&&A.captions||[],logs:A&&A.logs||[],data:C.buffer},[C.buffer])}initMp4WebVttParser(S){this.webVttParser||(this.webVttParser=new dr);const C=new Uint8Array(S.data,S.byteOffset,S.byteLength);this.webVttParser.init(C)}getMp4WebVttText(S){this.webVttParser||(this.webVttParser=new dr);const C=new Uint8Array(S.data,S.byteOffset,S.byteLength),A=this.webVttParser.parseSegment(C);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:A||[],data:C.buffer},[C.buffer])}probeMp4StartTime({timescales:S,data:C}){const A=Pa.startTime(S,C);this.self.postMessage({action:"probeMp4StartTime",startTime:A,data:C},[C.buffer])}probeMp4Tracks({data:S}){const C=Pa.tracks(S);this.self.postMessage({action:"probeMp4Tracks",tracks:C,data:S},[S.buffer])}probeEmsgID3({data:S,offset:C}){const A=Pa.getEmsgID3(S,C);this.self.postMessage({action:"probeEmsgID3",id3Frames:A,emsgData:S},[S.buffer])}probeTs({data:S,baseStartTime:C}){const A=typeof C=="number"&&!isNaN(C)?C*$t.ONE_SECOND_IN_TS:void 0,D=mr.inspect(S,A);let P=null;D&&(P={hasVideo:D.video&&D.video.length===2||!1,hasAudio:D.audio&&D.audio.length===2||!1},P.hasVideo&&(P.videoStart=D.video[0].ptsTime),P.hasAudio&&(P.audioStart=D.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:P,data:S},[S.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(S){const C=new Uint8Array(S.data,S.byteOffset,S.byteLength);this.transmuxer.push(C)}reset(){this.transmuxer.reset()}setTimestampOffset(S){const C=S.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round($t.secondsToVideoTs(C)))}setAudioAppendStart(S){this.transmuxer.setAudioAppendStart(Math.ceil($t.secondsToVideoTs(S.appendStart)))}setRemux(S){this.transmuxer.setRemux(S.remux)}flush(S){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(S){this.transmuxer.alignGopsWith(S.gopsToAlignWith.slice())}}self.onmessage=function(y){if(y.data.action==="init"&&y.data.options){this.messageHandlers=new $c(self,y.data.options);return}this.messageHandlers||(this.messageHandlers=new $c(self)),y.data&&y.data.action&&y.data.action!=="init"&&this.messageHandlers[y.data.action]&&this.messageHandlers[y.data.action](y.data)}}));var P5=HD(O5);const M5=(s,e,t)=>{const{type:i,initSegment:n,captions:r,captionStreams:o,metadata:u,videoFrameDtsTime:c,videoFramePtsTime:d}=s.data.segment;e.buffer.push({captions:r,captionStreams:o,metadata:u});const f=s.data.segment.boxes||{data:s.data.segment.data},m={type:i,data:new Uint8Array(f.data,f.data.byteOffset,f.data.byteLength),initSegment:new Uint8Array(n.data,n.byteOffset,n.byteLength)};typeof c<"u"&&(m.videoFrameDtsTime=c),typeof d<"u"&&(m.videoFramePtsTime=d),t(m)},N5=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},B5=(s,e)=>{e.gopInfo=s.data.gopInfo},qD=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:n,remux:r,onData:o,onTrackInfo:u,onAudioTimingInfo:c,onVideoTimingInfo:d,onVideoSegmentTimingInfo:f,onAudioSegmentTimingInfo:m,onId3:g,onCaptions:v,onDone:b,onEndedTimeline:_,onTransmuxerLog:E,isEndOfTimeline:L,segment:I,triggerSegmentEventFn:w}=s,F={buffer:[]};let U=L;const V=q=>{e.currentTransmux===s&&(q.data.action==="data"&&M5(q,F,o),q.data.action==="trackinfo"&&u(q.data.trackInfo),q.data.action==="gopInfo"&&B5(q,F),q.data.action==="audioTimingInfo"&&c(q.data.audioTimingInfo),q.data.action==="videoTimingInfo"&&d(q.data.videoTimingInfo),q.data.action==="videoSegmentTimingInfo"&&f(q.data.videoSegmentTimingInfo),q.data.action==="audioSegmentTimingInfo"&&m(q.data.audioSegmentTimingInfo),q.data.action==="id3Frame"&&g([q.data.id3Frame],q.data.id3Frame.dispatchType),q.data.action==="caption"&&v(q.data.caption),q.data.action==="endedtimeline"&&(U=!1,_()),q.data.action==="log"&&E(q.data.log),q.data.type==="transmuxed"&&(U||(e.onmessage=null,N5({transmuxedData:F,callback:b}),zD(e))))},B=()=>{const q={message:"Received an error message from the transmuxer worker",metadata:{errorType:Te.Error.StreamingFailedToTransmuxSegment,segmentInfo:fl({segment:I})}};b(null,q)};if(e.onmessage=V,e.onerror=B,i&&e.postMessage({action:"setAudioAppendStart",appendStart:i}),Array.isArray(n)&&e.postMessage({action:"alignGopsWith",gopsToAlignWith:n}),typeof r<"u"&&e.postMessage({action:"setRemux",remux:r}),t.byteLength){const q=t instanceof ArrayBuffer?t:t.buffer,k=t instanceof ArrayBuffer?0:t.byteOffset;w({type:"segmenttransmuxingstart",segment:I}),e.postMessage({action:"push",data:q,byteOffset:k,byteLength:t.byteLength},[q])}L&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},zD=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():qD(s.currentTransmux))},a1=(s,e)=>{s.postMessage({action:e}),zD(s)},KD=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,a1(e,s);return}e.transmuxQueue.push(a1.bind(null,e,s))},F5=s=>{KD("reset",s)},U5=s=>{KD("endTimeline",s)},YD=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,qD(s);return}s.transmuxer.transmuxQueue.push(s)},$5=s=>{const e=new P5;e.currentTransmux=null,e.transmuxQueue=[];const t=e.terminate;return e.terminate=()=>(e.currentTransmux=null,e.transmuxQueue.length=0,t.call(e)),e.postMessage({action:"init",options:s}),e};var Ry={reset:F5,endTimeline:U5,transmux:YD,createTransmuxer:$5};const Hu=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,n=$i({},s,{endAction:null,transmuxer:null,callback:null}),r=o=>{o.data.action===t&&(e.removeEventListener("message",r),o.data.data&&(o.data.data=new Uint8Array(o.data.data,s.byteOffset||0,s.byteLength||o.data.data.byteLength),s.data&&(s.data=o.data.data)),i(o.data))};if(e.addEventListener("message",r),s.data){const o=s.data instanceof ArrayBuffer;n.byteOffset=o?0:s.data.byteOffset,n.byteLength=s.data.byteLength;const u=[o?s.data:s.data.buffer];e.postMessage(n,u)}else e.postMessage(n)},kr={FAILURE:2,TIMEOUT:-101,ABORTED:-102},WD="wvtt",Bv=s=>{s.forEach(e=>{e.abort()})},j5=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),H5=s=>{const e=s.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-e.requestTime||0};return i.bytesReceived=s.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8*1e3),i},XT=(s,e)=>{const{requestType:t}=e,i=_l({requestType:t,request:e,error:s});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:kr.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:kr.ABORTED,xhr:e,metadata:i}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:kr.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:kr.FAILURE,xhr:e,metadata:i}:null},o1=(s,e,t,i)=>(n,r)=>{const o=r.response,u=XT(n,r);if(u)return t(u,s);if(o.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:kr.FAILURE,xhr:r},s);const c=new DataView(o),d=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let m=0;m{e===WD&&s.transmuxer.postMessage({action:"initMp4WebVttParser",data:s.map.bytes})},V5=(s,e,t)=>{e===WD&&Hu({action:"getMp4WebVttText",data:s.bytes,transmuxer:s.transmuxer,callback:({data:i,mp4VttCues:n})=>{s.bytes=i,t(null,s,{mp4VttCues:n})}})},XD=(s,e)=>{const t=TT(s.map.bytes);if(t!=="mp4"){const i=s.map.resolvedUri||s.map.uri,n=t||"unknown";return e({internal:!0,message:`Found unsupported ${n} container for initialization segment at URL: ${i}`,code:kr.FAILURE,metadata:{mediaType:n}})}Hu({action:"probeMp4Tracks",data:s.map.bytes,transmuxer:s.transmuxer,callback:({tracks:i,data:n})=>(s.map.bytes=n,i.forEach(function(r){s.map.tracks=s.map.tracks||{},!s.map.tracks[r.type]&&(s.map.tracks[r.type]=r,typeof r.id=="number"&&r.timescale&&(s.map.timescales=s.map.timescales||{},s.map.timescales[r.id]=r.timescale),r.type==="text"&&G5(s,r.codec))}),e(null))})},q5=({segment:s,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,n)=>{const r=XT(i,n);if(r)return e(r,s);const o=new Uint8Array(n.response);if(t({type:"segmentloaded",segment:s}),s.map.key)return s.map.encryptedBytes=o,e(null,s);s.map.bytes=o,XD(s,function(u){if(u)return u.xhr=n,u.status=n.status,e(u,s);e(null,s)})},z5=({segment:s,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(n,r)=>{const o=XT(n,r);if(o)return e(o,s);i({type:"segmentloaded",segment:s});const u=t==="arraybuffer"||!r.responseText?r.response:k5(r.responseText.substring(s.lastReachedChar||0));return s.stats=j5(r),s.key?s.encryptedBytes=new Uint8Array(u):s.bytes=new Uint8Array(u),e(null,s)},K5=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:m,onTransmuxerLog:g,triggerSegmentEventFn:v})=>{const b=s.map&&s.map.tracks||{},_=!!(b.audio&&b.video);let E=i.bind(null,s,"audio","start");const L=i.bind(null,s,"audio","end");let I=i.bind(null,s,"video","start");const w=i.bind(null,s,"video","end"),F=()=>YD({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:_,onData:U=>{U.type=U.type==="combined"?"video":U.type,f(s,U)},onTrackInfo:U=>{t&&(_&&(U.isMuxed=!0),t(s,U))},onAudioTimingInfo:U=>{E&&typeof U.start<"u"&&(E(U.start),E=null),L&&typeof U.end<"u"&&L(U.end)},onVideoTimingInfo:U=>{I&&typeof U.start<"u"&&(I(U.start),I=null),w&&typeof U.end<"u"&&w(U.end)},onVideoSegmentTimingInfo:U=>{const V={pts:{start:U.start.presentation,end:U.end.presentation},dts:{start:U.start.decode,end:U.end.decode}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:V}),n(U)},onAudioSegmentTimingInfo:U=>{const V={pts:{start:U.start.pts,end:U.end.pts},dts:{start:U.start.dts,end:U.end.dts}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:V}),r(U)},onId3:(U,V)=>{o(s,U,V)},onCaptions:U=>{u(s,[U])},isEndOfTimeline:c,onEndedTimeline:()=>{d()},onTransmuxerLog:g,onDone:(U,V)=>{m&&(U.type=U.type==="combined"?"video":U.type,v({type:"segmenttransmuxingcomplete",segment:s}),m(V,s,U))},segment:s,triggerSegmentEventFn:v});Hu({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:U=>{s.bytes=e=U.data;const V=U.result;V&&(t(s,{hasAudio:V.hasAudio,hasVideo:V.hasVideo,isMuxed:_}),t=null),F()}})},QD=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:m,onTransmuxerLog:g,triggerSegmentEventFn:v})=>{let b=new Uint8Array(e);if(pN(b)){s.isFmp4=!0;const{tracks:_}=s.map;if(_.text&&(!_.audio||!_.video)){f(s,{data:b,type:"text"}),V5(s,_.text.codec,m);return}const L={isFmp4:!0,hasVideo:!!_.video,hasAudio:!!_.audio};_.audio&&_.audio.codec&&_.audio.codec!=="enca"&&(L.audioCodec=_.audio.codec),_.video&&_.video.codec&&_.video.codec!=="encv"&&(L.videoCodec=_.video.codec),_.video&&_.audio&&(L.isMuxed=!0),t(s,L);const I=(w,F)=>{f(s,{data:b,type:L.hasAudio&&!L.isMuxed?"audio":"video"}),F&&F.length&&o(s,F),w&&w.length&&u(s,w),m(null,s,{})};Hu({action:"probeMp4StartTime",timescales:s.map.timescales,data:b,transmuxer:s.transmuxer,callback:({data:w,startTime:F})=>{e=w.buffer,s.bytes=b=w,L.hasAudio&&!L.isMuxed&&i(s,"audio","start",F),L.hasVideo&&i(s,"video","start",F),Hu({action:"probeEmsgID3",data:b,transmuxer:s.transmuxer,offset:F,callback:({emsgData:U,id3Frames:V})=>{if(e=U.buffer,s.bytes=b=U,!_.video||!U.byteLength||!s.transmuxer){I(void 0,V);return}Hu({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:b,timescales:s.map.timescales,trackIds:[_.video.id],callback:B=>{e=B.data.buffer,s.bytes=b=B.data,B.logs.forEach(function(q){g(Kt(q,{stream:"mp4CaptionParser"}))}),I(B.captions,V)}})}})}});return}if(!s.transmuxer){m(null,s,{});return}if(typeof s.container>"u"&&(s.container=TT(b)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),m(null,s,{});return}K5({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:m,onTransmuxerLog:g,triggerSegmentEventFn:v})},ZD=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i,segment:n,doneFn:r},o){const u=d=>{if(d.data.source===s){i.removeEventListener("message",u);const f=d.data.decrypted;o(new Uint8Array(f.bytes,f.byteOffset,f.byteLength))}};i.onerror=()=>{const d="An error occurred in the decryption worker",f=fl({segment:n}),m={message:d,metadata:{error:new Error(d),errorType:Te.Error.StreamingFailedToDecryptSegment,segmentInfo:f,keyInfo:{uri:n.key.resolvedUri||n.map.key.resolvedUri}}};r(m,n)},i.addEventListener("message",u);let c;e.bytes.slice?c=e.bytes.slice():c=new Uint32Array(Array.prototype.slice.call(e.bytes)),i.postMessage(ND({source:s,encrypted:t,key:c,iv:e.iv}),[t.buffer,c.buffer])},Y5=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:m,onTransmuxerLog:g,triggerSegmentEventFn:v})=>{v({type:"segmentdecryptionstart"}),ZD({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s,segment:e,doneFn:m},b=>{e.bytes=b,v({type:"segmentdecryptioncomplete",segment:e}),QD({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:m,onTransmuxerLog:g,triggerSegmentEventFn:v})})},W5=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:m,onTransmuxerLog:g,triggerSegmentEventFn:v})=>{let b=0,_=!1;return(E,L)=>{if(!_){if(E)return _=!0,Bv(s),m(E,L);if(b+=1,b===s.length){const I=function(){if(L.encryptedBytes)return Y5({decryptionWorker:e,segment:L,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:m,onTransmuxerLog:g,triggerSegmentEventFn:v});QD({segment:L,bytes:L.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:m,onTransmuxerLog:g,triggerSegmentEventFn:v})};if(L.endOfAllRequests=Date.now(),L.map&&L.map.encryptedBytes&&!L.map.bytes)return v({type:"segmentdecryptionstart",segment:L}),ZD({decryptionWorker:e,id:L.requestId+"-init",encryptedBytes:L.map.encryptedBytes,key:L.map.key,segment:L,doneFn:m},w=>{L.map.bytes=w,v({type:"segmentdecryptioncomplete",segment:L}),XD(L,F=>{if(F)return Bv(s),m(F,L);I()})});I()}}}},X5=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},Q5=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f})=>m=>{if(!m.target.aborted)return s.stats=Kt(s.stats,H5(m)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(m,s)},Z5=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:n,progressFn:r,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:m,isEndOfTimeline:g,endedTimelineFn:v,dataFn:b,doneFn:_,onTransmuxerLog:E,triggerSegmentEventFn:L})=>{const I=[],w=W5({activeXhrs:I,decryptionWorker:t,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:m,isEndOfTimeline:g,endedTimelineFn:v,dataFn:b,doneFn:_,onTransmuxerLog:E,triggerSegmentEventFn:L});if(i.key&&!i.key.bytes){const q=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&q.push(i.map.key);const k=Kt(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),R=o1(i,q,w,L),K={uri:i.key.resolvedUri};L({type:"segmentkeyloadstart",segment:i,keyInfo:K});const X=s(k,R);I.push(X)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const X=Kt(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),ee=o1(i,[i.map.key],w,L),le={uri:i.map.key.resolvedUri};L({type:"segmentkeyloadstart",segment:i,keyInfo:le});const ae=s(X,ee);I.push(ae)}const k=Kt(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:Mv(i.map),requestType:"segment-media-initialization"}),R=q5({segment:i,finishProcessingFn:w,triggerSegmentEventFn:L});L({type:"segmentloadstart",segment:i});const K=s(k,R);I.push(K)}const F=Kt(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:Mv(i),requestType:"segment"}),U=z5({segment:i,finishProcessingFn:w,responseType:F.responseType,triggerSegmentEventFn:L});L({type:"segmentloadstart",segment:i});const V=s(F,U);V.addEventListener("progress",Q5({segment:i,progressFn:r,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:m,isEndOfTimeline:g,endedTimelineFn:v,dataFn:b})),I.push(V);const B={};return I.forEach(q=>{q.addEventListener("loadend",X5({loadendState:B,abortFn:n}))}),()=>Bv(I)},Wf=$n("PlaylistSelector"),l1=function(s){if(!s||!s.playlist)return;const e=s.playlist;return JSON.stringify({id:e.id,bandwidth:s.bandwidth,width:s.width,height:s.height,codecs:e.attributes&&e.attributes.CODECS||""})},Gu=function(s,e){if(!s)return"";const t=se.getComputedStyle(s);return t?t[e]:""},Vu=function(s,e){const t=s.slice();s.sort(function(i,n){const r=e(i,n);return r===0?t.indexOf(i)-t.indexOf(n):r})},QT=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||se.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||se.Number.MAX_VALUE,t-i},J5=function(s,e){let t,i;return s.attributes.RESOLUTION&&s.attributes.RESOLUTION.width&&(t=s.attributes.RESOLUTION.width),t=t||se.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||se.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let JD=function(s){const{main:e,bandwidth:t,playerWidth:i,playerHeight:n,playerObjectFit:r,limitRenditionByPlayerDimensions:o,playlistController:u}=s;if(!e)return;const c={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:o};let d=e.playlists;tn.isAudioOnly(e)&&(d=u.getAudioTrackPlaylists_(),c.audioOnly=!0);let f=d.map(B=>{let q;const k=B.attributes&&B.attributes.RESOLUTION&&B.attributes.RESOLUTION.width,R=B.attributes&&B.attributes.RESOLUTION&&B.attributes.RESOLUTION.height;return q=B.attributes&&B.attributes.BANDWIDTH,q=q||se.Number.MAX_VALUE,{bandwidth:q,width:k,height:R,playlist:B}});Vu(f,(B,q)=>B.bandwidth-q.bandwidth),f=f.filter(B=>!tn.isIncompatible(B.playlist));let m=f.filter(B=>tn.isEnabled(B.playlist));m.length||(m=f.filter(B=>!tn.isDisabled(B.playlist)));const g=m.filter(B=>B.bandwidth*us.BANDWIDTH_VARIANCEB.bandwidth===v.bandwidth)[0];if(o===!1){const B=b||m[0]||f[0];if(B&&B.playlist){let q="sortedPlaylistReps";return b&&(q="bandwidthBestRep"),m[0]&&(q="enabledPlaylistReps"),Wf(`choosing ${l1(B)} using ${q} with options`,c),B.playlist}return Wf("could not choose a playlist with options",c),null}const _=g.filter(B=>B.width&&B.height);Vu(_,(B,q)=>B.width-q.width);const E=_.filter(B=>B.width===i&&B.height===n);v=E[E.length-1];const L=E.filter(B=>B.bandwidth===v.bandwidth)[0];let I,w,F;L||(I=_.filter(B=>r==="cover"?B.width>i&&B.height>n:B.width>i||B.height>n),w=I.filter(B=>B.width===I[0].width&&B.height===I[0].height),v=w[w.length-1],F=w.filter(B=>B.bandwidth===v.bandwidth)[0]);let U;if(u.leastPixelDiffSelector){const B=_.map(q=>(q.pixelDiff=Math.abs(q.width-i)+Math.abs(q.height-n),q));Vu(B,(q,k)=>q.pixelDiff===k.pixelDiff?k.bandwidth-q.bandwidth:q.pixelDiff-k.pixelDiff),U=B[0]}const V=U||F||L||b||m[0]||f[0];if(V&&V.playlist){let B="sortedPlaylistReps";return U?B="leastPixelDiffRep":F?B="resolutionPlusOneRep":L?B="resolutionBestRep":b?B="bandwidthBestRep":m[0]&&(B="enabledPlaylistReps"),Wf(`choosing ${l1(V)} using ${B} with options`,c),V.playlist}return Wf("could not choose a playlist with options",c),null};const u1=function(){let s=this.useDevicePixelRatio&&se.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),JD({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(Gu(this.tech_.el(),"width"),10)*s,playerHeight:parseInt(Gu(this.tech_.el(),"height"),10)*s,playerObjectFit:this.usePlayerObjectFit?Gu(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},e4=function(s){let e=-1,t=-1;if(s<0||s>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){let i=this.useDevicePixelRatio&&se.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(i=this.customPixelRatio),e<0&&(e=this.systemBandwidth,t=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==t&&(e=s*this.systemBandwidth+(1-s)*e,t=this.systemBandwidth),JD({main:this.playlists.main,bandwidth:e,playerWidth:parseInt(Gu(this.tech_.el(),"width"),10)*i,playerHeight:parseInt(Gu(this.tech_.el(),"height"),10)*i,playerObjectFit:this.usePlayerObjectFit?Gu(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},t4=function(s){const{main:e,currentTime:t,bandwidth:i,duration:n,segmentDuration:r,timeUntilRebuffer:o,currentTimeline:u,syncController:c}=s,d=e.playlists.filter(b=>!tn.isIncompatible(b));let f=d.filter(tn.isEnabled);f.length||(f=d.filter(b=>!tn.isDisabled(b)));const g=f.filter(tn.hasAttribute.bind(null,"BANDWIDTH")).map(b=>{const E=c.getSyncPoint(b,n,u,t)?1:2,I=tn.estimateSegmentRequestTime(r,i,b)*E-o;return{playlist:b,rebufferingImpact:I}}),v=g.filter(b=>b.rebufferingImpact<=0);return Vu(v,(b,_)=>QT(_.playlist,b.playlist)),v.length?v[0]:(Vu(g,(b,_)=>b.rebufferingImpact-_.rebufferingImpact),g[0]||null)},i4=function(){const s=this.playlists.main.playlists.filter(tn.isEnabled);return Vu(s,(t,i)=>QT(t,i)),s.filter(t=>!!jd(this.playlists.main,t).video)[0]||null},s4=s=>{let e=0,t;return s.bytes&&(t=new Uint8Array(s.bytes),s.segments.forEach(i=>{t.set(i,e),e+=i.byteLength})),t};function ew(s){try{return new URL(s).pathname.split("/").slice(-2).join("/")}catch{return""}}const n4=function(s,e,t){if(!s[t]){e.trigger({type:"usage",name:"vhs-608"});let i=t;/^cc708_/.test(t)&&(i="SERVICE"+t.split("_")[1]);const n=e.textTracks().getTrackById(i);if(n)s[t]=n;else{const r=e.options_.vhs&&e.options_.vhs.captionServices||{};let o=t,u=t,c=!1;const d=r[i];d&&(o=d.label,u=d.language,c=d.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:c,label:o,language:u},!1).track}}},r4=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=se.WebKitDataCue||se.VTTCue;e.forEach(n=>{const r=n.stream;n.content?n.content.forEach(o=>{const u=new i(n.startTime+t,n.endTime+t,o.text);u.line=o.line,u.align="left",u.position=o.position,u.positionAlign="line-left",s[r].addCue(u)}):s[r].addCue(new i(n.startTime+t,n.endTime+t,n.text))})},a4=function(s){Object.defineProperties(s.frame,{id:{get(){return Te.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),s.value.key}},value:{get(){return Te.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),s.value.data}},privateData:{get(){return Te.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),s.value.data}}})},o4=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const n=se.WebKitDataCue||se.VTTCue,r=s.metadataTrack_;if(!r||(e.forEach(f=>{const m=f.cueTime+t;typeof m!="number"||se.isNaN(m)||m<0||!(m<1/0)||!f.frames||!f.frames.length||f.frames.forEach(g=>{const v=new n(m,m,g.value||g.url||g.data||"");v.frame=g,v.value=g,a4(v),r.addCue(v)})}),!r.cues||!r.cues.length))return;const o=r.cues,u=[];for(let f=0;f{const g=f[m.startTime]||[];return g.push(m),f[m.startTime]=g,f},{}),d=Object.keys(c).sort((f,m)=>Number(f)-Number(m));d.forEach((f,m)=>{const g=c[f],v=isFinite(i)?i:f,b=Number(d[m+1])||v;g.forEach(_=>{_.endTime=b})})},l4={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},u4=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),c4=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=se.WebKitDataCue||se.VTTCue;e.forEach(n=>{for(const r of Object.keys(n)){if(u4.has(r))continue;const o=new i(n.startTime,n.endTime,"");o.id=n.id,o.type="com.apple.quicktime.HLS",o.value={key:l4[r],data:n[r]},(r==="scte35Out"||r==="scte35In")&&(o.value.data=new Uint8Array(o.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(o)}n.processDateRange()})},c1=(s,e,t)=>{s.metadataTrack_||(s.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,Te.browser.IS_ANY_SAFARI||(s.metadataTrack_.inBandMetadataTrackDispatchType=e))},Id=function(s,e,t){let i,n;if(t&&t.cues)for(i=t.cues.length;i--;)n=t.cues[i],n.startTime>=s&&n.endTime<=e&&t.removeCue(n)},d4=function(s){const e=s.cues;if(!e)return;const t={};for(let i=e.length-1;i>=0;i--){const n=e[i],r=`${n.startTime}-${n.endTime}-${n.text}`;t[r]?s.removeCue(n):t[r]=n}},h4=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*ml.ONE_SECOND_IN_TS);let n;for(n=0;ni);n++);return s.slice(n)},f4=(s,e,t)=>{if(!e.length)return s;if(t)return e.slice();const i=e[0].pts;let n=0;for(n;n=i);n++);return s.slice(0,n).concat(e)},p4=(s,e,t,i)=>{const n=Math.ceil((e-i)*ml.ONE_SECOND_IN_TS),r=Math.ceil((t-i)*ml.ONE_SECOND_IN_TS),o=s.slice();let u=s.length;for(;u--&&!(s[u].pts<=r););if(u===-1)return o;let c=u+1;for(;c--&&!(s[c].pts<=n););return c=Math.max(c,0),o.splice(c,u-c+1),o},m4=function(s,e){if(!s&&!e||!s&&e||s&&!e)return!1;if(s===e)return!0;const t=Object.keys(s).sort(),i=Object.keys(e).sort();if(t.length!==i.length)return!1;for(let n=0;nt))return r}return i.length===0?0:i[i.length-1]},Sd=1,y4=500,d1=s=>typeof s=="number"&&isFinite(s),Xf=1/60,v4=(s,e,t)=>s!=="main"||!e||!t?null:!t.hasAudio&&!t.hasVideo?"Neither audio nor video found in segment.":e.hasVideo&&!t.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!e.hasVideo&&t.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null,T4=(s,e,t)=>{let i=e-us.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const n=e-t;return Math.min(n,i)},xu=s=>{const{startOfSegment:e,duration:t,segment:i,part:n,playlist:{mediaSequence:r,id:o,segments:u=[]},mediaIndex:c,partIndex:d,timeline:f}=s,m=u.length-1;let g="mediaIndex/partIndex increment";s.getMediaInfoForTime?g=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(g="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(g+=` with independent ${s.independent}`);const v=typeof d=="number",b=s.segment.uri?"segment":"pre-segment",_=v?vD({preloadSegment:i})-1:0;return`${b} [${r+c}/${r+m}]`+(v?` part [${d}/${_}]`:"")+` segment start/end [${i.start} => ${i.end}]`+(v?` part start/end [${n.start} => ${n.end}]`:"")+` startOfSegment [${e}] duration [${t}] timeline [${f}] selected by [${g}] playlist [${o}]`},h1=s=>`${s}TimingInfo`,b4=({segmentTimeline:s,currentTimeline:e,startOfSegment:t,buffered:i,overrideCheck:n})=>!n&&s===e?null:s{if(e===t)return!1;if(i==="audio"){const r=s.lastTimelineChange({type:"main"});return!r||r.to!==t}if(i==="main"&&n){const r=s.pendingTimelineChange({type:"audio"});return!(r&&r.to===t)}return!1},_4=s=>{if(!s)return!1;const e=s.pendingTimelineChange({type:"audio"}),t=s.pendingTimelineChange({type:"main"}),i=e&&t,n=i&&e.to!==t.to;return!!(i&&e.from!==-1&&t.from!==-1&&n)},x4=s=>{const e=s.timelineChangeController_.pendingTimelineChange({type:"audio"}),t=s.timelineChangeController_.pendingTimelineChange({type:"main"});return e&&t&&e.to{const e=s.pendingSegment_;if(!e)return;if(Fv({timelineChangeController:s.timelineChangeController_,currentTimeline:s.currentTimeline_,segmentTimeline:e.timeline,loaderType:s.loaderType_,audioDisabled:s.audioDisabled_})&&_4(s.timelineChangeController_)){if(x4(s)){s.timelineChangeController_.trigger("audioTimelineBehind");return}s.timelineChangeController_.trigger("fixBadTimelineChange")}},S4=s=>{let e=0;return["video","audio"].forEach(function(t){const i=s[`${t}TimingInfo`];if(!i)return;const{start:n,end:r}=i;let o;typeof n=="bigint"||typeof r=="bigint"?o=se.BigInt(r)-se.BigInt(n):typeof n=="number"&&typeof r=="number"&&(o=r-n),typeof o<"u"&&o>e&&(e=o)}),typeof e=="bigint"&&es?Math.round(s)>e+Lr:!1,E4=(s,e)=>{if(e!=="hls")return null;const t=S4({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,n=f1({segmentDuration:t,maxDuration:i*2}),r=f1({segmentDuration:t,maxDuration:i}),o=`Segment with index ${s.mediaIndex} from playlist ${s.playlist.id} has a duration of ${t} when the reported duration is ${s.duration} and the target duration is ${i}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return n||r?{severity:n?"warn":"info",message:o}:null},fl=({type:s,segment:e})=>{if(!e)return;const t=!!(e.key||e.map&&e.map.ke),i=!!(e.map&&!e.map.bytes),n=e.startOfSegment===void 0?e.start:e.startOfSegment;return{type:s||e.type,uri:e.resolvedUri||e.uri,start:n,duration:e.duration,isEncrypted:t,isMediaInitialization:i}};class Uv extends Te.EventTarget{constructor(e,t={}){if(super(),!e)throw new TypeError("Initialization settings are required");if(typeof e.currentTime!="function")throw new TypeError("No currentTime getter specified");if(!e.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",()=>{this.isEndOfStream_()||(this.ended_=!1)}),this.fetchAtBuffer_=!1,this.logger_=$n(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(i){i!==this.state_&&(this.logger_(`${this.state_} -> ${i}`),this.state_=i,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():lo(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger($i({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():lo(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger($i({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():lo(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():lo(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return Ry.createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&se.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){if(this.state!=="WAITING"){this.pendingSegment_&&(this.pendingSegment_=null),this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);return}this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,se.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return this.state==="APPENDING"&&!this.pendingSegment_?(this.state="READY",!0):!this.pendingSegment_||this.pendingSegment_.requestId!==e}error(e){return typeof e<"u"&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&Ry.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return ds();if(this.loaderType_==="main"){const{hasAudio:t,hasVideo:i,isMuxed:n}=e;if(i&&t&&!this.audioDisabled_&&!n)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;const i=Yp(e);let n=this.initSegments_[i];return t&&!n&&e.bytes&&(this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),n||e}segmentKey(e,t=!1){if(!e)return null;const i=BD(e);let n=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!n&&e.bytes&&(this.keyCache_[i]=n={resolvedUri:e.resolvedUri,bytes:e.bytes});const r={resolvedUri:(n||e).resolvedUri};return n&&(r.bytes=n.bytes),r}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),!!this.playlist_){if(this.state==="INIT"&&this.couldBeginLoading_())return this.init_();!this.couldBeginLoading_()||this.state!=="READY"&&this.state!=="INIT"||(this.state="READY")}}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e||this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)return;const i=this.playlist_,n=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,this.state==="INIT"&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},this.loaderType_==="main"&&this.syncController_.setDateTimeMappingForStart(e));let r=null;if(i&&(i.id?r=i.id:i.uri&&(r=i.uri)),this.logger_(`playlist update [${r} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update: -currentTime: ${this.currentTime_()} -bufferedEnd: ${Iy(this.buffered_())} -`,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),this.state==="INIT"&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri){this.mediaIndex!==null&&(!e.endList&&typeof e.partTargetDuration=="number"?this.resetLoader():this.resyncLoader()),this.currentMediaInfo_=void 0,this.trigger("playlistupdate");return}const o=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${o}]`),this.mediaIndex!==null)if(this.mediaIndex-=o,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const u=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!u.parts||!u.parts.length||!u.parts[this.partIndex])){const c=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=c}}n&&(n.mediaIndex-=o,n.mediaIndex<0?(n.mediaIndex=null,n.partIndex=null):(n.mediaIndex>=0&&(n.segment=e.segments[n.mediaIndex]),n.partIndex>=0&&n.segment.parts&&(n.part=n.segment.parts[n.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(se.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return this.checkBufferTimeout_===null}resetEverything(e){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&Ry.reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;const e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;this.sourceType_==="hls"&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=()=>{},n=!1){if(t===1/0&&(t=this.duration_()),t<=e){this.logger_("skipping remove because end ${end} is <= start ${start}");return}if(!this.sourceUpdater_||!this.getMediaInfo_()){this.logger_("skipping remove because no source updater or starting media info");return}let r=1;const o=()=>{r--,r===0&&i()};(n||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,o)),(n||this.loaderType_==="main")&&(this.gopBuffer_=p4(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,o));for(const u in this.inbandTextTracks_)Id(e,t,this.inbandTextTracks_[u]);Id(e,t,this.segmentMetadataTrack_),o()}monitorBuffer_(){this.checkBufferTimeout_&&se.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=se.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&se.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=se.setTimeout(this.monitorBufferTick_.bind(this),y4)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:fl({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const n=typeof e=="number"&&t.segments[e],r=e+1===t.segments.length,o=!n||!n.parts||i+1===n.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&r&&o}chooseNextRequest_(){const e=this.buffered_(),t=Iy(e)||0,i=zT(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),o=this.playlist_.segments;if(!o.length||n||r)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const u={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(u.isSyncRequest)u.mediaIndex=g4(this.currentTimeline_,o,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${u.mediaIndex}`);else if(this.mediaIndex!==null){const g=o[this.mediaIndex],v=typeof this.partIndex=="number"?this.partIndex:-1;u.startOfSegment=g.end?g.end:t,g.parts&&g.parts[v+1]?(u.mediaIndex=this.mediaIndex,u.partIndex=v+1):u.mediaIndex=this.mediaIndex+1}else{let g,v,b;const _=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch: -For TargetTime: ${_}. -CurrentTime: ${this.currentTime_()} -BufferedEnd: ${t} -Fetch At Buffer: ${this.fetchAtBuffer_} -`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const E=this.getSyncInfoFromMediaSequenceSync_(_);if(!E){const L="No sync info found while using media sequence sync";return this.error({message:L,metadata:{errorType:Te.Error.StreamingFailedToSelectNextSegment,error:new Error(L)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${E.start} --> ${E.end})`),g=E.segmentIndex,v=E.partIndex,b=E.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const E=tn.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:_,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});g=E.segmentIndex,v=E.partIndex,b=E.startTime}u.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${_}`:`currentTime ${_}`,u.mediaIndex=g,u.startOfSegment=b,u.partIndex=v,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${u.mediaIndex} `)}const c=o[u.mediaIndex];let d=c&&typeof u.partIndex=="number"&&c.parts&&c.parts[u.partIndex];if(!c||typeof u.partIndex=="number"&&!d)return null;typeof u.partIndex!="number"&&c.parts&&(u.partIndex=0,d=c.parts[0]);const f=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&d&&!f&&!d.independent)if(u.partIndex===0){const g=o[u.mediaIndex-1],v=g.parts&&g.parts.length&&g.parts[g.parts.length-1];v&&v.independent&&(u.mediaIndex-=1,u.partIndex=g.parts.length-1,u.independent="previous segment")}else c.parts[u.partIndex-1].independent&&(u.partIndex-=1,u.independent="previous part");const m=this.mediaSource_&&this.mediaSource_.readyState==="ended";return u.mediaIndex>=o.length-1&&m&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,u.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(u))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;const t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);const i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;const n=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return n?(n.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),n):null}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:n,startOfSegment:r,isSyncRequest:o,partIndex:u,forceTimestampOffset:c,getMediaInfoForTime:d}=e,f=i.segments[n],m=typeof u=="number"&&f.parts[u],g={requestId:"segment-loader-"+Math.random(),uri:m&&m.resolvedUri||f.resolvedUri,mediaIndex:n,partIndex:m?u:null,isSyncRequest:o,startOfSegment:r,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:f.timeline,duration:m&&m.duration||f.duration,segment:f,part:m,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:d,independent:t},v=typeof c<"u"?c:this.isPendingTimestampOffset_;g.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:f.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:v});const b=Iy(this.sourceUpdater_.audioBuffered());return typeof b=="number"&&(g.audioAppendStart=b-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(g.gopsToAlignWith=h4(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),g}timestampOffsetForSegment_(e){return b4(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH||Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;const t=this.currentTime_(),i=e.bandwidth,n=this.pendingSegment_.duration,r=tn.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),o=H3(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=o)return;const u=t4({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:n,timeUntilRebuffer:o,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!u)return;const d=r-o-u.rebufferingImpact;let f=.5;o<=Lr&&(f=1),!(!u.playlist||u.playlist.uri===this.playlist_.uri||d{r[o.stream]=r[o.stream]||{startTime:1/0,captions:[],endTime:0};const u=r[o.stream];u.startTime=Math.min(u.startTime,o.startTime+n),u.endTime=Math.max(u.endTime,o.endTime+n),u.captions.push(o)}),Object.keys(r).forEach(o=>{const{startTime:u,endTime:c,captions:d}=r[o],f=this.inbandTextTracks_;this.logger_(`adding cues from ${u} -> ${c} for ${o}`),n4(f,this.vhs_.tech_,o),Id(u,c,f[o]),r4({captionArray:d,inbandTextTracks:f,timestampOffset:n})}),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(!this.pendingSegment_.hasAppendedData_){this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i));return}this.addMetadataToTextTrack(i,t,this.duration_())}processMetadataQueue_(){this.metadataQueue_.id3.forEach(e=>e()),this.metadataQueue_.caption.forEach(e=>e()),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){const e=this.callQueue_;this.callQueue_=[],e.forEach(t=>t())}processLoadQueue_(){const e=this.loadQueue_;this.loadQueue_=[],e.forEach(t=>t())}hasEnoughInfoToLoad_(){if(this.loaderType_!=="audio")return!0;const e=this.pendingSegment_;return e?this.getCurrentMediaInfo_()?!Fv({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}):!0:!1}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()||this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;const{hasAudio:i,hasVideo:n,isMuxed:r}=t;return!(n&&!e.videoTimingInfo||i&&!this.audioDisabled_&&!r&&!e.audioTimingInfo||Fv({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_()){lo(this),this.callQueue_.push(this.handleData_.bind(this,e,t));return}const i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),this.mediaSource_.readyState!=="closed"){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[h1(t.type)].start;else{const n=this.getCurrentMediaInfo_(),r=this.loaderType_==="main"&&n&&n.hasVideo;let o;r&&(o=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:r,firstVideoFrameTimeForData:o,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:this.loaderType_==="main"});const n=this.chooseNextRequest_();if(n.mediaIndex!==i.mediaIndex||n.partIndex!==i.partIndex){this.logger_("sync segment was incorrect, not appending");return}this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){this.loaderType_==="main"&&typeof e.timestampOffset=="number"&&!e.changedTimestampOffset&&(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:n}){if(i){const r=Yp(i);if(this.activeInitSegmentId_===r)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=r}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=n,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},n){const r=this.sourceUpdater_.audioBuffered(),o=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+gl(r).join(", ")),o.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+gl(o).join(", "));const u=r.length?r.start(0):0,c=r.length?r.end(r.length-1):0,d=o.length?o.start(0):0,f=o.length?o.end(o.length-1):0;if(c-u<=Sd&&f-d<=Sd){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${gl(r).join(", ")}, video buffer: ${gl(o).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const g=this.currentTime_()-Sd;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${g}`),this.remove(0,g,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${Sd}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=se.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},Sd*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},n){if(n){if(n.code===LD){this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i});return}this.logger_("Received non QUOTA_EXCEEDED_ERR on append",n),this.error({message:`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:Te.Error.StreamingFailedToAppendSegment}}),this.trigger("appenderror")}}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:n,bytes:r}){if(!r){const u=[n];let c=n.byteLength;i&&(u.unshift(i),c+=i.byteLength),r=s4({bytes:c,segments:u})}const o={segmentInfo:fl({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:o}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:r},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:r}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const n=this.pendingSegment_.segment,r=`${e}TimingInfo`;n[r]||(n[r]={}),n[r].transmuxerPrependedSeconds=i.prependedContentDuration||0,n[r].transmuxedPresentationStart=i.start.presentation,n[r].transmuxedDecodeStart=i.start.decode,n[r].transmuxedPresentationEnd=i.end.presentation,n[r].transmuxedDecodeEnd=i.end.decode,n[r].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:n}=t;if(!n||!n.byteLength||i==="audio"&&this.audioDisabled_)return;const r=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:r,data:n})}loadSegment_(e){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),typeof e.timestampOffset=="number"&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_()){lo(this),this.loadQueue_.push(()=>{const t=$i({},e,{forceTimestampOffset:!0});$i(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});return}this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),n=this.mediaIndex!==null,r=e.timeline!==this.currentTimeline_&&e.timeline>0,o=i||n&&r;this.logger_(`Requesting -${ew(e.uri)} -${xu(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=Z5({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:o,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:u,level:c,stream:d})=>{this.logger_(`${xu(e)} logged from transmuxer stream ${d} as a ${c}: ${u}`)},triggerSegmentEventFn:({type:u,segment:c,keyInfo:d,trackInfo:f,timingInfo:m})=>{const v={segmentInfo:fl({segment:c})};d&&(v.keyInfo=d),f&&(v.trackInfo=f),m&&(v.timingInfo=m),this.trigger({type:u,metadata:v})}})}trimBackBuffer_(e){const t=T4(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,n=e.segment.key||e.segment.map&&e.segment.map.key,r=e.segment.map&&!e.segment.map.bytes,o={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:n,isMediaInitialization:r},u=e.playlist.segments[e.mediaIndex-1];if(u&&u.timeline===t.timeline&&(u.videoTimingInfo?o.baseStartTime=u.videoTimingInfo.transmuxedDecodeEnd:u.audioTimingInfo&&(o.baseStartTime=u.audioTimingInfo.transmuxedDecodeEnd)),t.key){const c=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);o.key=this.segmentKey(t.key),o.key.iv=c}return t.map&&(o.map=this.initSegmentForMap(t.map)),o}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e"u"||d.end!==n+r?n:u.start}waitForAppendsToComplete_(e){const t=this.getCurrentMediaInfo_(e);if(!t){this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),this.trigger("error");return}const{hasAudio:i,hasVideo:n,isMuxed:r}=t,o=this.loaderType_==="main"&&n,u=!this.audioDisabled_&&i&&!r;if(e.waitingOnAppends=0,!e.hasAppendedData_){!e.timingInfo&&typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),this.checkAppendsDone_(e);return}o&&e.waitingOnAppends++,u&&e.waitingOnAppends++,o&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),u&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))}checkAppendsDone_(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,e.waitingOnAppends===0&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(e){const t=v4(this.loaderType_,this.getCurrentMediaInfo_(),e);return t?(this.error({message:t,playlistExclusionDuration:1/0}),this.trigger("error"),!0):!1}updateSourceBufferTimestampOffset_(e){if(e.timestampOffset===null||typeof e.timingInfo.start!="number"||e.changedTimestampOffset||this.loaderType_!=="main")return;let t=!1;e.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e.segment.videoTimingInfo,audioTimingInfo:e.segment.audioTimingInfo,timingInfo:e.timingInfo}),e.changedTimestampOffset=!0,e.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(e.timestampOffset),t=!0),e.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(e.timestampOffset),t=!0),t&&this.trigger("timestampoffset")}getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e,audioTimingInfo:t,timingInfo:i}){return this.useDtsForTimestampOffset_?e&&typeof e.transmuxedDecodeStart=="number"?e.transmuxedDecodeStart:t&&typeof t.transmuxedDecodeStart=="number"?t.transmuxedDecodeStart:i.start:i.start}updateTimingInfoEnd_(e){e.timingInfo=e.timingInfo||{};const t=this.getMediaInfo_(),n=this.loaderType_==="main"&&t&&t.hasVideo&&e.videoTimingInfo?e.videoTimingInfo:e.audioTimingInfo;n&&(e.timingInfo.end=typeof n.end=="number"?n.end:n.start+e.duration)}handleAppendsDone_(){if(this.pendingSegment_){const c={segmentInfo:fl({type:this.loaderType_,segment:this.pendingSegment_})};this.trigger({type:"appendsdone",metadata:c})}if(!this.pendingSegment_){this.state="READY",this.paused()||this.monitorBuffer_();return}const e=this.pendingSegment_;e.part&&e.part.syncInfo?e.part.syncInfo.markAppended():e.segment.syncInfo&&e.segment.syncInfo.markAppended(),this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:this.loaderType_==="main"});const t=E4(e,this.sourceType_);if(t&&(t.severity==="warn"?Te.log.warn(t.message):this.logger_(t.message)),this.recordThroughput_(e),this.pendingSegment_=null,this.state="READY",e.isSyncRequest&&(this.trigger("syncinfoupdate"),!e.hasAppendedData_)){this.logger_(`Throwing away un-appended sync request ${xu(e)}`);return}this.logger_(`Appended ${xu(e)}`),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),this.loaderType_==="main"&&!this.audioDisabled_&&this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");const i=e.segment,n=e.part,r=i.end&&this.currentTime_()-i.end>e.playlist.targetDuration*3,o=n&&n.end&&this.currentTime_()-n.end>e.playlist.partTargetDuration*3;if(r||o){this.logger_(`bad ${r?"segment":"part"} ${xu(e)}`),this.resetEverything();return}this.mediaIndex!==null&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duratione.toUpperCase())},A4=["video","audio"],$v=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},C4=(s,e)=>{for(let t=0;t{if(e.queue.length===0)return;let t=0,i=e.queue[t];if(i.type==="mediaSource"){!e.updating()&&e.mediaSource.readyState!=="closed"&&(e.queue.shift(),i.action(e),i.doneFn&&i.doneFn(),qu("audio",e),qu("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||$v(s,e))){if(i.type!==s){if(t=C4(s,e.queue),t===null)return;i=e.queue[t]}if(e.queue.splice(t,1),e.queuePending[s]=i,i.action(s,e),!i.doneFn){e.queuePending[s]=null,qu(s,e);return}}},iw=(s,e)=>{const t=e[`${s}Buffer`],i=tw(s);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[s]=null,e[`${s}Buffer`]=null)},Cr=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,gn={appendBuffer:(s,e,t)=>(i,n)=>{const r=n[`${i}Buffer`];if(Cr(n.mediaSource,r)){n.logger_(`Appending segment ${e.mediaIndex}'s ${s.length} bytes to ${i}Buffer`);try{r.appendBuffer(s)}catch(o){n.logger_(`Error with code ${o.code} `+(o.code===LD?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),n.queuePending[i]=null,t(o)}}},remove:(s,e)=>(t,i)=>{const n=i[`${t}Buffer`];if(Cr(i.mediaSource,n)){i.logger_(`Removing ${s} to ${e} from ${t}Buffer`);try{n.remove(s,e)}catch{i.logger_(`Remove ${s} to ${e} from ${t}Buffer failed`)}}},timestampOffset:s=>(e,t)=>{const i=t[`${e}Buffer`];Cr(t.mediaSource,i)&&(t.logger_(`Setting ${e}timestampOffset to ${s}`),i.timestampOffset=s)},callback:s=>(e,t)=>{s()},endOfStream:s=>e=>{if(e.mediaSource.readyState==="open"){e.logger_(`Calling mediaSource endOfStream(${s||""})`);try{e.mediaSource.endOfStream(s)}catch(t){Te.log.warn("Failed to call media source endOfStream",t)}}},duration:s=>e=>{e.logger_(`Setting mediaSource duration to ${s}`);try{e.mediaSource.duration=s}catch(t){Te.log.warn("Failed to set media source duration",t)}},abort:()=>(s,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${s}Buffer`];if(Cr(e.mediaSource,t)){e.logger_(`calling abort on ${s}Buffer`);try{t.abort()}catch(i){Te.log.warn(`Failed to abort on ${s}Buffer`,i)}}},addSourceBuffer:(s,e)=>t=>{const i=tw(s),n=Xu(e);t.logger_(`Adding ${s}Buffer with codec ${e} to mediaSource`);const r=t.mediaSource.addSourceBuffer(n);r.addEventListener("updateend",t[`on${i}UpdateEnd_`]),r.addEventListener("error",t[`on${i}Error_`]),t.codecs[s]=e,t[`${s}Buffer`]=r},removeSourceBuffer:s=>e=>{const t=e[`${s}Buffer`];if(iw(s,e),!!Cr(e.mediaSource,t)){e.logger_(`Removing ${s}Buffer with codec ${e.codecs[s]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){Te.log.warn(`Failed to removeSourceBuffer ${s}Buffer`,i)}}},changeType:s=>(e,t)=>{const i=t[`${e}Buffer`],n=Xu(s);if(!Cr(t.mediaSource,i))return;const r=s.substring(0,s.indexOf(".")),o=t.codecs[e];if(o.substring(0,o.indexOf("."))===r)return;const c={codecsChangeInfo:{from:o,to:s}};t.trigger({type:"codecschange",metadata:c}),t.logger_(`changing ${e}Buffer codec from ${o} to ${s}`);try{i.changeType(n),t.codecs[e]=s}catch(d){c.errorType=Te.Error.StreamingCodecsChangeError,c.error=d,d.metadata=c,t.error_=d,t.trigger("error"),Te.log.warn(`Failed to changeType on ${e}Buffer`,d)}}},yn=({type:s,sourceUpdater:e,action:t,doneFn:i,name:n})=>{e.queue.push({type:s,action:t,doneFn:i,name:n}),qu(s,e)},p1=(s,e)=>t=>{const i=e[`${s}Buffered`](),n=U3(i);if(e.logger_(`received "updateend" event for ${s} Source Buffer: `,n),e.queuePending[s]){const r=e.queuePending[s].doneFn;e.queuePending[s]=null,r&&r(e[`${s}Error_`])}qu(s,e)};class sw extends Te.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>qu("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=$n("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=p1("video",this),this.onAudioUpdateEnd_=p1("audio",this),this.onVideoError_=t=>{this.videoError_=t},this.onAudioError_=t=>{this.audioError_=t},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(e,t){yn({type:"mediaSource",sourceUpdater:this,action:gn.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){yn({type:e,sourceUpdater:this,action:gn.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){Te.log.error("removeSourceBuffer is not supported!");return}yn({type:"mediaSource",sourceUpdater:this,action:gn.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!Te.browser.IS_FIREFOX&&se.MediaSource&&se.MediaSource.prototype&&typeof se.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return se.SourceBuffer&&se.SourceBuffer.prototype&&typeof se.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){Te.log.error("changeType is not supported!");return}yn({type:e,sourceUpdater:this,action:gn.changeType(t),name:"changeType"})}addOrChangeSourceBuffers(e){if(!e||typeof e!="object"||Object.keys(e).length===0)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach(t=>{const i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)})}appendBuffer(e,t){const{segmentInfo:i,type:n,bytes:r}=e;if(this.processedAppend_=!0,n==="audio"&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([e,t]),this.logger_(`delayed audio append of ${r.length} until video append`);return}const o=t;if(yn({type:n,sourceUpdater:this,action:gn.appendBuffer(r,i||{mediaIndex:-1},o),doneFn:t,name:"appendBuffer"}),n==="video"){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const u=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${u.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,u.forEach(c=>{this.appendBuffer.apply(this,c)})}}audioBuffered(){return Cr(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:ds()}videoBuffered(){return Cr(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:ds()}buffered(){const e=Cr(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=Cr(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():j3(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=ga){yn({type:"mediaSource",sourceUpdater:this,action:gn.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=ga){typeof e!="string"&&(e=void 0),yn({type:"mediaSource",sourceUpdater:this,action:gn.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=ga){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}yn({type:"audio",sourceUpdater:this,action:gn.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=ga){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}yn({type:"video",sourceUpdater:this,action:gn.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!($v("audio",this)||$v("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(yn({type:"audio",sourceUpdater:this,action:gn.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(yn({type:"video",sourceUpdater:this,action:gn.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&yn({type:"audio",sourceUpdater:this,action:gn.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&yn({type:"video",sourceUpdater:this,action:gn.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),A4.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>iw(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const m1=s=>decodeURIComponent(escape(String.fromCharCode.apply(null,s))),D4=s=>{const e=new Uint8Array(s);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},g1=new Uint8Array(` - -`.split("").map(s=>s.charCodeAt(0)));class w4 extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class L4 extends Uv{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return ds();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return ds([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=Yp(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const r=g1.byteLength+e.bytes.byteLength,o=new Uint8Array(r);o.set(e.bytes),o.set(g1,e.bytes.byteLength),this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:o}}return n||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return typeof e>"u"?this.subtitlesTrack_:(this.subtitlesTrack_=e,this.state==="INIT"&&this.couldBeginLoading_()&&this.init_(),this.subtitlesTrack_)}remove(e,t){Id(e,t,this.subtitlesTrack_)}fillBuffer_(){const e=this.chooseNextRequest_();if(e){if(this.syncController_.timestampOffsetForTimeline(e.timeline)===null){const t=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};this.syncController_.one("timestampoffset",t),this.state="WAITING_ON_TIMELINE";return}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,i){if(!this.subtitlesTrack_){this.state="READY";return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_){this.state="READY",this.mediaRequestsAborted+=1;return}if(e){e.code===kr.TIMEOUT&&this.handleTimeout_(),e.code===kr.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}const n=this.pendingSegment_,r=i.mp4VttCues&&i.mp4VttCues.length;r&&(n.mp4VttCues=i.mp4VttCues),this.saveBandwidthRelatedStats_(n.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const o=n.segment;if(o.map&&(o.map.bytes=t.map.bytes),n.bytes=t.bytes,typeof se.WebVTT!="function"&&typeof this.loadVttJs=="function"){this.state="WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,i),()=>this.stopForError({message:"Error loading vtt.js"}));return}o.requested=!0;try{this.parseVTTCues_(n)}catch(u){this.stopForError({message:u.message,metadata:{errorType:Te.Error.StreamingVttParserError,error:u}});return}if(r||this.updateTimeMapping_(n,this.syncController_.timelines[n.timeline],this.playlist_),n.cues.length?n.timingInfo={start:n.cues[0].startTime,end:n.cues[n.cues.length-1].endTime}:n.timingInfo={start:n.startOfSegment,end:n.startOfSegment+n.duration},n.isSyncRequest){this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY";return}n.byteLength=n.bytes.byteLength,this.mediaSecondsLoaded+=o.duration,n.cues.forEach(u=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new se.VTTCue(u.startTime,u.endTime,u.text):u)}),d4(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){const i=e&&e.type==="vtt",n=t&&t.type==="text";i&&n&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){const t=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(i=>{const n=i.start+t,r=i.end+t,o=new se.VTTCue(n,r,i.cueText);i.settings&&i.settings.split(" ").forEach(u=>{const c=u.split(":"),d=c[0],f=c[1];o[d]=isNaN(f)?f:Number(f)}),e.cues.push(o)})}parseVTTCues_(e){let t,i=!1;if(typeof se.WebVTT!="function")throw new w4;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof se.TextDecoder=="function"?t=new se.TextDecoder("utf8"):(t=se.WebVTT.StringDecoder(),i=!0);const n=new se.WebVTT.Parser(se,se.vttjs,t);if(n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=o=>{e.timestampmap=o},n.onparsingerror=o=>{Te.log.warn("Error encountered when parsing cues: "+o.message)},e.segment.map){let o=e.segment.map.bytes;i&&(o=m1(o)),n.parse(o)}let r=e.bytes;i&&(r=m1(r)),n.parse(r),n.flush()}updateTimeMapping_(e,t,i){const n=e.segment;if(!t)return;if(!e.cues.length){n.empty=!0;return}const{MPEGTS:r,LOCAL:o}=e.timestampmap,c=r/ml.ONE_SECOND_IN_TS-o+t.mapping;if(e.cues.forEach(d=>{const f=d.endTime-d.startTime,m=this.handleRollover_(d.startTime+c,t.time);d.startTime=Math.max(m,0),d.endTime=Math.max(m+f,0)}),!i.syncInfo){const d=e.cues[0].startTime,f=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(d,f-n.duration)}}}handleRollover_(e,t){if(t===null)return e;let i=e*ml.ONE_SECOND_IN_TS;const n=t*ml.ONE_SECOND_IN_TS;let r;for(n4294967296;)i+=r;return i/ml.ONE_SECOND_IN_TS}}const I4=function(s,e){const t=s.cues;for(let i=0;i=n.adStartTime&&e<=n.adEndTime)return n}return null},k4=function(s,e,t=0){if(!s.segments)return;let i=t,n;for(let r=0;r=this.start&&e0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}}class nw{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){const{mediaSequence:i,segments:n}=e;if(this.isReliable_=this.isReliablePlaylist_(i,n),!!this.isReliable_)return this.updateStorage_(n,i,this.calculateBaseTime_(i,n,t))}getSyncInfoForTime(e){for(const{segmentSyncInfo:t,partsSyncInfo:i}of this.storage_.values())if(i.length){for(const n of i)if(n.isInRange(e))return n}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,i){const n=new Map;let r=` -`,o=i,u=t;this.start_=o,e.forEach((c,d)=>{const f=this.storage_.get(u),m=o,g=m+c.duration,v=!!(f&&f.segmentSyncInfo&&f.segmentSyncInfo.isAppended),b=new y1({start:m,end:g,appended:v,segmentIndex:d});c.syncInfo=b;let _=o;const E=(c.parts||[]).map((L,I)=>{const w=_,F=_+L.duration,U=!!(f&&f.partsSyncInfo&&f.partsSyncInfo[I]&&f.partsSyncInfo[I].isAppended),V=new y1({start:w,end:F,appended:U,segmentIndex:d,partIndex:I});return _=F,r+=`Media Sequence: ${u}.${I} | Range: ${w} --> ${F} | Appended: ${U} -`,L.syncInfo=V,V});n.set(u,new R4(b,E)),r+=`${ew(c.resolvedUri)} | Media Sequence: ${u} | Range: ${m} --> ${g} | Appended: ${v} -`,u++,o=g}),this.end_=o,this.storage_=n,this.diagnostics_=r}calculateBaseTime_(e,t,i){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const n=Math.min(...this.storage_.keys());if(et!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(s,e,t,i,n,r)=>{const o=s.getMediaSequenceSync(r);if(!o||!o.isReliable)return null;const u=o.getSyncInfoForTime(n);return u?{time:u.start,partIndex:u.partIndex,segmentIndex:u.segmentIndex}:null}},{name:"ProgramDateTime",run:(s,e,t,i,n)=>{if(!Object.keys(s.timelineToDatetimeMappings).length)return null;let r=null,o=null;const u=Iv(e);n=n||0;for(let c=0;c{let r=null,o=null;n=n||0;const u=Iv(e);for(let c=0;c=v)&&(o=v,r={time:g,segmentIndex:f.segmentIndex,partIndex:f.partIndex})}}return r}},{name:"Discontinuity",run:(s,e,t,i,n)=>{let r=null;if(n=n||0,e.discontinuityStarts&&e.discontinuityStarts.length){let o=null;for(let u=0;u=m)&&(o=m,r={time:f.time,segmentIndex:c,partIndex:null})}}}return r}},{name:"Playlist",run:(s,e,t,i,n)=>e.syncInfo?{time:e.syncInfo.time,segmentIndex:e.syncInfo.mediaSequence-e.mediaSequence,partIndex:null}:null}];class P4 extends Te.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new nw,i=new v1(t),n=new v1(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:n},this.logger_=$n("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,n,r){if(t!==1/0)return Oy.find(({name:c})=>c==="VOD").run(this,e,t);const o=this.runStrategies_(e,t,i,n,r);if(!o.length)return null;for(const u of o){const{syncPoint:c,strategy:d}=u,{segmentIndex:f,time:m}=c;if(f<0)continue;const g=e.segments[f],v=m,b=v+g.duration;if(this.logger_(`Strategy: ${d}. Current time: ${n}. selected segment: ${f}. Time: [${v} -> ${b}]}`),n>=v&&n0&&(n.time*=-1),Math.abs(n.time+$d({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n,r){const o=[];for(let u=0;uO4){Te.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);return}for(let n=i-1;n>=0;n--){const r=e.segments[n];if(r&&typeof r.start<"u"){t.syncInfo={mediaSequence:e.mediaSequence+n,time:r.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),n=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:n.start}));const r=n.dateTimeObject;n.discontinuity&&t&&r&&(this.timelineToDatetimeMappings[n.timeline]=-(r.getTime()/1e3))}timestampOffsetForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].time}mappingForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){const n=e.segment,r=e.part;let o=this.timelines[e.timeline],u,c;if(typeof e.timestampOffset=="number")o={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=o,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${o.time}] [mapping: ${o.mapping}]`)),u=e.startOfSegment,c=t.end+o.mapping;else if(o)u=t.start+o.mapping,c=t.end+o.mapping;else return!1;return r&&(r.start=u,r.end=c),(!n.start||uc){let d;u<0?d=i.start-$d({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):d=i.end+$d({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[o]={time:d,accuracy:c}}}}dispose(){this.trigger("dispose"),this.off()}}class M4 extends Te.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return typeof t=="number"&&typeof i=="number"&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){if(typeof t=="number"&&typeof i=="number"){this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e];const n={timelineChangeInfo:{from:t,to:i}};this.trigger({type:"timelinechange",metadata:n})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const N4=GD(VD(function(){var s=(function(){function _(){this.listeners={}}var E=_.prototype;return E.on=function(I,w){this.listeners[I]||(this.listeners[I]=[]),this.listeners[I].push(w)},E.off=function(I,w){if(!this.listeners[I])return!1;var F=this.listeners[I].indexOf(w);return this.listeners[I]=this.listeners[I].slice(0),this.listeners[I].splice(F,1),F>-1},E.trigger=function(I){var w=this.listeners[I];if(w)if(arguments.length===2)for(var F=w.length,U=0;U>7)*283)^F]=F;for(U=V=0;!I[U];U^=k||1,V=q[V]||1)for(X=V^V<<1^V<<2^V<<3^V<<4,X=X>>8^X&255^99,I[U]=X,w[X]=U,K=B[R=B[k=B[U]]],le=K*16843009^R*65537^k*257^U*16843008,ee=B[X]*257^X*16843008,F=0;F<4;F++)E[F][U]=ee=ee<<24^ee>>>8,L[F][X]=le=le<<24^le>>>8;for(F=0;F<5;F++)E[F]=E[F].slice(0),L[F]=L[F].slice(0);return _};let i=null;class n{constructor(E){i||(i=t()),this._tables=[[i[0][0].slice(),i[0][1].slice(),i[0][2].slice(),i[0][3].slice(),i[0][4].slice()],[i[1][0].slice(),i[1][1].slice(),i[1][2].slice(),i[1][3].slice(),i[1][4].slice()]];let L,I,w;const F=this._tables[0][4],U=this._tables[1],V=E.length;let B=1;if(V!==4&&V!==6&&V!==8)throw new Error("Invalid aes key size");const q=E.slice(0),k=[];for(this._key=[q,k],L=V;L<4*V+28;L++)w=q[L-1],(L%V===0||V===8&&L%V===4)&&(w=F[w>>>24]<<24^F[w>>16&255]<<16^F[w>>8&255]<<8^F[w&255],L%V===0&&(w=w<<8^w>>>24^B<<24,B=B<<1^(B>>7)*283)),q[L]=q[L-V]^w;for(I=0;L;I++,L--)w=q[I&3?L:L-4],L<=4||I<4?k[I]=w:k[I]=U[0][F[w>>>24]]^U[1][F[w>>16&255]]^U[2][F[w>>8&255]]^U[3][F[w&255]]}decrypt(E,L,I,w,F,U){const V=this._key[1];let B=E^V[0],q=w^V[1],k=I^V[2],R=L^V[3],K,X,ee;const le=V.length/4-2;let ae,Y=4;const Q=this._tables[1],te=Q[0],oe=Q[1],de=Q[2],$=Q[3],ie=Q[4];for(ae=0;ae>>24]^oe[q>>16&255]^de[k>>8&255]^$[R&255]^V[Y],X=te[q>>>24]^oe[k>>16&255]^de[R>>8&255]^$[B&255]^V[Y+1],ee=te[k>>>24]^oe[R>>16&255]^de[B>>8&255]^$[q&255]^V[Y+2],R=te[R>>>24]^oe[B>>16&255]^de[q>>8&255]^$[k&255]^V[Y+3],Y+=4,B=K,q=X,k=ee;for(ae=0;ae<4;ae++)F[(3&-ae)+U]=ie[B>>>24]<<24^ie[q>>16&255]<<16^ie[k>>8&255]<<8^ie[R&255]^V[Y++],K=B,B=q,q=k,k=R,R=K}}class r extends s{constructor(){super(s),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(E){this.jobs.push(E),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const o=function(_){return _<<24|(_&65280)<<8|(_&16711680)>>8|_>>>24},u=function(_,E,L){const I=new Int32Array(_.buffer,_.byteOffset,_.byteLength>>2),w=new n(Array.prototype.slice.call(E)),F=new Uint8Array(_.byteLength),U=new Int32Array(F.buffer);let V,B,q,k,R,K,X,ee,le;for(V=L[0],B=L[1],q=L[2],k=L[3],le=0;le{const I=_[L];g(I)?E[L]={bytes:I.buffer,byteOffset:I.byteOffset,byteLength:I.byteLength}:E[L]=I}),E};self.onmessage=function(_){const E=_.data,L=new Uint8Array(E.encrypted.bytes,E.encrypted.byteOffset,E.encrypted.byteLength),I=new Uint32Array(E.key.bytes,E.key.byteOffset,E.key.byteLength/4),w=new Uint32Array(E.iv.bytes,E.iv.byteOffset,E.iv.byteLength/4);new c(L,I,w,function(F,U){self.postMessage(b({source:E.source,decrypted:U}),[U.buffer])})}}));var B4=HD(N4);const F4=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},rw=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},jv=(s,e)=>{e.activePlaylistLoader=s,s.load()},U4=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:n}}=e,r=n.activeTrack(),o=n.getActiveGroup(),u=n.activePlaylistLoader,c=n.lastGroup_;if(!(o&&c&&o.id===c.id)&&(n.lastGroup_=o,n.lastTrack_=r,rw(t,n),!(!o||o.isMainPlaylist))){if(!o.playlistLoader){u&&i.resetEverything();return}t.resyncLoader(),jv(o.playlistLoader,n)}},$4=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},j4=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:n},mediaTypes:{[s]:r}}=e,o=r.activeTrack(),u=r.getActiveGroup(),c=r.activePlaylistLoader,d=r.lastTrack_;if(!(d&&o&&d.id===o.id)&&(r.lastGroup_=u,r.lastTrack_=o,rw(i,r),!!u)){if(u.isMainPlaylist){if(!o||!d||o.id===d.id)return;const f=e.vhs.playlistController_,m=f.selectPlaylist();if(f.media()===m)return;r.logger_(`track change. Switching main audio from ${d.id} to ${o.id}`),t.pause(),n.resetEverything(),f.fastQualityChange_(m);return}if(s==="AUDIO"){if(!u.playlistLoader){n.setAudio(!0),n.resetEverything();return}i.setAudio(!0),n.setAudio(!1)}if(c===u.playlistLoader){jv(u.playlistLoader,r);return}i.track&&i.track(o),i.resetEverything(),jv(u.playlistLoader,r)}},Wp={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,n=t.activeTrack(),r=t.activeGroup(),o=(r.filter(c=>c.default)[0]||r[0]).id,u=t.tracks[o];if(n===u){i({error:{message:"Problem encountered loading the default audio track."}});return}Te.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const c in t.tracks)t.tracks[c].enabled=t.tracks[c]===u;t.onTrackChanged()},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:t}}=e;Te.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},T1={AUDIO:(s,e,t)=>{if(!e)return;const{tech:i,requestOptions:n,segmentLoaders:{[s]:r}}=t;e.on("loadedmetadata",()=>{const o=e.media();r.playlist(o,n),(!i.paused()||o.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",Wp[s](s,t))},SUBTITLES:(s,e,t)=>{const{tech:i,requestOptions:n,segmentLoaders:{[s]:r},mediaTypes:{[s]:o}}=t;e.on("loadedmetadata",()=>{const u=e.media();r.playlist(u,n),r.track(o.activeTrack()),(!i.paused()||u.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",Wp[s](s,t))}},H4={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:n},requestOptions:r,main:{mediaGroups:o},mediaTypes:{[s]:{groups:u,tracks:c,logger_:d}},mainPlaylistLoader:f}=e,m=hh(f.main);(!o[s]||Object.keys(o[s]).length===0)&&(o[s]={main:{default:{default:!0}}},m&&(o[s].main.default.playlists=f.main.playlists));for(const g in o[s]){u[g]||(u[g]=[]);for(const v in o[s][g]){let b=o[s][g][v],_;if(m?(d(`AUDIO group '${g}' label '${v}' is a main playlist`),b.isMainPlaylist=!0,_=null):i==="vhs-json"&&b.playlists?_=new Pu(b.playlists[0],t,r):b.resolvedUri?_=new Pu(b.resolvedUri,t,r):b.playlists&&i==="dash"?_=new Nv(b.playlists[0],t,r,f):_=null,b=Kt({id:v,playlistLoader:_},b),T1[s](s,b.playlistLoader,e),u[g].push(b),typeof c[v]>"u"){const E=new Te.AudioTrack({id:v,kind:F4(b),enabled:!1,language:b.language,default:b.default,label:v});c[v]=E}}}n.on("error",Wp[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:n,segmentLoaders:{[s]:r},requestOptions:o,main:{mediaGroups:u},mediaTypes:{[s]:{groups:c,tracks:d}},mainPlaylistLoader:f}=e;for(const m in u[s]){c[m]||(c[m]=[]);for(const g in u[s][m]){if(!i.options_.useForcedSubtitles&&u[s][m][g].forced)continue;let v=u[s][m][g],b;if(n==="hls")b=new Pu(v.resolvedUri,i,o);else if(n==="dash"){if(!v.playlists.filter(E=>E.excludeUntil!==1/0).length)return;b=new Nv(v.playlists[0],i,o,f)}else n==="vhs-json"&&(b=new Pu(v.playlists?v.playlists[0]:v.resolvedUri,i,o));if(v=Kt({id:g,playlistLoader:b},v),T1[s](s,v.playlistLoader,e),c[m].push(v),typeof d[g]>"u"){const _=t.addRemoteTextTrack({id:g,kind:"subtitles",default:v.default&&v.autoselect,language:v.language,label:g},!1).track;d[g]=_}}}r.on("error",Wp[s](s,e))},"CLOSED-CAPTIONS":(s,e)=>{const{tech:t,main:{mediaGroups:i},mediaTypes:{[s]:{groups:n,tracks:r}}}=e;for(const o in i[s]){n[o]||(n[o]=[]);for(const u in i[s][o]){const c=i[s][o][u];if(!/^(?:CC|SERVICE)/.test(c.instreamId))continue;const d=t.options_.vhs&&t.options_.vhs.captionServices||{};let f={label:u,language:c.language,instreamId:c.instreamId,default:c.default&&c.autoselect};if(d[f.instreamId]&&(f=Kt(f,d[f.instreamId])),f.default===void 0&&delete f.default,n[o].push(Kt({id:u},c)),typeof r[u]>"u"){const m=t.addRemoteTextTrack({id:f.instreamId,kind:"captions",default:f.default,language:f.language,label:f.label},!1).track;r[u]=m}}}}},aw=(s,e)=>{for(let t=0;tt=>{const{mainPlaylistLoader:i,mediaTypes:{[s]:{groups:n}}}=e,r=i.media();if(!r)return null;let o=null;r.attributes[s]&&(o=n[r.attributes[s]]);const u=Object.keys(n);if(!o)if(s==="AUDIO"&&u.length>1&&hh(e.main))for(let c=0;c"u"?o:t===null||!o?null:o.filter(c=>c.id===t.id)[0]||null},V4={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:{tracks:t}}}=e;for(const i in t)if(t[i].enabled)return t[i];return null},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:{tracks:t}}}=e;for(const i in t)if(t[i].mode==="showing"||t[i].mode==="hidden")return t[i];return null}},q4=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},z4=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(d=>{H4[d](d,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:n,segmentLoaders:{["AUDIO"]:r,main:o}}=s;["AUDIO","SUBTITLES"].forEach(d=>{e[d].activeGroup=G4(d,s),e[d].activeTrack=V4[d](d,s),e[d].onGroupChanged=U4(d,s),e[d].onGroupChanging=$4(d,s),e[d].onTrackChanged=j4(d,s),e[d].getActiveGroup=q4(d,s)});const u=e.AUDIO.activeGroup();if(u){const d=(u.filter(m=>m.default)[0]||u[0]).id;e.AUDIO.tracks[d].enabled=!0,e.AUDIO.onGroupChanged(),e.AUDIO.onTrackChanged(),e.AUDIO.getActiveGroup().playlistLoader?(o.setAudio(!1),r.setAudio(!0)):o.setAudio(!0)}t.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanging())});const c=()=>{e.AUDIO.onTrackChanged(),i.trigger({type:"usage",name:"vhs-audio-change"})};i.audioTracks().addEventListener("change",c),i.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),n.on("dispose",()=>{i.audioTracks().removeEventListener("change",c),i.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),i.clearTracks("audio");for(const d in e.AUDIO.tracks)i.audioTracks().addTrack(e.AUDIO.tracks[d])},K4=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:ga,activeTrack:ga,getActiveGroup:ga,onGroupChanged:ga,onTrackChanged:ga,lastTrack_:null,logger_:$n(`MediaGroups[${e}]`)}}),s};class b1{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){e===1&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=en(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(t=>[t.ID,t])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}let Y4=class extends Te.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new b1,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=$n("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const i=t.serverUri||t.serverURL;if(!i){this.logger_(`steering manifest URL is ${i}, cannot request steering manifest.`),this.trigger("error");return}if(i.startsWith("data:")){this.decodeDataUriManifest_(i.substring(i.indexOf(",")+1));return}this.steeringManifest.reloadUri=en(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const i=e?t:this.getRequestURI(t);if(!i){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}const n={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:n}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(r,o)=>{if(r){if(o.status===410){this.logger_(`manifest request 410 ${r}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),this.excludedSteeringManifestURLs.add(i);return}if(o.status===429){const d=o.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${r}.`),this.logger_(`content steering will retry in ${d} seconds.`),this.startTTLTimeout_(parseInt(d,10));return}this.logger_(`manifest failed to load ${r}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:n});let u;try{u=JSON.parse(this.request_.responseText)}catch(d){const f={errorType:Te.Error.StreamingContentSteeringParserError,error:d};this.trigger({type:"error",metadata:f})}this.assignSteeringProperties_(u);const c={contentSteeringInfo:n.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:c}),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new se.URL(e),i=new se.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(se.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new se.URL(e),i=this.getPathway(),n=this.getBandwidth_();if(i){const r=`_${this.manifestType_}_pathway`;t.searchParams.set(r,i)}if(n){const r=`_${this.manifestType_}_throughput`;t.searchParams.set(r,n)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger("error");return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const i=(n=>{for(const r of n)if(this.availablePathways_.has(r))return r;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==i&&(this.currentPathway=i,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=n=>this.excludedSteeringManifestURLs.has(n);if(this.proxyServerUrl_){const n=this.setProxyServerUrl_(e);if(!t(n))return n}const i=this.setSteeringParams_(e);return t(i)?null:i}startTTLTimeout_(e=this.steeringManifest.ttl){const t=e*1e3;this.ttlTimeout_=se.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){se.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new b1}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(en(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}};const W4=(s,e)=>{let t=null;return(...i)=>{clearTimeout(t),t=setTimeout(()=>{s.apply(null,i)},e)}},X4=10;let uo;const Q4=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],Z4=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},J4=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:o,bufferBasedABR:u,log:c}){if(!i)return Te.log.warn("We received no playlist to switch to. Please check your stream."),!1;const d=`allowing switch ${s&&s.id||"null"} -> ${i.id}`;if(!s)return c(`${d} as current playlist is not set`),!0;if(i.id===s.id)return!1;const f=!!Ou(e,t).length;if(!s.endList)return!f&&typeof s.partTargetDuration=="number"?(c(`not ${d} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(c(`${d} as current playlist is live`),!0);const m=zT(e,t),g=u?us.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:us.MAX_BUFFER_LOW_WATER_LINE;if(ob)&&m>=n){let _=`${d} as forwardBuffer >= bufferLowWaterLine (${m} >= ${n})`;return u&&(_+=` and next bandwidth > current bandwidth (${v} > ${b})`),c(_),!0}return c(`not ${d} as no switching criteria met`),!1};class eB extends Te.EventTarget{constructor(e){super(),this.fastQualityChange_=W4(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:n,bandwidth:r,externVhs:o,useCueTags:u,playlistExclusionDuration:c,enableLowInitialPlaylist:d,sourceType:f,cacheEncryptionKeys:m,bufferBasedABR:g,leastPixelDiffSelector:v,captionServices:b,experimentalUseMMS:_}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:E}=e;(E===null||typeof E>"u")&&(E=1/0),uo=o,this.bufferBasedABR=!!g,this.leastPixelDiffSelector=!!v,this.withCredentials=i,this.tech_=n,this.vhs_=n.vhs,this.player_=e.player_,this.sourceType_=f,this.useCueTags_=u,this.playlistExclusionDuration=c,this.maxPlaylistRetries=E,this.enableLowInitialPlaylist=d,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:E,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=K4(),_&&se.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new se.ManagedMediaSource,this.usingManagedMediaSource_=!0,Te.log("Using ManagedMediaSource")):se.MediaSource&&(this.mediaSource=new se.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=ds(),this.hasPlayed_=!1,this.syncController_=new P4(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new B4,this.sourceUpdater_=new sw(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new M4,this.keyStatusMap_=new Map;const L={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:b,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:r,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:m,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new Nv(t,this.vhs_,Kt(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Pu(t,this.vhs_,Kt(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Uv(Kt(L,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new Uv(Kt(L,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new L4(Kt(L,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((F,U)=>{function V(){n.off("vttjserror",B),F()}function B(){n.off("vttjsloaded",V),U()}n.one("vttjsloaded",V),n.one("vttjserror",B),n.addWebVttScript_()})}),e);const I=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new Y4(this.vhs_.xhr,I),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),Q4.forEach(F=>{this[F+"_"]=Z4.bind(this,F)}),this.logger_=$n("pc"),this.triggeredFmp4Usage=!1,this.tech_.preload()==="none"?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const w=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(w,()=>{const F=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-F,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const n=this.media(),r=n&&(n.id||n.uri),o=e&&(e.id||e.uri);if(r&&r!==o){this.logger_(`switch media ${r} -> ${o} from ${t}`);const u={renditionInfo:{id:o,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:u}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],i=t?t.activeGroup():null,n=this.contentSteeringController_.getPathway();if(i&&n){const o=(i.length?i[0].playlists:i.playlists).filter(u=>u.attributes.serviceLocation===n);o.length&&this.mediaTypes_[e].activePlaylistLoader.media(o[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=se.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(se.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const i=e.mediaGroups.AUDIO,n=Object.keys(i);let r;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)r=this.mediaTypes_.AUDIO.activeTrack();else{const u=i.main||n.length&&i[n[0]];for(const c in u)if(u[c].default){r={label:c};break}}if(!r)return t;const o=[];for(const u in i)if(i[u][r.label]){const c=i[u][r.label];if(c.playlists&&c.playlists.length)o.push.apply(o,c.playlists);else if(c.uri)o.push(c);else if(e.playlists.length)for(let d=0;d{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;kv(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,t.endList&&this.tech_.preload()!=="none"&&(this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.mainSegmentLoader_.load()),z4({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),t),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let t=this.mainPlaylistLoader_.media();if(!t){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let i;if(this.enableLowInitialPlaylist&&(i=this.selectInitialPlaylist()),i||(i=this.selectPlaylist()),!i||!this.shouldSwitchToMedia_(i)||(this.initialMedia_=i,this.switchMedia_(this.initialMedia_,"initial"),!(this.sourceType_==="vhs-json"&&this.initialMedia_.segments)))return;t=this.initialMedia_}this.handleUpdatedMediaPlaylist(t)}),this.mainPlaylistLoader_.on("error",()=>{const t=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:t.playlist,error:t})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;kv(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,this.sourceType_==="dash"&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const t=this.mainPlaylistLoader_.media();if(t.lastExcludeReason_==="playlist-unchanged")return;this.stuckAtPlaylistEnd_(t)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(t=>{this.mainPlaylistLoader_.on(t,i=>{this.player_.trigger($i({},i))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const i=e.mediaGroups||{};let n=!0;const r=Object.keys(i.AUDIO);for(const o in i.AUDIO)for(const u in i.AUDIO[o])i.AUDIO[o][u].uri||(n=!1);n&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),uo.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),r.length&&Object.keys(i.AUDIO[r[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),n=this.bufferLowWaterLine(),r=this.bufferHighWaterLine(),o=this.tech_.buffered();return J4({buffered:o,currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const i=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:i.playlist,error:i})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const i=this.audioSegmentLoader_.pendingSegment_;if(!i||!i.segment||!i.segment.syncInfo)return;const n=i.segment.syncInfo.end+.01;this.tech_.setCurrentTime(n)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",i=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:X4}))});const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const i=this.getCodecsOrExclude_();i&&this.sourceUpdater_.addOrChangeSourceBuffers(i)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(i=>{this.mainSegmentLoader_.on(i,n=>{this.player_.trigger($i({},n))}),this.audioSegmentLoader_.on(i,n=>{this.player_.trigger($i({},n))}),this.subtitleSegmentLoader_.on(i,n=>{this.player_.trigger($i({},n))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_("skipping fastQualityChange because new media is same as old");return}this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime(){})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();!t||t.hasVideo?e=e&&this.audioSegmentLoader_.ended_:e=this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const i=this.syncController_.getExpiredTime(e,this.duration());if(i===null)return!1;const n=uo.Playlist.playlistEnd(e,i),r=this.tech_.currentTime(),o=this.tech_.buffered();if(!o.length)return n-r<=Ir;const u=o.end(o.length-1);return u-r<=Ir&&n-u<=Ir}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,this.mediaSource.readyState!=="open"?this.trigger("error"):this.sourceUpdater_.endOfStream("network");return}e.playlistErrors_++;const n=this.mainPlaylistLoader_.main.playlists,r=n.filter($m),o=r.length===1&&r[0]===e;if(n.length===1&&i!==1/0)return Te.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(o);if(o){if(this.main().contentSteering){const b=this.pathwayAttribute_(e),_=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(b),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(b)},_);return}let v=!1;n.forEach(b=>{if(b===e)return;const _=b.excludeUntil;typeof _<"u"&&_!==1/0&&(v=!0,delete b.excludeUntil)}),v&&(Te.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let u;e.playlistErrors_>this.maxPlaylistRetries?u=1/0:u=Date.now()+i*1e3,e.excludeUntil=u,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const c=this.selectPlaylist();if(!c){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}const d=t.internal?this.logger_:Te.log.warn,f=t.message?" "+t.message:"";d(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${f} Switching to playlist ${c.id}.`),c.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),c.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const m=c.targetDuration/2*1e3||5*1e3,g=typeof c.lastRequest=="number"&&Date.now()-c.lastRequest<=m;return this.switchMedia_(c,"exclude",o||g)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const i=[],n=e==="all";(n||e==="main")&&i.push(this.mainPlaylistLoader_);const r=[];(n||e==="audio")&&r.push("AUDIO"),(n||e==="subtitle")&&(r.push("CLOSED-CAPTIONS"),r.push("SUBTITLES")),r.forEach(o=>{const u=this.mediaTypes_[o]&&this.mediaTypes_[o].activePlaylistLoader;u&&i.push(u)}),["main","audio","subtitle"].forEach(o=>{const u=this[`${o}SegmentLoader_`];u&&(e===o||e==="all")&&i.push(u)}),i.forEach(o=>t.forEach(u=>{typeof o[u]=="function"&&o[u]()}))}setCurrentTime(e){const t=Ou(this.tech_.buffered(),e);if(!(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media())||!this.mainPlaylistLoader_.media().segments)return 0;if(t&&t.length)return e;this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:uo.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){const i=e.media();if(!i)return null;const n=this.syncController_.getMediaSequenceSync(t);if(n&&n.isReliable){const u=n.start,c=n.end;if(!isFinite(u)||!isFinite(c))return null;const d=uo.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),f=Math.max(u,c-d);return ds([[u,f]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(r===null)return null;const o=uo.Playlist.seekable(i,r,uo.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return o.length?o:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),n=e.end(0),r=t.start(0),o=t.end(0);return r>n||i>o?e:ds([[Math.max(i,r),Math.min(n,o)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const i=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_||i&&i.length&&this.seekable_.length&&i.start(0)===this.seekable_.start(0)&&i.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${gD(this.seekable_)}]`);const n={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:n}),this.tech_.trigger("seekablechanged")}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),this.mediaSource.readyState!=="open"){this.updateDuration_=this.updateDuration.bind(this,e),this.mediaSource.addEventListener("sourceopen",this.updateDuration_);return}if(e){const n=this.seekable();if(!n.length)return;(isNaN(this.mediaSource.duration)||this.mediaSource.duration0&&(i=Math.max(i,t.end(t.length-1))),this.mediaSource.duration!==i&&this.sourceUpdater_.setDuration(i)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{const t=this.mediaTypes_[e].groups;for(const i in t)t[i].forEach(n=>{n.playlistLoader&&n.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),i=e?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return!(!t||!i)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const i=jd(this.main(),t),n={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=i.video||e.main.videoCodec||HP),e.main.isMuxed&&(n.video+=`,${i.audio||e.main.audioCodec||uE}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(n.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||uE,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!n.audio&&!n.video){this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}const o=(d,f)=>d?Nd(f,this.usingManagedMediaSource_):fy(f),u={};let c;if(["video","audio"].forEach(function(d){if(n.hasOwnProperty(d)&&!o(e[d].isFmp4,n[d])){const f=e[d].isFmp4?"browser":"muxer";u[f]=u[f]||[],u[f].push(n[d]),d==="audio"&&(c=f)}}),r&&c&&t.attributes.AUDIO){const d=t.attributes.AUDIO;this.main().playlists.forEach(f=>{(f.attributes&&f.attributes.AUDIO)===d&&f!==t&&(f.excludeUntil=1/0)}),this.logger_(`excluding audio group ${d} as ${c} does not support codec(s): "${n.audio}"`)}if(Object.keys(u).length){const d=Object.keys(u).reduce((f,m)=>(f&&(f+=", "),f+=`${m} does not support codec(s): "${u[m].join(",")}"`,f),"")+".";this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:d},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const d=[];if(["video","audio"].forEach(f=>{const m=(Ar(this.sourceUpdater_.codecs[f]||"")[0]||{}).type,g=(Ar(n[f]||"")[0]||{}).type;m&&g&&m.toLowerCase()!==g.toLowerCase()&&d.push(`"${this.sourceUpdater_.codecs[f]}" -> "${n[f]}"`)}),d.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${d.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0});return}}return n}tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!=="open"||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach(i=>{const n=e[i];if(t.indexOf(n.id)!==-1)return;t.push(n.id);const r=jd(this.main,n),o=[];r.audio&&!fy(r.audio)&&!Nd(r.audio,this.usingManagedMediaSource_)&&o.push(`audio codec ${r.audio}`),r.video&&!fy(r.video)&&!Nd(r.video,this.usingManagedMediaSource_)&&o.push(`video codec ${r.video}`),r.text&&r.text==="stpp.ttml.im1t"&&o.push(`text codec ${r.text}`),o.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${o.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=Wd(Ar(e)),r=i1(n),o=n.video&&Ar(n.video)[0]||null,u=n.audio&&Ar(n.audio)[0]||null;Object.keys(i).forEach(c=>{const d=i[c];if(t.indexOf(d.id)!==-1||d.excludeUntil===1/0)return;t.push(d.id);const f=[],m=jd(this.mainPlaylistLoader_.main,d),g=i1(m);if(!(!m.audio&&!m.video)){if(g!==r&&f.push(`codec count "${g}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const v=m.video&&Ar(m.video)[0]||null,b=m.audio&&Ar(m.audio)[0]||null;v&&o&&v.type.toLowerCase()!==o.type.toLowerCase()&&f.push(`video codec "${v.type}" !== "${o.type}"`),b&&u&&b.type.toLowerCase()!==u.type.toLowerCase()&&f.push(`audio codec "${b.type}" !== "${u.type}"`)}f.length&&(d.excludeUntil=1/0,this.logger_(`excluding ${d.id}: ${f.join(" && ")}`))}})}updateAdCues_(e){let t=0;const i=this.seekable();i.length&&(t=i.start(0)),k4(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=us.GOAL_BUFFER_LENGTH,i=us.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,us.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=us.BUFFER_LOW_WATER_LINE,i=us.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,us.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,us.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:n)}bufferHighWaterLine(){return us.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){c1(this.inbandTextTracks_,"com.apple.streaming",this.tech_),c4({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();c1(this.inbandTextTracks_,e,this.tech_),o4({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:n,videoDuration:i})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(t=>{this.contentSteeringController_.on(t,i=>{this.trigger($i({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),o=[];for(const u of t.playlists){const c=u.attributes.serviceLocation;if(c&&(o.push(c),!r.has(c)))return!0}return!!(!o.length&&r.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const i=this.main().playlists,n=new Set;let r=!1;Object.keys(i).forEach(o=>{const u=i[o],c=this.pathwayAttribute_(u),d=c&&e!==c;u.excludeUntil===1/0&&u.lastExcludeReason_==="content-steering"&&!d&&(delete u.excludeUntil,delete u.lastExcludeReason_,r=!0);const m=!u.excludeUntil&&u.excludeUntil!==1/0;!n.has(u.id)&&d&&m&&(n.add(u.id),u.excludeUntil=1/0,u.lastExcludeReason_="content-steering",this.logger_(`excluding ${u.id} for ${u.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_==="DASH"&&Object.keys(this.mediaTypes_).forEach(o=>{const u=this.mediaTypes_[o];if(u.activePlaylistLoader){const c=u.activePlaylistLoader.media_;c&&c.attributes.serviceLocation!==e&&(r=!0)}}),r&&this.changeSegmentPathway_()}handlePathwayClones_(){const t=this.main().playlists,i=this.contentSteeringController_.currentPathwayClones,n=this.contentSteeringController_.nextPathwayClones;if(i&&i.size||n&&n.size){for(const[o,u]of i.entries())n.get(o)||(this.mainPlaylistLoader_.updateOrDeleteClone(u),this.contentSteeringController_.excludePathway(o));for(const[o,u]of n.entries()){const c=i.get(o);if(!c){t.filter(f=>f.attributes["PATHWAY-ID"]===u["BASE-ID"]).forEach(f=>{this.mainPlaylistLoader_.addClonePathway(u,f)}),this.contentSteeringController_.addAvailablePathway(o);continue}this.equalPathwayClones_(c,u)||(this.mainPlaylistLoader_.updateOrDeleteClone(u,!0),this.contentSteeringController_.addAvailablePathway(o))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...n])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const i=e["URI-REPLACEMENT"].PARAMS,n=t["URI-REPLACEMENT"].PARAMS;for(const r in i)if(i[r]!==n[r])return!1;for(const r in n)if(i[r]!==n[r])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_==="DASH"&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(i=>{const n=this.mainPlaylistLoader_.getKeyIdSet(i);!n||!n.size||n.forEach(r=>{const o="usable",u=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===o,c=i.lastExcludeReason_===t&&i.excludeUntil===1/0;u?u&&c&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${r} is ${o}`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${r} doesn't exist in the keyStatusMap or is not ${o}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(i=>{const n=i&&i.attributes&&i.attributes.RESOLUTION&&i.attributes.RESOLUTION.height<720,r=i.excludeUntil===1/0&&i.lastExcludeReason_===t;n&&r&&(delete i.excludeUntil,Te.log.warn(`enabling non-HD playlist ${i.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){const r=(typeof e=="string"?e:D4(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${r} added to the keyStatusMap`),this.keyStatusMap_.set(r,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}const tB=(s,e,t)=>i=>{const n=s.main.playlists[e],r=YT(n),o=$m(n);if(typeof i>"u")return o;i?delete n.disabled:n.disabled=!0;const u={renditionInfo:{id:e,bandwidth:n.attributes.BANDWIDTH,resolution:n.attributes.RESOLUTION,codecs:n.attributes.CODECS},cause:"fast-quality"};return i!==o&&!r&&(i?(t(n),s.trigger({type:"renditionenabled",metadata:u})):s.trigger({type:"renditiondisabled",metadata:u})),i};class iB{constructor(e,t,i){const{playlistController_:n}=e,r=n.fastQualityChange_.bind(n);if(t.attributes){const o=t.attributes.RESOLUTION;this.width=o&&o.width,this.height=o&&o.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=jd(n.main(),t),this.playlist=t,this.id=i,this.enabled=tB(e.playlists,t.id,r)}}const sB=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=hh(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!YT(i)).map((i,n)=>new iB(s,i,i.id)):[]}},_1=["seeking","seeked","pause","playing","error"];class nB extends Te.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=$n("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),o=this.playlistController_,u=["main","subtitle","audio"],c={};u.forEach(f=>{c[f]={reset:()=>this.resetSegmentDownloads_(f),updateend:()=>this.checkSegmentDownloads_(f)},o[`${f}SegmentLoader_`].on("appendsdone",c[f].updateend),o[`${f}SegmentLoader_`].on("playlistupdate",c[f].reset),this.tech_.on(["seeked","seeking"],c[f].reset)});const d=f=>{["main","audio"].forEach(m=>{o[`${m}SegmentLoader_`][f]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),d("off"))},this.clearSeekingAppendCheck_=()=>d("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),d("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",n),this.tech_.on(_1,r),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",n),this.tech_.off(_1,r),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),u.forEach(f=>{o[`${f}SegmentLoader_`].off("appendsdone",c[f].updateend),o[`${f}SegmentLoader_`].off("playlistupdate",c[f].reset),this.tech_.off(["seeked","seeking"],c[f].reset)}),this.checkCurrentTimeTimeout_&&se.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&se.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=se.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,i=t[`${e}SegmentLoader_`],n=i.buffered_(),r=G3(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,r){const o={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:o}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:gl(n)}),!(this[`${e}StalledDownloads_`]<10)&&(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),e!=="subtitle"&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+Ir>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(ds([this.lastRecordedTime,e]));const i={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:i}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const t=this.seekable(),i=this.tech_.currentTime(),n=this.afterSeekableWindow_(t,i,this.media(),this.allowSeeksWithinUnsafeLiveWindow);let r;if(n&&(r=t.end(t.length-1)),this.beforeSeekableWindow_(t,i)){const b=t.start(0);r=b+(b===t.end(0)?0:Ir)}if(typeof r<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${gD(t)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;const o=this.playlistController_.sourceUpdater_,u=this.tech_.buffered(),c=o.audioBuffer?o.audioBuffered():null,d=o.videoBuffer?o.videoBuffered():null,f=this.media(),m=f.partTargetDuration?f.partTargetDuration:(f.targetDuration-Lr)*2,g=[c,d];for(let b=0;b ${i.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const u=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${u}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(u),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const i=this.tech_.vhs.playlistController_.sourceUpdater_,n=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const o=Yf(n,t);return o.length>0?(this.logger_(`Stopped at ${t} and seeking to ${o.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,i,n=!1){if(!e.length)return!1;let r=e.end(e.length-1)+Ir;const o=!i.endList,u=typeof i.partTargetDuration=="number";return o&&(u||n)&&(r=e.end(e.length-1)+i.targetDuration*3),t>r}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t2)return{start:r,end:o}}return null}}const rB={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},ow=function(s,e){let t=0,i=0;const n=Kt(rB,e);s.ready(()=>{s.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const r=function(){i&&s.currentTime(i)},o=function(f){f!=null&&(i=s.duration()!==1/0&&s.currentTime()||0,s.one("loadedmetadata",r),s.src(f),s.trigger({type:"usage",name:"vhs-error-reload"}),s.play())},u=function(){if(Date.now()-t{Object.defineProperty(Si,s,{get(){return Te.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),us[s]},set(e){if(Te.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){Te.log.warn(`value of Vhs.${s} must be greater than or equal to 0`);return}us[s]=e}})});const uw="videojs-vhs",cw=function(s,e){const t=e.media();let i=-1;for(let n=0;n{s.addQualityLevel(t)}),cw(s,e.playlists)};Si.canPlaySource=function(){return Te.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const hB=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=Wd(Ar(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const n=Xu(i.video),r=Xu(i.audio),o={};for(const u in s)o[u]={},r&&(o[u].audioContentType=r),n&&(o[u].videoContentType=n),e.contentProtection&&e.contentProtection[u]&&e.contentProtection[u].pssh&&(o[u].pssh=e.contentProtection[u].pssh),typeof s[u]=="string"&&(o[u].url=s[u]);return Kt(s,o)},fB=(s,e)=>s.reduce((t,i)=>{if(!i.contentProtection)return t;const n=e.reduce((r,o)=>{const u=i.contentProtection[o];return u&&u.pssh&&(r[o]={pssh:u.pssh}),r},{});return Object.keys(n).length&&t.push(n),t},[]),pB=({player:s,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!s.eme.initializeMediaKeys)return Promise.resolve();const n=t?i.concat([t]):i,r=fB(n,Object.keys(e)),o=[],u=[];return r.forEach(c=>{u.push(new Promise((d,f)=>{s.tech_.one("keysessioncreated",d)})),o.push(new Promise((d,f)=>{s.eme.initializeMediaKeys({keySystems:c},m=>{if(m){f(m);return}d()})}))}),Promise.race([Promise.all(o),Promise.race(u)])},mB=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const n=hB(e,t,i);return n?(s.currentSource().keySystems=n,n&&!s.eme?(Te.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},dw=()=>{if(!se.localStorage)return null;const s=se.localStorage.getItem(uw);if(!s)return null;try{return JSON.parse(s)}catch{return null}},gB=s=>{if(!se.localStorage)return!1;let e=dw();e=e?Kt(e,s):s;try{se.localStorage.setItem(uw,JSON.stringify(e))}catch{return!1}return e},yB=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,hw=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},fw=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},pw=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},mw=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};Si.supportsNativeHls=(function(){if(!qe||!qe.createElement)return!1;const s=qe.createElement("video");return Te.getTech("Html5").isSupported()?["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(t){return/maybe|probably/i.test(s.canPlayType(t))}):!1})();Si.supportsNativeDash=(function(){return!qe||!qe.createElement||!Te.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(qe.createElement("video").canPlayType("application/dash+xml"))})();Si.supportsTypeNatively=s=>s==="hls"?Si.supportsNativeHls:s==="dash"?Si.supportsNativeDash:!1;Si.isSupported=function(){return Te.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};Si.xhr.onRequest=function(s){hw(Si.xhr,s)};Si.xhr.onResponse=function(s){fw(Si.xhr,s)};Si.xhr.offRequest=function(s){pw(Si.xhr,s)};Si.xhr.offResponse=function(s){mw(Si.xhr,s)};const vB=Te.getComponent("Component");class gw extends vB{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=$n("VhsHandler"),t.options_&&t.options_.playerId){const n=Te.getPlayer(t.options_.playerId);this.player_=n}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(qe,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const r=qe.fullscreenElement||qe.webkitFullscreenElement||qe.mozFullScreenElement||qe.msFullscreenElement;r&&r.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,"seeking",function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,"error",function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,"play",this.play)}setOptions_(e={}){if(this.options_=Kt(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions!==!1,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.usePlayerObjectFit=this.options_.usePlayerObjectFit||!1,this.options_.useBandwidthFromLocalStorage=typeof this.source_.useBandwidthFromLocalStorage<"u"?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=typeof this.options_.useNetworkInformationApi<"u"?this.options_.useNetworkInformationApi:!0,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=this.options_.llhls!==!1,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,typeof this.options_.playlistExclusionDuration!="number"&&(this.options_.playlistExclusionDuration=60),typeof this.options_.bandwidth!="number"&&this.options_.useBandwidthFromLocalStorage){const i=dw();i&&i.bandwidth&&(this.options_.bandwidth=i.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),i&&i.throughput&&(this.options_.throughput=i.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}typeof this.options_.bandwidth!="number"&&(this.options_.bandwidth=us.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===us.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","usePlayerObjectFit","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(i=>{typeof this.source_[i]<"u"&&(this.options_[i]=this.source_[i])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio,this.usePlayerObjectFit=this.options_.usePlayerObjectFit;const t=this.options_.customPixelRatio;typeof t=="number"&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=yB(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=Si,this.options_.sourceType=BA(t),this.options_.seekTo=r=>{this.tech_.setCurrentTime(r)},this.options_.player_=this.player_,this.playlistController_=new eB(this.options_);const i=Kt({liveRangeSafeTimeDelta:Ir},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new nB(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const r=Te.players[this.tech_.options_.playerId];let o=this.playlistController_.error;typeof o=="object"&&!o.code?o.code=3:typeof o=="string"&&(o={message:o,code:3}),r.error(o)});const n=this.options_.bufferBasedABR?Si.movingAverageBandwidthSelector(.55):Si.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=Si.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(r){this.playlistController_.selectPlaylist=r.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(r){this.playlistController_.mainSegmentLoader_.throughput.rate=r,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let r=this.playlistController_.mainSegmentLoader_.bandwidth;const o=se.navigator.connection||se.navigator.mozConnection||se.navigator.webkitConnection,u=1e7;if(this.options_.useNetworkInformationApi&&o){const c=o.downlink*1e3*1e3;c>=u&&r>=u?r=Math.max(r,c):r=c}return r},set(r){this.playlistController_.mainSegmentLoader_.bandwidth=r,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const r=1/(this.bandwidth||1);let o;return this.throughput>0?o=1/this.throughput:o=0,Math.floor(1/(r+o))},set(){Te.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>gl(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>gl(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&gB({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{sB(this)}),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",()=>{this.setupEme_()}),this.on(this.playlistController_,"progress",function(){this.tech_.trigger("progress")}),this.on(this.playlistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=se.URL.createObjectURL(this.playlistController_.mediaSource),(Te.browser.IS_ANY_SAFARI||Te.browser.IS_IOS)&&this.options_.overrideNative&&this.options_.sourceType==="hls"&&typeof this.tech_.addSourceElement=="function"?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),pB({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(t=>{this.logger_("error while creating EME key session",t),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=mB({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on("keystatuschange",i=>{this.playlistController_.updatePlaylistByKeyStatus(i.keyId,i.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){const e=Te.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{dB(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{cw(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":lw,"mux.js":oB,"mpd-parser":lB,"m3u8-parser":uB,"aes-decrypter":cB}}version(){return this.constructor.version()}canChangeType(){return sw.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&se.URL.revokeObjectURL&&(se.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return x5({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return $D({programTime:e,playlist:this.playlistController_.media(),retryCount:n,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{hw(this.xhr,e)},this.xhr.onResponse=e=>{fw(this.xhr,e)},this.xhr.offRequest=e=>{pw(this.xhr,e)},this.xhr.offResponse=e=>{mw(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){const e=["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"],t=["gapjumped","playedrangeschanged"];e.forEach(i=>{this.playlistController_.on(i,n=>{this.player_.trigger($i({},n))})}),t.forEach(i=>{this.playbackWatcher_.on(i,n=>{this.player_.trigger($i({},n))})})}}const Xp={name:"videojs-http-streaming",VERSION:lw,canHandleSource(s,e={}){const t=Kt(Te.options,e);return!t.vhs.experimentalUseMMS&&!Nd("avc1.4d400d,mp4a.40.2",!1)?!1:Xp.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=Kt(Te.options,t);return e.vhs=new gw(s,e,i),e.vhs.xhr=MD(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=BA(s);if(!t)return"";const i=Xp.getOverrideNative(e);return!Si.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(s={}){const{vhs:e={}}=s,t=!(Te.browser.IS_ANY_SAFARI||Te.browser.IS_IOS),{overrideNative:i=t}=e;return i}},TB=()=>Nd("avc1.4d400d,mp4a.40.2",!0);TB()&&Te.getTech("Html5").registerSourceHandler(Xp,0);Te.VhsHandler=gw;Te.VhsSourceHandler=Xp;Te.Vhs=Si;Te.use||Te.registerComponent("Vhs",Si);Te.options.vhs=Te.options.vhs||{};(!Te.getPlugin||!Te.getPlugin("reloadSourceOnError"))&&Te.registerPlugin("reloadSourceOnError",aB);const Iu=s=>(s||"").replaceAll("\\","/").split("/").pop()||"",yw=s=>s.startsWith("HOT ")?s.slice(4):s;function x1(s){if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`}function bB(s){if(typeof s!="number"||!Number.isFinite(s)||s<=0)return"—";const e=["B","KB","MB","GB","TB"];let t=s,i=0;for(;t>=1024&&i=100?0:t>=10?1:2;return`${t.toFixed(n)} ${e[i]}`}const _B=s=>{const e=Iu(s||""),t=yw(e);if(!t)return"—";const i=t.replace(/\.[^.]+$/,""),n=i.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(n?.[1])return n[1];const r=i.lastIndexOf("_");return r>0?i.slice(0,r):i},xB=s=>{const e=s,t=e.sizeBytes??e.fileSizeBytes??e.bytes??e.size??null;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null};function al(...s){return s.filter(Boolean).join(" ")}function SB({job:s,expanded:e,onClose:t,onToggleExpand:i,className:n,isHot:r=!1,isFavorite:o=!1,isLiked:u=!1,onDelete:c,onToggleHot:d,onToggleFavorite:f,onToggleLike:m}){const g=j.useMemo(()=>Iu(s.output?.trim()||"")||s.id,[s.output,s.id]),v=j.useMemo(()=>Iu(s.output?.trim()||""),[s.output]),b=v.startsWith("HOT "),_=j.useMemo(()=>_B(s.output),[s.output]),E=j.useMemo(()=>yw(v),[v]),L=j.useMemo(()=>{const Me=Date.parse(String(s.startedAt||"")),Je=Date.parse(String(s.endedAt||""));if(Number.isFinite(Me)&&Number.isFinite(Je)&&Je>Me)return x1(Je-Me);const st=s.durationSeconds;return typeof st=="number"&&Number.isFinite(st)&&st>0?x1(st*1e3):"—"},[s]),I=j.useMemo(()=>bB(xB(s)),[s]);j.useEffect(()=>{const Me=Je=>Je.key==="Escape"&&t();return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[t]);const w=j.useMemo(()=>{if(s.status==="running")return{src:`/api/record/preview?id=${encodeURIComponent(s.id)}&file=index_hq.m3u8`,type:"application/x-mpegURL"};const Me=Iu(s.output?.trim()||"");return Me?{src:`/api/record/video?file=${encodeURIComponent(Me)}`,type:"video/mp4"}:{src:`/api/record/video?id=${encodeURIComponent(s.id)}`,type:"video/mp4"}},[s.id,s.output,s.status]),F=j.useRef(null),U=j.useRef(null),V=j.useRef(null),[B,q]=j.useState(!1),[k,R]=j.useState(56);j.useEffect(()=>{if(!B)return;const Me=U.current;if(!Me||Me.isDisposed?.())return;const Je=Me.el();if(!Je)return;const st=Je.querySelector(".vjs-control-bar");if(!st)return;const Ct=()=>{const ut=Math.round(st.getBoundingClientRect().height||0);ut>0&&R(ut)};Ct();let Fe=null;return typeof ResizeObserver<"u"&&(Fe=new ResizeObserver(Ct),Fe.observe(st)),window.addEventListener("resize",Ct),()=>{window.removeEventListener("resize",Ct),Fe?.disconnect()}},[B,e]),j.useEffect(()=>q(!0),[]),j.useLayoutEffect(()=>{if(!B||!F.current||U.current)return;const Me=document.createElement("video");Me.className="video-js vjs-big-play-centered w-full h-full",Me.setAttribute("playsinline","true"),F.current.appendChild(Me),V.current=Me;const Je=Te(Me,{autoplay:!0,muted:!0,controls:!0,preload:"metadata",playsinline:!0,responsive:!0,fluid:!1,fill:!0,controlBar:{skipButtons:{backward:10,forward:10},children:["playToggle","progressControl","currentTimeDisplay","timeDivider","durationDisplay","volumePanel","playbackRateMenuButton","fullscreenToggle"]},playbackRates:[.5,1,1.25,1.5,2]});return U.current=Je,()=>{try{U.current&&(U.current.dispose(),U.current=null)}finally{V.current&&(V.current.remove(),V.current=null)}}},[B]),j.useEffect(()=>{if(!B)return;const Me=U.current;if(!Me||Me.isDisposed?.())return;const Je=Me.currentTime()||0;Me.muted(!0),Me.src({src:w.src,type:w.type});const st=()=>{const Ct=Me.play?.();Ct&&typeof Ct.catch=="function"&&Ct.catch(()=>{})};Me.one("loadedmetadata",()=>{Me.isDisposed?.()||(Je>0&&w.type!=="application/x-mpegURL"&&Me.currentTime(Je),st())}),st()},[B,w.src,w.type]),j.useEffect(()=>{const Me=U.current;!Me||Me.isDisposed?.()||queueMicrotask(()=>Me.trigger("resize"))},[e]);const K=j.useCallback(()=>{const Me=U.current;if(!(!Me||Me.isDisposed?.())){try{Me.pause(),Me.reset?.()}catch{}try{Me.src({src:"",type:"video/mp4"}),Me.load?.()}catch{}}},[]);j.useEffect(()=>{const Me=Je=>{const Ct=(Je.detail?.file??"").trim();if(!Ct)return;const Fe=Iu(s.output?.trim()||"");Fe&&Fe===Ct&&K()};return window.addEventListener("player:release",Me),()=>window.removeEventListener("player:release",Me)},[s.output,K]),j.useEffect(()=>{const Me=Je=>{const Ct=(Je.detail?.file??"").trim();if(!Ct)return;const Fe=Iu(s.output?.trim()||"");Fe&&Fe===Ct&&(K(),t())};return window.addEventListener("player:close",Me),()=>window.removeEventListener("player:close",Me)},[s.output,K,t]);const X=!e,[ee,le]=j.useState(!1),[ae,Y]=j.useState(!1),[Q,te]=j.useState(!1),[oe,de]=j.useState(!1);j.useEffect(()=>{if(!B)return;const Me=U.current;if(!Me||Me.isDisposed?.())return;const Je=()=>{try{de(!!Me.paused?.())}catch{de(!1)}};return Je(),Me.on("play",Je),Me.on("pause",Je),()=>{try{Me.off("play",Je),Me.off("pause",Je)}catch{}}},[B]);const $=j.useRef(null),ie=j.useCallback(()=>{$.current&&window.clearTimeout($.current),$.current=null,te(!1)},[]),he=j.useCallback(()=>{te(!0),$.current&&window.clearTimeout($.current),$.current=window.setTimeout(()=>{te(!1),$.current=null},500)},[]);j.useEffect(()=>{e&&ae&&he()},[e,ae,he]),j.useEffect(()=>()=>{$.current&&window.clearTimeout($.current)},[]),j.useEffect(()=>{e||te(!1)},[e]),j.useEffect(()=>{const Me=window.matchMedia?.("(hover: hover) and (pointer: fine)"),Je=()=>Y(!!Me?.matches);return Je(),Me?.addEventListener?.("change",Je),()=>Me?.removeEventListener?.("change",Je)},[]),j.useEffect(()=>{X||le(!1)},[X]);const Ce=X&&(ae?ee:!0);if(!B)return null;const be="inline-flex items-center justify-center rounded-md bg-black/40 p-2 text-white backdrop-blur hover:bg-black/55 transition focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed",Ee=O.jsxs("div",{className:"flex items-center gap-1",children:[O.jsx("button",{type:"button",className:be,title:r?"HOT entfernen":"Als HOT markieren","aria-label":r?"HOT entfernen":"Als HOT markieren",onClick:async Me=>{Me.stopPropagation(),K(),await new Promise(st=>setTimeout(st,150)),await d?.(s),await new Promise(st=>setTimeout(st,0));const Je=U.current;if(Je&&!Je.isDisposed?.()){const st=Je.play?.();st&&typeof st.catch=="function"&&st.catch(()=>{})}},disabled:!d,children:O.jsx(CA,{className:al("h-5 w-5",r?"text-amber-300":"text-white")})}),O.jsx("button",{type:"button",className:be,title:o?"Favorit entfernen":"Als Favorit markieren","aria-label":o?"Favorit entfernen":"Als Favorit markieren",onClick:Me=>{Me.stopPropagation(),f?.(s)},disabled:!f,children:(()=>{const Me=o?kA:wA;return O.jsx(Me,{className:al("h-5 w-5",o?"text-amber-300":"text-white/90")})})()}),O.jsx("button",{type:"button",className:be,title:u?"Gefällt mir entfernen":"Als Gefällt mir markieren","aria-label":u?"Gefällt mir entfernen":"Als Gefällt mir markieren",onClick:Me=>{Me.stopPropagation(),m?.(s)},disabled:!m,children:(()=>{const Me=u?IA:DA;return O.jsx(Me,{className:al("h-5 w-5",u?"text-rose-300":"text-white/90")})})()}),O.jsx("button",{type:"button",className:"inline-flex items-center justify-center rounded-md bg-red-600/35 p-2 text-white backdrop-blur hover:bg-red-600/55 transition focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed",title:"Löschen","aria-label":"Löschen",onClick:async Me=>{Me.stopPropagation(),K(),t(),await new Promise(Je=>setTimeout(Je,150)),await c?.(s)},disabled:!c,children:O.jsx(Md,{className:"h-5 w-5"})})]}),Ve=e&&(!ae||Q||oe)?k:0,tt=`calc(${Ve}px + env(safe-area-inset-bottom))`,lt=`calc(${Ve+8}px + env(safe-area-inset-bottom))`;return sh.createPortal(O.jsxs(O.Fragment,{children:[e&&O.jsx("div",{className:"fixed inset-0 z-40 bg-black/45 backdrop-blur-[1px] transition-opacity",onClick:t,"aria-hidden":"true"}),O.jsx(Pn,{edgeToEdgeMobile:!0,noBodyPadding:!0,className:al("fixed z-50 flex flex-col shadow-2xl ring-1 ring-black/10 dark:ring-white/10",e?"inset-4 sm:inset-6":"left-0 right-0 bottom-0 w-full rounded-none pb-[env(safe-area-inset-bottom)] sm:rounded-lg sm:left-auto sm:right-4 sm:bottom-4 sm:w-[420px]",n??""),bodyClassName:"flex flex-col flex-1 min-h-0 p-0",children:O.jsx("div",{className:e?"flex-1 min-h-0":"aspect-video",children:O.jsxs("div",{className:al("relative w-full h-full",X&&"vjs-mini",ae&&"vjs-controls-on-activity",ae&&Q&&"vjs-controls-active"),onMouseEnter:X?()=>{le(!0),ae&&he()}:e&&ae?he:void 0,onMouseMove:ae?he:void 0,onMouseLeave:()=>{X&&le(!1),ae&&ie()},onFocusCapture:e&&ae?()=>te(!0):void 0,onBlurCapture:e&&ae?Me=>{const Je=Me.relatedTarget;(!Je||!Me.currentTarget.contains(Je))&&ie()}:void 0,children:[O.jsx("div",{ref:F,className:"absolute inset-0"}),O.jsxs("div",{className:"absolute inset-x-2 top-2 z-20 flex items-start justify-between gap-2",children:[O.jsx("div",{className:"min-w-0",children:O.jsxs("div",{className:"player-ui max-w-[70vw] sm:max-w-[360px] rounded-md bg-black/45 px-2.5 py-1.5 text-white backdrop-blur",children:[O.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[O.jsx("div",{className:"truncate text-sm font-semibold",children:_}),b?O.jsx("span",{className:"shrink-0 rounded-md bg-amber-500/25 px-2 py-0.5 text-[11px] font-semibold text-white",children:"HOT"}):null]}),O.jsx("div",{className:"truncate text-[11px] text-white/80",children:E||g})]})}),O.jsxs("div",{className:"flex items-center gap-1 pointer-events-auto",children:[Ee,O.jsx("button",{type:"button",className:"inline-flex items-center justify-center rounded-md bg-black/40 p-2 text-white backdrop-blur hover:bg-black/55 transition focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500",onClick:i,"aria-label":e?"Minimieren":"Maximieren",title:e?"Minimieren":"Maximieren",children:e?O.jsx(YO,{className:"h-5 w-5"}):O.jsx(XO,{className:"h-5 w-5"})}),O.jsx("button",{type:"button",className:"inline-flex items-center justify-center rounded-md bg-black/40 p-2 text-white backdrop-blur hover:bg-black/55 transition focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500",onClick:t,"aria-label":"Schließen",title:"Schließen",children:O.jsx(LA,{className:"h-5 w-5"})})]})]}),O.jsx("div",{className:al("player-ui pointer-events-none absolute inset-x-0 bg-gradient-to-t from-black/70 to-transparent","transition-all duration-200 ease-out",e?"h-28":Ce?"bottom-7 h-24":"bottom-0 h-20"),style:e?{bottom:tt}:void 0}),O.jsxs("div",{className:al("player-ui pointer-events-none absolute inset-x-2 z-20 flex items-end justify-between gap-2","transition-all duration-200 ease-out",e?"":Ce?"bottom-7":"bottom-2"),style:e?{bottom:lt}:void 0,children:[O.jsxs("div",{className:"min-w-0",children:[O.jsx("div",{className:"truncate text-sm font-semibold text-white",children:_}),O.jsx("div",{className:"truncate text-[11px] text-white/80",children:E||g})]}),O.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 text-[11px] text-white",children:[O.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-semibold",children:s.status}),O.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:L}),I!=="—"?O.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:I}):null]})]})]})})})]}),document.body)}const Qe=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},EB=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=AB},AB=Number.MAX_SAFE_INTEGER||9007199254740991;let ot=(function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s})({}),ve=(function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s})({}),N=(function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s})({});var Rt={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},it={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Su{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class CB{constructor(e,t,i,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Su(e),this.fast_=new Su(t),this.defaultTTFB_=n,this.ttfb_=new Su(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Su(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Su(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Su(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,n=e/1e3,r=i/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function DB(s,e,t){return(e=LB(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function ni(){return ni=Object.assign?Object.assign.bind():function(s){for(var e=1;e`):mo}function E1(s,e,t){return e[s]?e[s].bind(e):kB(s,t)}const Gv=Hv();function RB(s,e,t){const i=Hv();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=E1(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Hv()}n.forEach(r=>{Gv[r]=E1(r,s)})}else ni(Gv,i);return i}const Zt=Gv;function Eo(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function OB(s){return typeof self<"u"&&s===self.ManagedMediaSource}function vw(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(o=>i.indexOf(o)===-1)}function Sn(s,e=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(e){const f=d.indexOf("\0");return f!==-1?d.substring(0,f):d}return d.replace(/\0/g,"")}const t=s.length;let i,n,r,o="",u=0;for(;u>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:n=s[u++],o+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[u++],r=s[u++],o+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return o}function Ts(s){let e="";for(let t=0;t1||n===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!Qe(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ui(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const n=t[e];n&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,n,r,o=!1){const{elementaryStreams:u}=this,c=u[e];if(!c){u[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:o};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,i),c.startDTS=Math.min(c.startDTS,n),c.endDTS=Math.max(c.endDTS,r)}}class NB extends bw{constructor(e,t,i,n,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function _w(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||_w(t,e)}}function BB(s,e){const t=_w(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const C1=Math.pow(2,32)-1,FB=[].push,xw={video:1,audio:2,id3:3,text:4};function Zi(s){return String.fromCharCode.apply(null,s)}function Sw(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function yt(s,e){const t=Ew(s,e);return t<0?4294967296+t:t}function D1(s,e){let t=yt(s,e);return t*=Math.pow(2,32),t+=yt(s,e+4),t}function Ew(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function UB(s){const e=s.byteLength;for(let t=0;t8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function kt(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n1?n+r:i;if(o===e[0])if(e.length===1)t.push(s.subarray(n+8,u));else{const c=kt(s.subarray(n+8,u),e.slice(1));c.length&&FB.apply(t,c)}n=u}return t}function $B(s){const e=[],t=s[0];let i=8;const n=yt(s,i);i+=4;let r=0,o=0;t===0?(r=yt(s,i),o=yt(s,i+4),i+=8):(r=D1(s,i),o=D1(s,i+8),i+=16),i+=2;let u=s.length+o;const c=Sw(s,i);i+=2;for(let d=0;d>>31===1)return Zt.warn("SIDX has hierarchical references (not supported)"),null;const b=yt(s,f);f+=4,e.push({referenceSize:g,subsegmentDuration:b,info:{duration:b/n,start:u,end:u+g-1}}),u+=g,f+=4,i=f}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:c,references:e}}function Aw(s){const e=[],t=kt(s,["moov","trak"]);for(let n=0;n{const r=yt(n,4),o=e[r];o&&(o.default={duration:yt(n,12),flags:yt(n,20)})}),e}function jB(s){const e=s.subarray(8),t=e.subarray(86),i=Zi(e.subarray(4,8));let n=i,r;const o=i==="enca"||i==="encv";if(o){const d=kt(e,[i])[0].subarray(i==="enca"?28:78);kt(d,["sinf"]).forEach(m=>{const g=kt(m,["schm"])[0];if(g){const v=Zi(g.subarray(4,8));if(v==="cbcs"||v==="cenc"){const b=kt(m,["frma"])[0];b&&(n=Zi(b))}}})}const u=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const c=kt(t,["avcC"])[0];c&&c.length>3&&(n+="."+Zf(c[1])+Zf(c[2])+Zf(c[3]),r=Qf(u==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=kt(e,[i])[0],d=kt(c.subarray(28),["esds"])[0];if(d&&d.length>7){let f=4;if(d[f++]!==3)break;f=Ny(d,f),f+=2;const m=d[f++];if(m&128&&(f+=2),m&64&&(f+=d[f++]),d[f++]!==4)break;f=Ny(d,f);const g=d[f++];if(g===64)n+="."+Zf(g);else break;if(f+=12,d[f++]!==5)break;f=Ny(d,f);const v=d[f++];let b=(v&248)>>3;b===31&&(b+=1+((v&7)<<3)+((d[f]&224)>>5)),n+="."+b}break}case"hvc1":case"hev1":{const c=kt(t,["hvcC"])[0];if(c&&c.length>12){const d=c[1],f=["","A","B","C"][d>>6],m=d&31,g=yt(c,2),v=(d&32)>>5?"H":"L",b=c[12],_=c.subarray(6,12);n+="."+f+m,n+="."+HB(g).toString(16).toUpperCase(),n+="."+v+b;let E="";for(let L=_.length;L--;){const I=_[L];(I||E)&&(E="."+I.toString(16).toUpperCase()+E)}n+=E}r=Qf(u=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=Qf(n,t)||n;break}case"vp09":{const c=kt(t,["vpcC"])[0];if(c&&c.length>6){const d=c[4],f=c[5],m=c[6]>>4&15;n+="."+Er(d)+"."+Er(f)+"."+Er(m)}break}case"av01":{const c=kt(t,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,f=c[1]&31,m=c[2]>>>7?"H":"M",g=(c[2]&64)>>6,v=(c[2]&32)>>5,b=d===2&&g?v?12:10:g?10:8,_=(c[2]&16)>>4,E=(c[2]&8)>>3,L=(c[2]&4)>>2,I=c[2]&3;n+="."+d+"."+Er(f)+m+"."+Er(b)+"."+_+"."+E+L+I+"."+Er(1)+"."+Er(1)+"."+Er(1)+"."+0,r=Qf("dav1",t)}break}}return{codec:n,encrypted:o,supplemental:r}}function Qf(s,e){const t=kt(e,["dvvC"]),i=t.length?t[0]:kt(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+Er(n)+"."+Er(r)}}function HB(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function Ny(s,e){const t=e+5;for(;s[e++]&128&&e{const r=i.subarray(8,24);r.some(o=>o!==0)||(Zt.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Ts(r)} -> ${Ts(t)}`),i.set(t,8))})}function VB(s){const e=[];return Cw(s,t=>e.push(t.subarray(8,24))),e}function Cw(s,e){kt(s,["moov","trak"]).forEach(i=>{const n=kt(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let o=kt(r,["enca"]);const u=o.length>0;u||(o=kt(r,["encv"])),o.forEach(c=>{const d=u?c.subarray(28):c.subarray(78);kt(d,["sinf"]).forEach(m=>{const g=Dw(m);g&&e(g,u)})})})}function Dw(s){const e=kt(s,["schm"])[0];if(e){const t=Zi(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=kt(s,["schi","tenc"])[0];if(i)return i}}}function qB(s,e,t){const i={},n=kt(s,["moof","traf"]);for(let r=0;ri[r].duration)){let r=1/0,o=0;const u=kt(s,["sidx"]);for(let c=0;cm+g.info.duration||0,0);o=Math.max(o,f+d.earliestPresentationTime/d.timescale)}}o&&Qe(o)&&Object.keys(i).forEach(c=>{i[c].duration||(i[c].duration=o*i[c].timescale-i[c].start)})}return i}function zB(s){const e={valid:null,remainder:null},t=kt(s,["moof"]);if(t.length<2)return e.remainder=s,e;const i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function Fn(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function w1(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let o=!1;return kt(i,["moof"]).map(c=>{const d=c.byteOffset-8;kt(c,["traf"]).map(m=>{const g=kt(m,["tfdt"]).map(v=>{const b=v[0];let _=yt(v,4);return b===1&&(_*=Math.pow(2,32),_+=yt(v,8)),_/n})[0];return g!==void 0&&(s=g),kt(m,["tfhd"]).map(v=>{const b=yt(v,4),_=yt(v,0)&16777215,E=(_&1)!==0,L=(_&2)!==0,I=(_&8)!==0;let w=0;const F=(_&16)!==0;let U=0;const V=(_&32)!==0;let B=8;b===r&&(E&&(B+=8),L&&(B+=4),I&&(w=yt(v,B),B+=4),F&&(U=yt(v,B),B+=4),V&&(B+=4),e.type==="video"&&(o=jm(e.codec)),kt(m,["trun"]).map(q=>{const k=q[0],R=yt(q,0)&16777215,K=(R&1)!==0;let X=0;const ee=(R&4)!==0,le=(R&256)!==0;let ae=0;const Y=(R&512)!==0;let Q=0;const te=(R&1024)!==0,oe=(R&2048)!==0;let de=0;const $=yt(q,4);let ie=8;K&&(X=yt(q,ie),ie+=4),ee&&(ie+=4);let he=X+d;for(let Ce=0;Ce<$;Ce++){if(le?(ae=yt(q,ie),ie+=4):ae=w,Y?(Q=yt(q,ie),ie+=4):Q=U,te&&(ie+=4),oe&&(k===0?de=yt(q,ie):de=Ew(q,ie),ie+=4),e.type===oi.VIDEO){let be=0;for(;be>1&63;return t===39||t===40}else return(e&31)===6}function eb(s,e,t,i){const n=ww(s);let r=0;r+=e;let o=0,u=0,c=0;for(;r=n.length)break;c=n[r++],o+=c}while(c===255);u=0;do{if(r>=n.length)break;c=n[r++],u+=c}while(c===255);const d=n.length-r;let f=r;if(ud){Zt.error(`Malformed SEI payload. ${u} is too small, only ${d} bytes left to parse.`);break}if(o===4){if(n[f++]===181){const g=Sw(n,f);if(f+=2,g===49){const v=yt(n,f);if(f+=4,v===1195456820){const b=n[f++];if(b===3){const _=n[f++],E=31&_,L=64&_,I=L?2+E*3:0,w=new Uint8Array(I);if(L){w[0]=_;for(let F=1;F16){const m=[];for(let b=0;b<16;b++){const _=n[f++].toString(16);m.push(_.length==1?"0"+_:_),(b===3||b===5||b===7||b===9)&&m.push("-")}const g=u-16,v=new Uint8Array(g);for(let b=0;b>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(s,4),n=0,i=8;n0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const o=new Uint8Array(4);return t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),WB([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,o,t)}function QB(s){const e=[];if(s instanceof ArrayBuffer){const t=s.byteLength;let i=0;for(;i+32>>24;if(r!==0&&r!==1)return{offset:t,size:e};const o=s.buffer,u=Ts(new Uint8Array(o,t+12,16));let c=null,d=null,f=0;if(r===0)f=28;else{const g=s.getUint32(28);if(!g||i<32+g*16)return{offset:t,size:e};c=[];for(let v=0;v/\(Windows.+Firefox\//i.test(navigator.userAgent),rc={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function tb(s,e){const t=rc[e];return!!t&&!!t[s.slice(0,4)]}function Xd(s,e,t=!0){return!s.split(",").some(i=>!ib(i,e,t))}function ib(s,e,t=!0){var i;const n=Eo(t);return(i=n?.isTypeSupported(Qd(s,e)))!=null?i:!1}function Qd(s,e){return`${e}/mp4;codecs=${s}`}function L1(s){if(s){const e=s.substring(0,4);return rc.video[e]}return 2}function Qp(s){const e=Lw();return s.split(",").reduce((t,i)=>{const r=e&&jm(i)?9:rc.video[i];return r?(r*2+t)/(t?3:2):(rc.audio[i]+t)/(t?2:1)},0)}const By={};function JB(s,e=!0){if(By[s])return By[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;nJB(t.toLowerCase(),e))}function tF(s,e){const t=[];if(s){const i=s.split(",");for(let n=0;n4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(I1(s,"audio")||I1(s,"video")))return s;if(e){const t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function I1(s,e){return tb(s,e)&&ib(s,e)}function iF(s){const e=s.split(",");for(let t=0;t2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function sF(s){if(s.startsWith("av01.")){const e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function k1(s){const e=Eo(s)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Vv(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const nF={supported:!0,powerEfficient:!0,smooth:!0},rF={supported:!1,smooth:!1,powerEfficient:!1},Iw={supported:!0,configurations:[],decodingInfoResults:[nF]};function kw(s,e){return{supported:!1,configurations:e,decodingInfoResults:[rF],error:s}}function aF(s,e,t,i,n,r){const o=s.videoCodec,u=s.audioCodec?s.audioGroups:null,c=r?.audioCodec,d=r?.channels,f=d?parseInt(d):c?1/0:2;let m=null;if(u!=null&&u.length)try{u.length===1&&u[0]?m=e.groups[u[0]].channels:m=u.reduce((g,v)=>{if(v){const b=e.groups[v];if(!b)throw new Error(`Audio track group ${v} not found`);Object.keys(b.channels).forEach(_=>{g[_]=(g[_]||0)+b.channels[_]})}return g},{2:0})}catch{return!0}return o!==void 0&&(o.split(",").some(g=>jm(g))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(n,8e6))||!!m&&Qe(f)&&Object.keys(m).some(g=>parseInt(g)>f)}function Rw(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(Iw);const r=[],o=oF(s),u=o.length,c=lF(s,e,u>0),d=c.length;for(let f=u||1*d||1;f--;){const m={type:"media-source"};if(u&&(m.video=o[f%u]),d){m.audio=c[f%d];const g=m.audio.bitrate;m.video&&g&&(m.video.bitrate-=g)}r.push(m)}if(n){const f=navigator.userAgent;if(n.split(",").some(m=>jm(m))&&Lw())return Promise.resolve(kw(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${f})`),r))}return Promise.all(r.map(f=>{const m=cF(f);return i[m]||(i[m]=t.decodingInfo(f))})).then(f=>({supported:!f.some(m=>!m.supported),configurations:r,decodingInfoResults:f})).catch(f=>({supported:!1,configurations:r,decodingInfoResults:[],error:f}))}function oF(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=Ow(s),n=s.width||640,r=s.height||480,o=s.frameRate||30,u=s.videoRange.toLowerCase();return t?t.map(c=>{const d={contentType:Qd(sF(c),"video"),width:n,height:r,bitrate:i,framerate:o};return u!=="sdr"&&(d.transferFunction=u),d}):[]}function lF(s,e,t){var i;const n=(i=s.audioCodec)==null?void 0:i.split(","),r=Ow(s);return n&&s.audioGroups?s.audioGroups.reduce((o,u)=>{var c;const d=u?(c=e.groups[u])==null?void 0:c.tracks:null;return d?d.reduce((f,m)=>{if(m.groupId===u){const g=parseFloat(m.channels||"");n.forEach(v=>{const b={contentType:Qd(v,"audio"),bitrate:t?uF(v,r):r};g&&(b.channels=""+g),f.push(b)})}return f},o):o},[]):[]}function uF(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Ow(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function cF(s){let e="";const{audio:t,video:i}=s;if(i){const n=Vv(i.contentType);e+=`${n}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){const n=Vv(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const qv=["NONE","TYPE-0","TYPE-1",null];function dF(s){return qv.indexOf(s)>-1}const Jp=["SDR","PQ","HLG"];function hF(s){return!!s&&Jp.indexOf(s)>-1}var bp={No:"",Yes:"YES",v2:"v2"};function R1(s){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,n=i!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return P1(this._audioGroups,e)}hasSubtitleGroup(e){return P1(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function P1(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function fF(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function pF(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||Jp.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&fF(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const mF=s=>{const e=new WeakSet;return(t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},ui=(s,e)=>JSON.stringify(s,mF(e));function gF(s,e,t,i,n){const r=Object.keys(s),o=i?.channels,u=i?.audioCodec,c=n?.videoCodec,d=o&&parseInt(o)===2;let f=!1,m=!1,g=1/0,v=1/0,b=1/0,_=1/0,E=0,L=[];const{preferHDR:I,allowedVideoRanges:w}=pF(e,n);for(let q=r.length;q--;){const k=s[r[q]];f||(f=k.channels[2]>0),g=Math.min(g,k.minHeight),v=Math.min(v,k.minFramerate),b=Math.min(b,k.minBitrate),w.filter(K=>k.videoRanges[K]>0).length>0&&(m=!0)}g=Qe(g)?g:0,v=Qe(v)?v:0;const F=Math.max(1080,g),U=Math.max(30,v);b=Qe(b)?b:t,t=Math.max(b,t),m||(e=void 0);const V=r.length>1;return{codecSet:r.reduce((q,k)=>{const R=s[k];if(k===q)return q;if(L=m?w.filter(K=>R.videoRanges[K]>0):[],V){if(R.minBitrate>t)return _r(k,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),q;if(!R.hasDefaultAudio)return _r(k,"no renditions with default or auto-select sound found"),q;if(u&&k.indexOf(u.substring(0,4))%5!==0)return _r(k,`audio codec preference "${u}" not found`),q;if(o&&!d){if(!R.channels[o])return _r(k,`no renditions with ${o} channel sound found (channels options: ${Object.keys(R.channels)})`),q}else if((!u||d)&&f&&R.channels[2]===0)return _r(k,"no renditions with stereo sound found"),q;if(R.minHeight>F)return _r(k,`min resolution of ${R.minHeight} > maximum of ${F}`),q;if(R.minFramerate>U)return _r(k,`min framerate of ${R.minFramerate} > maximum of ${U}`),q;if(!L.some(K=>R.videoRanges[K]>0))return _r(k,`no variants with VIDEO-RANGE of ${ui(L)} found`),q;if(c&&k.indexOf(c.substring(0,4))%5!==0)return _r(k,`video codec preference "${c}" not found`),q;if(R.maxScore=Qp(q)||R.fragmentError>s[q].fragmentError)?q:(_=R.minIndex,E=R.maxScore,k)},void 0),videoRanges:L,preferHDR:I,minFramerate:v,minBitrate:b,minIndex:_}}function _r(s,e){Zt.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function Pw(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const n=t.channels||"2";return i.channels[n]=(i.channels[n]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function yF(s,e,t,i){return s.slice(t,i+1).reduce((n,r,o)=>{if(!r.codecSet)return n;const u=r.audioGroups;let c=n[r.codecSet];c||(n[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!u,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const d=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,o),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,u&&u.forEach(f=>{if(!f)return;const m=e.groups[f];m&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?m.hasDefault:m.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(m.channels).forEach(g=>{c.channels[g]=(c.channels[g]||0)+m.channels[g]}))}),n},{})}function M1(s){if(!s)return s;const{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}=s;return{lang:e,assocLang:t,characteristics:i,channels:n,audioCodec:r}}function Rr(s,e,t){if("attrs"in s){const i=e.indexOf(s);if(i!==-1)return i}for(let i=0;ii.indexOf(n)===-1)}function dl(s,e){const{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function bF(s,e,t,i,n){const r=e[i],u=e.reduce((g,v,b)=>{const _=v.uri;return(g[_]||(g[_]=[])).push(b),g},{})[r.uri];u.length>1&&(i=Math.max.apply(Math,u));const c=r.videoRange,d=r.frameRate,f=r.codecSet.substring(0,4),m=N1(e,i,g=>{if(g.videoRange!==c||g.frameRate!==d||g.codecSet.substring(0,4)!==f)return!1;const v=g.audioGroups,b=t.filter(_=>!v||v.indexOf(_.groupId)!==-1);return Rr(s,b,n)>-1});return m>-1?m:N1(e,i,g=>{const v=g.audioGroups,b=t.filter(_=>!v||v.indexOf(_.groupId)!==-1);return Rr(s,b,n)>-1})}function N1(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i{var i;const{fragCurrent:n,partCurrent:r,hls:o}=this,{autoLevelEnabled:u,media:c}=o;if(!n||!c)return;const d=performance.now(),f=r?r.stats:n.stats,m=r?r.duration:n.duration,g=d-f.loading.start,v=o.minAutoLevel,b=n.level,_=this._nextAutoLevel;if(f.aborted||f.loaded&&f.loaded===f.total||b<=v){this.clearTimer(),this._nextAutoLevel=-1;return}if(!u)return;const E=_>-1&&_!==b,L=!!t||E;if(!L&&(c.paused||!c.playbackRate||!c.readyState))return;const I=o.mainForwardBufferInfo;if(!L&&I===null)return;const w=this.bwEstimator.getEstimateTTFB(),F=Math.abs(c.playbackRate);if(g<=Math.max(w,1e3*(m/(F*2))))return;const U=I?I.len/F:0,V=f.loading.first?f.loading.first-f.loading.start:-1,B=f.loaded&&V>-1,q=this.getBwEstimate(),k=o.levels,R=k[b],K=Math.max(f.loaded,Math.round(m*(n.bitrate||R.averageBitrate)/8));let X=B?g-V:g;X<1&&B&&(X=Math.min(g,f.loaded*8/q));const ee=B?f.loaded*1e3/X:0,le=w/1e3,ae=ee?(K-f.loaded)/ee:K*8/q+le;if(ae<=U)return;const Y=ee?ee*8:q,Q=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,te=this.hls.config.abrBandWidthUpFactor;let oe=Number.POSITIVE_INFINITY,de;for(de=b-1;de>v;de--){const Ce=k[de].maxBitrate,be=!k[de].details||Q;if(oe=this.getTimeToLoadFrag(le,Y,m*Ce,be),oe=ae||oe>m*10)return;B?this.bwEstimator.sample(g-Math.min(w,V),f.loaded):this.bwEstimator.sampleTTFB(g);const $=k[de].maxBitrate;this.getBwEstimate()*te>$&&this.resetEstimator($);const ie=this.findBestLevel($,v,de,0,U,1,1);ie>-1&&(de=ie),this.warn(`Fragment ${n.sn}${r?" part "+r.index:""} of level ${b} is loading too slowly; - Fragment duration: ${n.duration.toFixed(3)} - Time to underbuffer: ${U.toFixed(3)} s - Estimated load time for current fragment: ${ae.toFixed(3)} s - Estimated load time for down switch fragment: ${oe.toFixed(3)} s - TTFB estimate: ${V|0} ms - Current BW estimate: ${Qe(q)?q|0:"Unknown"} bps - New BW estimate: ${this.getBwEstimate()|0} bps - Switching to level ${de} @ ${$|0} bps`),o.nextLoadLevel=o.nextAutoLevel=de,this.clearTimer();const he=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===de&&de>0){const Ce=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${de>0?"and switching down":""} - Fragment duration: ${n.duration.toFixed(3)} s - Time to underbuffer: ${Ce.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,de>v){let be=this.findBestLevel(this.hls.levels[v].bitrate,v,de,0,Ce,1,1);be===-1&&(be=v),this.hls.nextLoadLevel=this.hls.nextAutoLevel=be,this.resetEstimator(this.hls.levels[be].bitrate)}}};E||ae>oe*2?he():this.timer=self.setInterval(he,oe*1e3),o.trigger(N.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:r,stats:f})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new CB(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.FRAG_LOADING,this.onFragLoading,this),e.on(N.FRAG_LOADED,this.onFragLoaded,this),e.on(N.FRAG_BUFFERED,this.onFragBuffered,this),e.on(N.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(N.LEVEL_LOADED,this.onLevelLoaded,this),e.on(N.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(N.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(N.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.FRAG_LOADING,this.onFragLoading,this),e.off(N.FRAG_LOADED,this.onFragLoaded,this),e.off(N.FRAG_BUFFERED,this.onFragBuffered,this),e.off(N.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(N.LEVEL_LOADED,this.onLevelLoaded,this),e.off(N.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(N.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(N.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var n;this.fragCurrent=i,this.partCurrent=(n=t.part)!=null?n:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ve.BUFFER_ADD_CODEC_ERROR:case ve.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ve.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const o=performance.now(),u=r?r.stats:i.stats,c=o-u.loading.start,d=u.loading.first?u.loading.first-u.loading.start:-1;if(u.loaded&&d>-1){const m=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(m,d),u.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,i,n){const r=e+i/t,o=n?e+this.lastLevelLoadSec:0;return r+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;Qe(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===it.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,o=this.hls.levels[t.level],u=(o.loaded?o.loaded.bytes:0)+n.loaded,c=(o.loaded?o.loaded.duration:0)+r;o.loaded={bytes:u,duration:c},o.realBitrate=Math.round(8*u/c)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(N.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,r=n!=null&&n.stats.loaded?n.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const o=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==it.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,n,1,1);if(r>-1)return r;const o=this.hls.firstLevel,u=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${u}`),u}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,r)&&o[e].loadError<=o[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:r,minAutoLevel:o}=i,u=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let f=r.abrBandWidthFactor,m=r.abrBandWidthUpFactor;if(d){const E=this.findBestLevel(c,o,n,d,0,f,m);if(E>=0)return this.rebufferNotice=-1,E}let g=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!d){const E=this.bitrateTestDelay;E&&(g=(u?Math.min(u,r.maxLoadingDelay):r.maxLoadingDelay)-E,this.info(`bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),f=m=1)}const v=this.findBestLevel(c,o,n,d,g,f,m);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${v}`)),v>-1)return v;const b=i.levels[o],_=i.loadLevelObj;return _&&b?.bitrate<_.bitrate?o:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,n,r,o,u){var c;const d=n+r,f=this.lastLoadedFragLevel,m=f===-1?this.hls.firstLevel:f,{fragCurrent:g,partCurrent:v}=this,{levels:b,allAudioTracks:_,loadLevel:E,config:L}=this.hls;if(b.length===1)return 0;const I=b[m],w=!!((c=this.hls.latestLevelDetails)!=null&&c.live),F=E===-1||f===-1;let U,V="SDR",B=I?.frameRate||0;const{audioPreference:q,videoPreference:k}=L,R=this.audioTracksByGroup||(this.audioTracksByGroup=Pw(_));let K=-1;if(F){if(this.firstSelection!==-1)return this.firstSelection;const Y=this.codecTiers||(this.codecTiers=yF(b,R,t,i)),Q=gF(Y,V,e,q,k),{codecSet:te,videoRanges:oe,minFramerate:de,minBitrate:$,minIndex:ie,preferHDR:he}=Q;K=ie,U=te,V=he?oe[oe.length-1]:oe[0],B=de,e=Math.max(e,$),this.log(`picked start tier ${ui(Q)}`)}else U=I?.codecSet,V=I?.videoRange;const X=v?v.duration:g?g.duration:0,ee=this.bwEstimator.getEstimateTTFB()/1e3,le=[];for(let Y=i;Y>=t;Y--){var ae;const Q=b[Y],te=Y>m;if(!Q)continue;if(L.useMediaCapabilities&&!Q.supportedResult&&!Q.supportedPromise){const be=navigator.mediaCapabilities;typeof be?.decodingInfo=="function"&&aF(Q,R,V,B,e,q)?(Q.supportedPromise=Rw(Q,R,be,this.supportedCache),Q.supportedPromise.then(Ue=>{if(!this.hls)return;Q.supportedResult=Ue;const Ee=this.hls.levels,je=Ee.indexOf(Q);Ue.error?this.warn(`MediaCapabilities decodingInfo error: "${Ue.error}" for level ${je} ${ui(Ue)}`):Ue.supported?Ue.decodingInfoResults.some(Ve=>Ve.smooth===!1||Ve.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${je} not smooth or powerEfficient: ${ui(Ue)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${je} ${ui(Ue)}`),je>-1&&Ee.length>1&&(this.log(`Removing unsupported level ${je}`),this.hls.removeLevel(je),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ue=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ue}`)})):Q.supportedResult=Iw}if((U&&Q.codecSet!==U||V&&Q.videoRange!==V||te&&B>Q.frameRate||!te&&B>0&&Bbe.smooth===!1))&&(!F||Y!==K)){le.push(Y);continue}const oe=Q.details,de=(v?oe?.partTarget:oe?.averagetargetduration)||X;let $;te?$=u*e:$=o*e;const ie=X&&n>=X*2&&r===0?Q.averageBitrate:Q.maxBitrate,he=this.getTimeToLoadFrag(ee,$,ie*de,oe===void 0);if($>=ie&&(Y===f||Q.loadError===0&&Q.fragmentError===0)&&(he<=ee||!Qe(he)||w&&!this.bitrateTestDelay||he${Y} adjustedbw(${Math.round($)})-bitrate=${Math.round($-ie)} ttfb:${ee.toFixed(1)} avgDuration:${de.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${he.toFixed(1)} firstSelection:${F} codecSet:${Q.codecSet} videoRange:${Q.videoRange} hls.loadLevel:${E}`)),F&&(this.firstSelection=Y),Y}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const Mw={search:function(s,e){let t=0,i=s.length-1,n=null,r=null;for(;t<=i;){n=(t+i)/2|0,r=s[n];const o=e(r);if(o>0)t=n+1;else if(o<0)i=n-1;else return r}return null}};function xF(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!Qe(e))return null;const i=s[0].programDateTime;if(e<(i||0))return null;const n=s[s.length-1].endProgramDateTime;if(e>=(n||0))return null;for(let r=0;r0&&u<15e-7&&(t+=15e-7),r&&s.level!==r.level&&r.end<=s.end&&(r=e[2+s.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!s||s.level===r.level)&&B1(t,i,r)===0||SF(r,s,Math.min(n,i))))return r;const o=Mw.search(e,B1.bind(null,t,i));return o&&(o!==s||!r)?o:r}function SF(s,e,t){if(e&&e.start===0&&e.level0){const i=e.tagList.reduce((n,r)=>(r[0]==="INF"&&(n+=parseFloat(r[1])),n),t);return s.start<=i}return!1}function B1(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function EF(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function Nw(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments;const{fragmentHint:n}=s;n&&(i=i.concat(n));let r;return Mw.search(i,o=>o.cce?-1:(r=o,o.end<=t?1:o.start>t?-1:0)),r||null}return null}function tm(s){switch(s.details){case ve.FRAG_LOAD_TIMEOUT:case ve.KEY_LOAD_TIMEOUT:case ve.LEVEL_LOAD_TIMEOUT:case ve.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Bw(s){return s.details.startsWith("key")}function Fw(s){return Bw(s)&&!!s.frag&&!s.frag.decryptdata}function F1(s,e){const t=tm(e);return s.default[`${t?"timeout":"error"}Retry`]}function sb(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function U1(s){return Qt(Qt({},s),{errorRetry:null,timeoutRetry:null})}function im(s,e,t,i){if(!s)return!1;const n=i?.code,r=e499)}function zv(s){return s===0&&navigator.onLine===!1}var ys={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},bn={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class CF extends jn{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(N.ERROR,this.onError,this),e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(N.ERROR,this.onError,this),e.off(N.ERROR,this.onErrorOut,this),e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===it.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(o=>n.indexOf(o.groupId)>=0).some(o=>{var u;return(u=o.details)==null?void 0:u.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const n=this.hls,r=t.context;switch(t.details){case ve.FRAG_LOAD_ERROR:case ve.FRAG_LOAD_TIMEOUT:case ve.KEY_LOAD_ERROR:case ve.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case ve.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=zu();return}case ve.FRAG_GAP:case ve.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ys.SendAlternateToPenaltyBox;return}case ve.LEVEL_EMPTY_ERROR:case ve.LEVEL_PARSING_ERROR:{var o;const c=t.parent===it.MAIN?t.level:n.loadLevel;t.details===ve.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(o=o.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case ve.LEVEL_LOAD_ERROR:case ve.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case ve.AUDIO_TRACK_LOAD_ERROR:case ve.AUDIO_TRACK_LOAD_TIMEOUT:case ve.SUBTITLE_LOAD_ERROR:case ve.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=n.loadLevelObj;if(c&&(r.type===Rt.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===Rt.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=ys.SendAlternateToPenaltyBox,t.errorAction.flags=bn.MoveAllAlternatesMatchingHost;return}}return;case ve.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ys.SendAlternateToPenaltyBox,flags:bn.MoveAllAlternatesMatchingHDCP};return;case ve.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ve.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ve.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ys.SendAlternateToPenaltyBox,flags:bn.MoveAllAlternatesMatchingKey};return;case ve.BUFFER_ADD_CODEC_ERROR:case ve.REMUX_ALLOC_ERROR:case ve.BUFFER_APPEND_ERROR:if(!t.errorAction){var u;t.errorAction=this.getLevelSwitchAction(t,(u=t.level)!=null?u:n.loadLevel)}return;case ve.INTERNAL_EXCEPTION:case ve.BUFFER_APPENDING_ERROR:case ve.BUFFER_FULL_ERROR:case ve.LEVEL_SWITCH_ERROR:case ve.BUFFER_STALLED_ERROR:case ve.BUFFER_SEEK_OVER_HOLE:case ve.BUFFER_NUDGE_ON_STALL:t.errorAction=zu();return}t.type===ot.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=zu())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=F1(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(im(n,r,tm(e),e.response))return{action:ys.RetryRequest,flags:bn.None,retryConfig:n,retryCount:r};const u=this.getLevelSwitchAction(e,t);return n&&(u.retryConfig=n,u.retryCount=r),u}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:o}=t.config,u=F1(Bw(e)?o:r,e),c=t.levels.reduce((f,m)=>f+m.fragmentError,0);if(n&&(e.details!==ve.FRAG_GAP&&n.fragmentError++,!Fw(e)&&im(u,c,tm(e),e.response)))return{action:ys.RetryRequest,flags:bn.None,retryConfig:u,retryCount:c};const d=this.getLevelSwitchAction(e,i);return u&&(d.retryConfig=u,d.retryCount=c),d}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var r,o;const d=e.details;n.loadError++,d===ve.BUFFER_APPEND_ERROR&&n.fragmentError++;let f=-1;const{levels:m,loadLevel:g,minAutoLevel:v,maxAutoLevel:b}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const _=(r=e.frag)==null?void 0:r.type,L=(_===it.AUDIO&&d===ve.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===ve.BUFFER_ADD_CODEC_ERROR||d===ve.BUFFER_APPEND_ERROR))&&m.some(({audioCodec:V})=>n.audioCodec!==V),w=e.sourceBufferName==="video"&&(d===ve.BUFFER_ADD_CODEC_ERROR||d===ve.BUFFER_APPEND_ERROR)&&m.some(({codecSet:V,audioCodec:B})=>n.codecSet!==V&&n.audioCodec===B),{type:F,groupId:U}=(o=e.context)!=null?o:{};for(let V=m.length;V--;){const B=(V+g)%m.length;if(B!==g&&B>=v&&B<=b&&m[B].loadError===0){var u,c;const q=m[B];if(d===ve.FRAG_GAP&&_===it.MAIN&&e.frag){const k=m[B].details;if(k){const R=Cl(e.frag,k.fragments,e.frag.start);if(R!=null&&R.gap)continue}}else{if(F===Rt.AUDIO_TRACK&&q.hasAudioGroup(U)||F===Rt.SUBTITLE_TRACK&&q.hasSubtitleGroup(U))continue;if(_===it.AUDIO&&(u=n.audioGroups)!=null&&u.some(k=>q.hasAudioGroup(k))||_===it.SUBTITLE&&(c=n.subtitleGroups)!=null&&c.some(k=>q.hasSubtitleGroup(k))||L&&n.audioCodec===q.audioCodec||w&&n.codecSet===q.codecSet||!L&&n.codecSet!==q.codecSet)continue}f=B;break}}if(f>-1&&i.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:ys.SendAlternateToPenaltyBox,flags:bn.None,nextAutoLevel:f}}return{action:ys.SendAlternateToPenaltyBox,flags:bn.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ys.DoNothing:break;case ys.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==ve.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n}=i,r=i.nextAutoLevel;switch(n){case bn.None:this.switchLevel(e,r);break;case bn.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),d=t.levels[c],f=d?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=f,f==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(f){t.maxHdcpLevel=qv[qv.indexOf(f)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case bn.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const d=this.hls.levels,f=d.length;for(let g=f;g--;)if(this.variantHasKey(d[g],c)){var o,u;this.log(`Banned key found in level ${g} (${d[g].bitrate}bps) or audio group "${(o=d[g].audioGroups)==null?void 0:o.join(",")}" (${(u=e.frag)==null?void 0:u.type} fragment) ${Ts(c.keyId||[])}`),d[g].fragmentError++,d[g].loadError++,this.log(`Removing level ${g} with key error (${e.error})`),this.hls.removeLevel(g)}const m=e.frag;if(this.hls.levels.length{const c=this.fragments[u];if(!c||o>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===i&&this.removeFragment(c.body);return}const d=c.range[e];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(f=>{const m=!this.isTimeBuffered(f.startPTS,f.endPTS,t);return m&&this.removeFragment(c.body),m})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=Eu(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(u=>{const c=i.elementaryStreams[u];if(!c)return;const d=t[u],f=o||c.partial===!0;r.range[u]=this.getBufferedTimes(i,e.part,f,d)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),Jf(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=$1(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Eu(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,i,n){const r={time:[],partial:i},o=e.start,u=e.end,c=e.minEndPTS||u,d=e.maxStartPTS||o;for(let f=0;f=m&&c<=g){r.time.push({startPTS:Math.max(o,n.start(f)),endPTS:Math.min(u,n.end(f))});break}else if(om){const v=Math.max(o,n.start(f)),b=Math.min(u,n.end(f));b>v&&(r.partial=!0,r.time.push({startPTS:v,endPTS:b}))}else if(u<=m)break}return r}getPartialFragment(e){let t=null,i,n,r,o=0;const{bufferPadding:u,fragments:c}=this;return Object.keys(c).forEach(d=>{const f=c[d];f&&Jf(f)&&(n=f.body.start-u,r=f.body.end+u,e>=n&&e<=r&&(i=Math.min(e-n,r-e),o<=i&&(t=f.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Jf(t))}getState(e){const t=Eu(e),i=this.fragments[t];return i?i.buffered?Jf(i)?Ji.PARTIAL:Ji.OK:Ji.APPENDING:Ji.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let o=0;o=n&&t<=r)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,r=Eu(i);this.fragments[r]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:r,type:o}=t;if(i.sn==="initSegment")return;const u=i.type;if(n){let d=this.activePartLists[u];d||(this.activePartLists[u]=d=[]),d.push(n)}this.timeRanges=r;const c=r[o];this.detectEvictedFragments(o,c,u,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Eu(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const r=t[i[n]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const u=this.fragments[o];if(!u)return;const c=u.body;c.type!==i||n&&!c.gap||c.starte&&(u.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=Eu(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=$1(i,r=>r.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}}function Jf(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function Eu(s){return`${s.type}_${s.level}_${s.sn}`}function $1(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Ao={cbc:0,ctr:1};class wF{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Ao.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ao.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function LF(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class IF{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],r=i[1],o=i[2],u=i[3],c=this.invSubMix,d=c[0],f=c[1],m=c[2],g=c[3],v=new Uint32Array(256);let b=0,_=0,E=0;for(E=0;E<256;E++)E<128?v[E]=E<<1:v[E]=E<<1^283;for(E=0;E<256;E++){let L=_^_<<1^_<<2^_<<3^_<<4;L=L>>>8^L&255^99,e[b]=L,t[L]=b;const I=v[b],w=v[I],F=v[w];let U=v[L]*257^L*16843008;n[b]=U<<24|U>>>8,r[b]=U<<16|U>>>16,o[b]=U<<8|U>>>24,u[b]=U,U=F*16843009^w*65537^I*257^b*16843008,d[L]=U<<24|U>>>8,f[L]=U<<16|U>>>16,m[L]=U<<8|U>>>24,g[L]=U,b?(b=I^v[v[v[F^I]]],_^=v[v[_]]):b=_=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n{const u=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(u,t,i,n);const c=this.flush();c?r(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:o,remainderData:u}=this;if(n!==Ao.cbc||t.byteLength!==16)return Zt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),u&&(e=Fn(u,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(i=r);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new IF),d.expandKey(t);const f=o;return this.currentResult=d.decrypt(c.buffer,0,i),this.currentIV=c.slice(-16).buffer,f||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new kF(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new wF(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Zt.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%OF;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Zt.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const j1=Math.pow(2,17);class PF{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new ha({type:ot.NETWORK_ERROR,details:ve.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(b=>b[0]==="GAP")){c(G1(e));return}else e.gap=!1;const d=this.loader=r?new r(n):new o(n),f=H1(e);e.loader=d;const m=U1(n.fragLoadPolicy.default),g={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:j1};e.stats=d.stats;const v={onSuccess:(b,_,E,L)=>{this.resetLoader(e,d);let I=b.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(I.slice(0,16)),I=I.slice(16)),u({frag:e,part:null,payload:I,networkDetails:L})},onError:(b,_,E,L)=>{this.resetLoader(e,d),c(new ha({type:ot.NETWORK_ERROR,details:ve.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Qt({url:i,data:void 0},b),error:new Error(`HTTP Error ${b.code} ${b.text}`),networkDetails:E,stats:L}))},onAbort:(b,_,E)=>{this.resetLoader(e,d),c(new ha({type:ot.NETWORK_ERROR,details:ve.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:b}))},onTimeout:(b,_,E)=>{this.resetLoader(e,d),c(new ha({type:ot.NETWORK_ERROR,details:ve.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:E,stats:b}))}};t&&(v.onProgress=(b,_,E,L)=>t({frag:e,part:null,payload:E,networkDetails:L})),d.load(f,g,v)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(G1(e,t));return}const d=this.loader=r?new r(n):new o(n),f=H1(e,t);e.loader=d;const m=U1(n.fragLoadPolicy.default),g={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:j1};t.stats=d.stats,d.load(f,g,{onSuccess:(v,b,_,E)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const L={frag:e,part:t,payload:v.data,networkDetails:E};i(L),u(L)},onError:(v,b,_,E)=>{this.resetLoader(e,d),c(new ha({type:ot.NETWORK_ERROR,details:ve.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Qt({url:f.url,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:_,stats:E}))},onAbort:(v,b,_)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),c(new ha({type:ot.NETWORK_ERROR,details:ve.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:_,stats:v}))},onTimeout:(v,b,_)=>{this.resetLoader(e,d),c(new ha({type:ot.NETWORK_ERROR,details:ve.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:_,stats:v}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,r=n.total;if(i.loaded+=n.loaded,r){const c=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/r),c),m=(c-d)*Math.round(i.loaded/d);i.total=i.loaded+m}else i.total=Math.max(i.loaded,i.total);const o=i.loading,u=n.loading;o.start?o.first+=u.first-u.start:(o.start=u.start,o.first=u.first),o.end=u.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function H1(s,e=null){const t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(Qe(n)&&Qe(r)){var o;let u=n,c=r;if(s.sn==="initSegment"&&MF((o=s.decryptdata)==null?void 0:o.method)){const d=r-n;d%16&&(c=r+(16-d%16)),n!==0&&(i.resetIV=!0,u=n-16)}i.rangeStart=u,i.rangeEnd=c}return i}function G1(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:ot.MEDIA_ERROR,details:ve.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new ha(i)}function MF(s){return s==="AES-128"||s==="AES-256"}class ha extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Uw extends jn{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class rb{constructor(e,t,i,n=0,r=-1,o=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=ep(),this.buffering={audio:ep(),video:ep(),audiovideo:ep()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=o}}function ep(){return{start:0,executeStart:0,executeEnd:0,end:0}}const V1={length:0,start:()=>0,end:()=>0};class _t{static isBuffered(e,t){if(e){const i=_t.getBuffered(e);for(let n=i.length;n--;)if(t>=i.start(n)&&t<=i.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=_t.getBuffered(e);return _t.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i1&&e.sort((f,m)=>f.start-m.start||m.end-f.end);let n=-1,r=[];if(i)for(let f=0;f=e[f].start&&t<=e[f].end&&(n=f);const m=r.length;if(m){const g=r[m-1].end;e[f].start-gg&&(r[m-1].end=e[f].end):r.push(e[f])}else r.push(e[f])}else r=e;let o=0,u,c=t,d=t;for(let f=0;f=m&&t<=g&&(n=f),t+i>=m&&t{const n=i.substring(2,i.length-1),r=t?.[n];return r===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):r})}return e}function z1(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))r=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,r=e.VALUE;n in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=r||""}function NF(s,e,t){const i=e.IMPORT;if(t&&i in t){let n=s.variableList;n||(s.variableList=n={}),n[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const BF=/^(\d+)x(\d+)$/,K1=/(.+?)=(".*?"|.*?)(?:,|$)/g;class _i{constructor(e,t){typeof e=="string"&&(e=_i.parseAttrList(e,t)),ni(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let n=0;nNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((n,r)=>(n[r.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=BF.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const n={};for(K1.lastIndex=0;(i=K1.exec(e))!==null;){const o=i[1].trim();let u=i[2];const c=u.indexOf('"')===0&&u.lastIndexOf('"')===u.length-1;let d=!1;if(c)u=u.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(c||d))u=Kv(t,u);else if(!d&&!c)switch(o){case"CLOSED-CAPTIONS":if(u==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Zt.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=u}return n}}const FF="com.apple.hls.interstitial";function UF(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function $F(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class jw{constructor(e,t,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(n=t?.tagOrder)!=null?n:i,t){const r=t.attr;for(const o in r)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==r[o]){Zt.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=ni(new _i({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=t?.endDate||new Date(this.attr["END-DATE"]);Qe(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Zt.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Qe(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===FF}get isValid(){return!!this.id&&!this._badValueForSameId&&Qe(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const jF=10;class HF{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?Qe(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||jF}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function sm(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function Y1(s,e){return!s&&!e?!0:!s||!e?!1:sm(s,e)}function Ku(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function ab(s){switch(s){case"AES-128":case"AES-256":return Ao.cbc;case"AES-256-CTR":return Ao.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function ob(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Yv(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function GF(s){const e=Yv(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Hw(s){const e=function(i,n,r){const o=i[n];i[n]=i[r],i[r]=o};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function Gw(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const r=n[0]==="base64",o=n[1];r?(i.splice(-1,1),t=ob(o)):t=GF(o)}}return t}const nm=typeof self<"u"?self:void 0;var xi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},bs={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function _p(s){switch(s){case bs.FAIRPLAY:return xi.FAIRPLAY;case bs.PLAYREADY:return xi.PLAYREADY;case bs.WIDEVINE:return xi.WIDEVINE;case bs.CLEARKEY:return xi.CLEARKEY}}function Fy(s){switch(s){case xi.FAIRPLAY:return bs.FAIRPLAY;case xi.PLAYREADY:return bs.PLAYREADY;case xi.WIDEVINE:return bs.WIDEVINE;case xi.CLEARKEY:return bs.CLEARKEY}}function kd(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[xi.FAIRPLAY,xi.WIDEVINE,xi.PLAYREADY,xi.CLEARKEY].filter(n=>!!e[n]):[];return!i[xi.WIDEVINE]&&t&&i.push(xi.WIDEVINE),i}const Vw=(function(s){return nm!=null&&(s=nm.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function VF(s,e,t,i){let n;switch(s){case xi.FAIRPLAY:n=["cenc","sinf"];break;case xi.WIDEVINE:case xi.PLAYREADY:n=["cenc"];break;case xi.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return qF(n,e,t,i)}function qF(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function zF(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function qw(s){const e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){const u=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(u){const c=ob(u).subarray(0,16);return Hw(c),c}}return null}let Au={};class _o{static clearKeyUriToKeyIdMap(){Au={}}static setKeyIdForUri(e,t){Au[e]=t}static addKeyIdForUri(e){const t=Object.keys(Au).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Au[e]=i,i}constructor(e,t,i,n=[1],r=null,o){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=n,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ku(e),o!=null&&o.startsWith("0x")&&(this.keyId=new Uint8Array(Tw(o)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&sm(e.keyFormatVersions,this.keyFormatVersions)&&Y1(e.iv,this.iv)&&Y1(e.keyId,this.keyId)}isSupported(){if(this.method){if(Ku(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case bs.FAIRPLAY:case bs.WIDEVINE:case bs.PLAYREADY:case bs.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Ku(this.method)){let r=this.iv;return r||(typeof e!="number"&&(Zt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=YF(e)),new _o(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Au[this.uri];if(r&&!sm(this.keyId,r)&&_o.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Gw(this.uri);if(i)switch(this.keyFormat){case bs.WIDEVINE:if(this.pssh=i,!this.keyId){const r=QB(i.buffer);if(r.length){var n;const o=r[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=W1(t));break;case bs.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=XB(r,null,i),this.keyId=qw(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const o=new Uint8Array(16);o.set(r,16-r.length),r=o}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=KF(t),r||(r=W1(t),r||(r=Au[this.uri])),r&&(this.keyId=r,_o.setKeyIdForUri(this.uri,r))}return this}}function KF(s){const e=s?.[bs.WIDEVINE];return e?e.keyId:null}function W1(s){const e=s?.[bs.PLAYREADY];if(e){const t=Gw(e.uri);if(t)return qw(t)}return null}function YF(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const X1=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Q1=/#EXT-X-MEDIA:(.*)/g,WF=/^#EXT(?:INF|-X-TARGETDURATION):/m,Uy=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),XF=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Or{static findGroup(e,t){for(let i=0;i0&&r.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:o.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(Q1.lastIndex=0;(n=Q1.exec(e))!==null;){const d=new _i(n[1],i),f=d.TYPE;if(f){const m=u[f],g=r[f]||[];r[f]=g;const v=d.LANGUAGE,b=d["ASSOC-LANGUAGE"],_=d.CHANNELS,E=d.CHARACTERISTICS,L=d["INSTREAM-ID"],I={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||v||"",type:f,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:v,url:d.URI?Or.resolve(d.URI,t):""};if(b&&(I.assocLang=b),_&&(I.channels=_),E&&(I.characteristics=E),L&&(I.instreamId=L),m!=null&&m.length){const w=Or.findGroup(m,I.groupId)||m[0];t2(I,w,"audioCodec"),t2(I,w,"textCodec")}g.push(I)}}return r}static parseLevelPlaylist(e,t,i,n,r,o){var u;const c={url:t},d=new HF(t),f=d.fragments,m=[];let g=null,v=0,b=0,_=0,E=0,L=0,I=null,w=new My(n,c),F,U,V,B=-1,q=!1,k=null,R;if(Uy.lastIndex=0,d.m3u8=e,d.hasVariableRefs=q1(e),((u=Uy.exec(e))==null?void 0:u[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(F=Uy.exec(e))!==null;){q&&(q=!1,w=new My(n,c),w.playlistOffset=_,w.setStart(_),w.sn=v,w.cc=E,L&&(w.bitrate=L),w.level=i,g&&(w.initSegment=g,g.rawProgramDateTime&&(w.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),k&&(w.setByteRange(k),k=null)));const le=F[1];if(le){w.duration=parseFloat(le);const ae=(" "+F[2]).slice(1);w.title=ae||null,w.tagList.push(ae?["INF",le,ae]:["INF",le])}else if(F[3]){if(Qe(w.duration)){w.playlistOffset=_,w.setStart(_),V&&s2(w,V,d),w.sn=v,w.level=i,w.cc=E,f.push(w);const ae=(" "+F[3]).slice(1);w.relurl=Kv(d,ae),Wv(w,I,m),I=w,_+=w.duration,v++,b=0,q=!0}}else{if(F=F[0].match(XF),!F){Zt.warn("No matches on slow regex match for level playlist!");continue}for(U=1;U0&&n2(d,ae,F),v=d.startSN=parseInt(Y);break;case"SKIP":{d.skippedSegments&&ca(d,ae,F);const te=new _i(Y,d),oe=te.decimalInteger("SKIPPED-SEGMENTS");if(Qe(oe)){d.skippedSegments+=oe;for(let $=oe;$--;)f.push(null);v+=oe}const de=te.enumeratedString("RECENTLY-REMOVED-DATERANGES");de&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(de.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&ca(d,ae,F),d.targetduration=Math.max(parseInt(Y),1);break;case"VERSION":d.version!==null&&ca(d,ae,F),d.version=parseInt(Y);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||ca(d,ae,F),d.live=!1;break;case"#":(Y||Q)&&w.tagList.push(Q?[Y,Q]:[Y]);break;case"DISCONTINUITY":E++,w.tagList.push(["DIS"]);break;case"GAP":w.gap=!0,w.tagList.push([ae]);break;case"BITRATE":w.tagList.push([ae,Y]),L=parseInt(Y)*1e3,Qe(L)?w.bitrate=L:L=0;break;case"DATERANGE":{const te=new _i(Y,d),oe=new jw(te,d.dateRanges[te.ID],d.dateRangeTagCount);d.dateRangeTagCount++,oe.isValid||d.skippedSegments?d.dateRanges[oe.id]=oe:Zt.warn(`Ignoring invalid DATERANGE tag: "${Y}"`),w.tagList.push(["EXT-X-DATERANGE",Y]);break}case"DEFINE":{{const te=new _i(Y,d);"IMPORT"in te?NF(d,te,o):z1(d,te,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?ca(d,ae,F):f.length>0&&n2(d,ae,F),d.startCC=E=parseInt(Y);break;case"KEY":{const te=Z1(Y,t,d);if(te.isSupported()){if(te.method==="NONE"){V=void 0;break}V||(V={});const oe=V[te.keyFormat];oe!=null&&oe.matches(te)||(oe&&(V=ni({},V)),V[te.keyFormat]=te)}else Zt.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Y}"`);break}case"START":d.startTimeOffset=J1(Y);break;case"MAP":{const te=new _i(Y,d);if(w.duration){const oe=new My(n,c);i2(oe,te,i,V),g=oe,w.initSegment=g,g.rawProgramDateTime&&!w.rawProgramDateTime&&(w.rawProgramDateTime=g.rawProgramDateTime)}else{const oe=w.byteRangeEndOffset;if(oe){const de=w.byteRangeStartOffset;k=`${oe-de}@${de}`}else k=null;i2(w,te,i,V),g=w,q=!0}g.cc=E;break}case"SERVER-CONTROL":{R&&ca(d,ae,F),R=new _i(Y),d.canBlockReload=R.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=R.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&R.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=R.optionalFloat("PART-HOLD-BACK",0),d.holdBack=R.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&ca(d,ae,F);const te=new _i(Y);d.partTarget=te.decimalFloatingPoint("PART-TARGET");break}case"PART":{let te=d.partList;te||(te=d.partList=[]);const oe=b>0?te[te.length-1]:void 0,de=b++,$=new _i(Y,d),ie=new NB($,w,c,de,oe);te.push(ie),w.duration+=ie.duration;break}case"PRELOAD-HINT":{const te=new _i(Y,d);d.preloadHint=te;break}case"RENDITION-REPORT":{const te=new _i(Y,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(te);break}default:Zt.warn(`line parsed but not handled: ${F}`);break}}}I&&!I.relurl?(f.pop(),_-=I.duration,d.partList&&(d.fragmentHint=I)):d.partList&&(Wv(w,I,m),w.cc=E,d.fragmentHint=w,V&&s2(w,V,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const K=f.length,X=f[0],ee=f[K-1];if(_+=d.skippedSegments*d.targetduration,_>0&&K&&ee){d.averagetargetduration=_/K;const le=ee.sn;d.endSN=le!=="initSegment"?le:0,d.live||(ee.endList=!0),B>0&&(ZF(f,B),X&&m.unshift(X))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,m.length&&d.dateRangeTagCount&&X&&zw(m,d),d.endCC=E,d}}function zw(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){const u=e.fragments[e.fragments.length-1];s.push(u),t++}else return;const i=s[t-1],n=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let u=r.length;u--;){const c=e.dateRanges[r[u]],d=c.startDate.getTime();c.tagAnchor=i.ref;for(let f=t;f--;){var o;if(((o=s[f])==null?void 0:o.sn)=u||i===0){var o;const c=(((o=t[i+1])==null?void 0:o.start)||n)-r.start;if(e<=u+c*1e3){const d=t[i].sn-s.startSN;if(d<0)return-1;const f=s.fragments;if(f.length>t.length){const g=(t[i+1]||f[f.length-1]).sn-s.startSN;for(let v=g;v>d;v--){const b=f[v].programDateTime;if(e>=b&&ei);["video","audio","text"].forEach(i=>{const n=t.filter(r=>tb(r,i));n.length&&(e[`${i}Codec`]=n.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>n.indexOf(r)===-1))}),e.unknownCodecs=t}function t2(s,e,t){const i=e[t];i&&(s[t]=i)}function ZF(s,e){let t=s[e];for(let i=e;i--;){const n=s[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Wv(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function i2(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function s2(s,e,t){s.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(s)}function ca(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function n2(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function $y(s,e){const t=e.startPTS;if(Qe(t)){let i=0,n;e.sn>s.sn?(i=t-s.start,n=s):(i=s.start-t,n=e),n.duration!==i&&n.setDuration(i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0))}function Kw(s,e,t,i,n,r,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,r=n+e.duration);let c=t,d=i;const f=e.startPTS,m=e.endPTS;if(Qe(f)){const L=Math.abs(f-t);s&&L>s.totalduration?o.warn(`media timestamps and playlist times differ by ${L}s for level ${e.level} ${s.url}`):Qe(e.deltaPTS)?e.deltaPTS=Math.max(L,e.deltaPTS):e.deltaPTS=L,c=Math.max(t,f),t=Math.min(t,f),n=e.startDTS!==void 0?Math.min(n,e.startDTS):n,d=Math.min(i,m),i=Math.max(i,m),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const g=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=n,e.endPTS=i,e.minEndPTS=d,e.endDTS=r;const v=e.sn;if(!s||vs.endSN)return 0;let b;const _=v-s.startSN,E=s.fragments;for(E[_]=e,b=_;b>0;b--)$y(E[b],E[b-1]);for(b=_;b=0;f--){const m=n[f].initSegment;if(m){i=m;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;i8(s,e,(f,m,g,v)=>{if((!e.startCC||e.skippedSegments)&&m.cc!==f.cc){const b=f.cc-m.cc;for(let _=g;_{var m;f&&(!f.initSegment||f.initSegment.relurl===((m=i)==null?void 0:m.relurl))&&(f.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(f=>!f),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let f=e.skippedSegments;f--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=e8(s.dateRanges,e,t));const f=s.fragments.filter(m=>m.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let m=1;m{m.elementaryStreams=f.elementaryStreams,m.stats=f.stats}),r?Kw(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Yw(s,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const f=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=f),e.driftEndTime=d,e.driftEnd=f}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function e8(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=ni({},s);n&&n.forEach(c=>{delete r[c]});const u=Object.keys(r).length;return u?(Object.keys(i).forEach(c=>{const d=r[c],f=new jw(i[c].attr,d);f.isValid?(r[c]=f,d||(f.tagOrder+=u)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ui(i[c].attr)}"`)}),r):i}function t8(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const o=s[n],u=e[n+i];o&&u&&o.index===u.index&&o.fragment.sn===u.fragment.sn?t(o,u):i--}}}function i8(s,e,t){const i=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,r=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,o=e.startSN-s.startSN,u=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=n;d<=r;d++){const f=c[o+d];let m=u[d];if(i&&!m&&f&&(m=e.fragments[d]=f),f&&m){t(f,m,d,u);const g=f.relurl,v=m.relurl;if(g&&s8(g,v)){e.playlistParsingError=r2(`media sequence mismatch ${m.sn}:`,s,e,f,m);return}else if(f.cc!==m.cc){e.playlistParsingError=r2(`discontinuity sequence mismatch (${f.cc}!=${m.cc})`,s,e,f,m);return}}}}function r2(s,e,t,i,n){return new Error(`${s} ${n.url} -Playlist starting @${e.startSN} -${e.m3u8} - -Playlist starting @${t.startSN} -${t.m3u8}`)}function Yw(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let o=0;if(r&&ie){const r=i[i.length-1].duration*1e3;r{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function s8(s,e){return s!==e&&e?o2(s)!==o2(e):!1}function o2(s){return s.replace(/\?[^?]*$/,"")}function Hd(s,e){for(let i=0,n=s.length;is.startCC)}function l2(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function Jw(s,e){const t=e.fragments;for(let i=0,n=t.length;i{const{config:o,fragCurrent:u,media:c,mediaBuffer:d,state:f}=this,m=c?c.currentTime:0,g=_t.bufferInfo(d||c,m,o.maxBufferHole),v=!g.len;if(this.log(`Media seeking to ${Qe(m)?m.toFixed(3):m}, state: ${f}, ${v?"out of":"in"} buffer`),this.state===Pe.ENDED)this.resetLoadingState();else if(u){const b=o.maxFragLookUpTolerance,_=u.start-b,E=u.start+u.duration+b;if(v||Eg.end){const L=m>E;(m<_||L)&&(L&&u.loader&&(this.log(`Cancelling fragment load for seek (sn: ${u.sn})`),u.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(m,1/0,this.playlistType,!0);const b=this.lastCurrentTime;if(m>b&&(this.lastCurrentTime=m),!this.loadingParts){const _=Math.max(g.end,m),E=this.shouldLoadParts(this.getLevelDetails(),_);E&&(this.log(`LL-Part loading ON after seeking to ${m.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=E)}}this.hls.hasEnoughToStart||(this.log(`Setting ${v?"startPosition":"nextLoadPosition"} to ${m} for seek without enough to start`),this.nextLoadPosition=m,v&&(this.startPosition=m)),v&&this.state===Pe.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new PF(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new nb(e.config)}registerListeners(){const{hls:e}=this;e.on(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(N.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(N.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Pe.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Pe.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=_t.bufferedInfo(r,e.start,0));const o=e.nextStart;if(o&&o>n&&o{const o=r.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(o,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const o=this.state,u=r.frag;if(this.fragContextChanged(u)){(o===Pe.FRAG_LOADING||!this.fragCurrent&&o===Pe.PARSING)&&(this.fragmentTracker.removeFragment(u),this.state=Pe.IDLE);return}"payload"in r&&(this.log(`Loaded ${u.type} sn: ${u.sn} of ${this.playlistLabel()} ${u.level}`),this.hls.trigger(N.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===Pe.STOPPED||this.state===Pe.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Ji.APPENDING){const r=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,r),u=Math.max(e.duration,o?o.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(u,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ji.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(N.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i?.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:r,payload:o}=i,u=r.decryptdata;if(o&&o.byteLength>0&&u!=null&&u.key&&u.iv&&Ku(u.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),u.key.buffer,u.iv.buffer,ab(u.method)).catch(d=>{throw n.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),d}).then(d=>{const f=self.performance.now();return n.trigger(N.FRAG_DECRYPTED,{frag:r,payload:d,stats:{tstart:c,tdecrypt:f}}),i.payload=d,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===Pe.STOPPED||this.state===Pe.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==Pe.STOPPED&&(this.state=Pe.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,n;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(n=r.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const o=this.media,u=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${o?"attached mediaKeys: "+o.mediaKeys:"detached"})`);return this.warn(u.message),!o||o.mediaKeys?!1:(this.hls.trigger(N.ERROR,{type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_KEYS,fatal:!1,error:u,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?a8.toString(_t.getBuffered(i)):"(detached)"})`),Ui(e)){var n;if(e.type!==it.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(u=>!!o[u])){this.state=Pe.IDLE;return}}const r=(n=this.levels)==null?void 0:n[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=Pe.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,o=!r||r.length===0||r.some(c=>!c),u=new rb(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(u)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;this.fragCurrent=e;const o=t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let u=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Pe.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(g=>{if(!this.fragContextChanged(g.frag))return this.hls.trigger(N.KEY_LOADED,g),this.state===Pe.KEY_LOADING&&(this.state=Pe.IDLE),g}),this.hls.trigger(N.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(u=this.keyLoader.loadClear(e,o.encryptedFragments,this.startFragRequested),u&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(Ui(e)&&(!c||e.sn!==c.sn)){const g=this.shouldLoadParts(t.details,e.end);g!==this.loadingParts&&(this.log(`LL-Part loading ${g?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=g)}if(i=Math.max(e.start,i||0),this.loadingParts&&Ui(e)){const g=o.partList;if(g&&n){i>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);const v=this.getNextPart(g,e,i);if(v>-1){const b=g[v];e=this.fragCurrent=b.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${b.index} (${v}/${g.length-1}) of ${this.fragInfo(e,!1,b)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=b.start+b.duration,this.state=Pe.FRAG_LOADING;let _;return u?_=u.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,b,t,n)).catch(E=>this.handleFragLoadError(E)):_=this.doFragPartsLoad(e,b,t,n).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(N.FRAG_LOADING,{frag:e,part:b,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):_}else if(!e.url||this.loadedEndOfParts(g,i))return Promise.resolve(null)}}if(Ui(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=o.partList)==null?void 0:d.filter(g=>g.loaded).map(g=>`[${g.start}-${g.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),Qe(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Pe.FRAG_LOADING;const f=this.config.progressive&&e.type!==it.SUBTITLE;let m;return f&&u?m=u.then(g=>!g||this.fragContextChanged(g.frag)?null:this.fragmentLoader.load(e,n)).catch(g=>this.handleFragLoadError(g)):m=Promise.all([this.fragmentLoader.load(e,f?n:void 0),u]).then(([g])=>(!f&&n&&n(g),g)).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(N.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):m}doFragPartsLoad(e,t,i,n){return new Promise((r,o)=>{var u;const c=[],d=(u=i.details)==null?void 0:u.partList,f=m=>{this.fragmentLoader.loadPart(e,m,n).then(g=>{c[m.index]=g;const v=g.part;this.hls.trigger(N.FRAG_LOADED,g);const b=a2(i.details,e.sn,m.index+1)||Qw(d,e.sn,m.index+1);if(b)f(b);else return r({frag:e,part:v,partsLoaded:c})}).catch(o)};f(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===ve.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ot.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(N.ERROR,t)}else this.hls.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Pe.PARSING){!this.fragCurrent&&this.state!==Pe.STOPPED&&this.state!==Pe.ERROR&&(this.state=Pe.IDLE);return}const{frag:i,part:n,level:r}=t,o=self.performance.now();i.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const u=this.getLevelDetails(),d=u&&i.sn>u.endSN||this.shouldLoadParts(u,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(i,n,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===it.SUBTITLE)return!1;const o=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:r,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const u=t[n],c=u.details,d=o>-1?a2(c,r,o):null,f=d?d.fragment:Xw(c,r,i);return f?(i&&i!==f&&(f.stats=i.stats),{frag:f,part:d,level:u}):null}bufferFragmentData(e,t,i,n,r){if(this.state!==Pe.PARSING)return;const{data1:o,data2:u}=e;let c=o;if(u&&(c=Fn(o,u)),!c.length)return;const d=this.initPTS[t.cc],f=d?-d.baseTime/d.timescale:void 0,m={type:e.type,frag:t,part:i,chunkMeta:n,offset:f,parent:t.type,data:c};if(this.hls.trigger(N.BUFFER_APPENDING,m),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!_t.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=_t.bufferInfo(t,i,0),r=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),u=Math.max(Math.min(e.start-o,n.end-o),i+o);e.start-u>o&&this.flushMainBuffer(u,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!Qe(n))return null;const o=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,i,n){const r=_t.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&(r.nextStart<=o.end||o.gap)){const u=Math.max(Math.min(r.nextStart,o.end)-t,n);return _t.bufferInfo(e,t,u)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,n=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-t*3,i.maxMaxBufferLength/2,n);return r>=n?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=it.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:r}=this,o=i[0].start,u=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const m=r.initialLiveManifestSize;if(n=o?g:v)||c.start:e;this.log(`Setting startPosition to ${b} to match start frag at live edge. mainStart: ${g} liveSyncPosition: ${v} frag.start: ${(d=c)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=b}}else e<=o&&(c=i[0]);if(!c){const m=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,m,t)}let f=this.filterReplacedPrimary(c,t);if(!f&&c){const m=c.sn-t.startSN;f=this.filterReplacedPrimary(i[m+1]||null,t)}return this.mapToInitFragWhenRequired(f)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Ji.OK||i===Ji.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,r){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){const u=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(u!==null&&i.len+u.len>=r){const c=o.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(u2(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(u2(this.config)&&e.type!==it.SUBTITLE){const i=this.hls.interstitialsManager,n=i?.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&t?.live===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const r=i?.playerQueue;if(r)for(let o=r.length;o--;){const u=r[o].interstitial;if(u.appendInPlace&&e.start>=u.startTime&&e.end<=u.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,r=!1,o=!0;for(let u=0,c=e.length;u-1&&ii.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=xF(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const o=t[r-e.startSN];i.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Nw(e,i.cc,i.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(n=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:o,endSN:u}=i;const{fragmentHint:c}=i,{maxFragLookUpTolerance:d}=n,f=i.partList,m=!!(this.loadingParts&&f!=null&&f.length&&c);m&&!this.bitrateTest&&f[f.length-1].fragment.sn===c.sn&&(o=o.concat(c),u=c.sn);let g;if(et-d||(v=this.media)!=null&&v.paused||!this.startFragRequested?0:d;g=Cl(r,o,e,_)}else g=o[o.length-1];if(g){const b=g.sn-i.startSN,_=this.fragmentTracker.getState(g);if((_===Ji.OK||_===Ji.PARTIAL&&g.gap)&&(r=g),r&&g.sn===r.sn&&(!m||f[0].fragment.sn>g.sn||!i.live)&&g.level===r.level){const L=o[b+1];g.sn${e.startSN} fragments: ${n}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ui(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Pe.FRAG_LOADING_WAITING_RETRY)&&(this.state=Pe.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const L=this.getCurrentContext(t.chunkMeta);L&&(t.frag=L.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var r;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const o=t.details===ve.FRAG_GAP;o&&this.fragmentTracker.fragBuffered(n,!0);const u=t.errorAction;if(!u){this.state=Pe.ERROR;return}const{action:c,flags:d,retryCount:f=0,retryConfig:m}=u,g=!!m,v=g&&c===ys.RetryRequest,b=g&&!u.resolved&&d===bn.MoveAllAlternatesMatchingHost,_=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!v&&b&&Ui(n)&&!n.endList&&_&&!Fw(t))this.resetFragmentErrors(e),this.treatAsGap(n),u.resolved=!0;else if((v||b)&&f=t||i&&!zv(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Pe.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Pe.PARSING||this.state===Pe.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len,t?.duration||10);const o=!r;return o&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===it.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Pe.STOPPED&&(this.state=Pe.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=_t.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===Pe.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Pe.STOPPED&&(this.state=Pe.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){const r=i.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,d)=>{const f=e.elementaryStreams[d];if(f){const m=f.endPTS-f.startPTS;if(m<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${m})`),c||!1;const g=n?0:Kw(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this);return this.hls.trigger(N.LEVEL_PTS_UPDATED,{details:r,level:i,drift:g,type:d,frag:e,start:f.startPTS,end:f.endPTS}),!0}return c},!1)){var u;const c=((u=this.transmuxer)==null?void 0:u.error)===null;if((i.fragmentError===0||c&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),c){const d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Pe.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(N.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===it.MAIN?"level":"track"}fragInfo(e,t=!0,i){var n,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((n=t&&!i?e.startPTS:(i||e).start)!=null?n:NaN).toFixed(3)}-${((r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function u2(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class tL{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=o8(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function o8(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n0)return s.subarray(t,t+i)}function p8(s,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],o=r>>2&15;if(o>12){const v=new Error(`invalid ADTS sampling index:${o}`);s.emit(N.ERROR,N.ERROR,{type:ot.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,fatal:!0,error:v,reason:v.message});return}const u=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,d="mp4a.40."+u,f=n[o];let m=o;(u===5||u===29)&&(m-=3);const g=[u<<3|(m&14)>>1,(m&1)<<7|c<<3];return Zt.log(`manifest codec:${i}, parsed codec:${d}, channels:${c}, rate:${f} (ADTS object type:${u} sampling index:${o})`),{config:g,samplerate:f,channelCount:c,codec:d,parsedCodec:d,manifestCodec:i}}function sL(s,e){return s[e]===255&&(s[e+1]&246)===240}function nL(s,e){return s[e+1]&1?7:9}function db(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function m8(s,e){return e+5=s.length)return!1;const i=db(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||am(s,n)}return!1}function rL(s,e,t,i,n){if(!s.samplerate){const r=p8(e,t,i,n);if(!r)return;ni(s,r)}}function aL(s){return 1024*9e4/s}function v8(s,e){const t=nL(s,e);if(e+t<=s.length){const i=db(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function oL(s,e,t,i,n){const r=aL(s.samplerate),o=i+n*r,u=v8(e,t);let c;if(u){const{frameLength:m,headerLength:g}=u,v=g+m,b=Math.max(0,t+v-e.length);b?(c=new Uint8Array(v-g),c.set(e.subarray(t+g,e.length),0)):c=e.subarray(t+g,t+v);const _={unit:c,pts:o};return b||s.samples.push(_),{sample:_,length:v,missing:b}}const d=e.length-t;return c=new Uint8Array(d),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:o},length:d,missing:-1}}function T8(s,e){return cb(s,e)&&Hm(s,e+6)+10<=s.length-e}function b8(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Hy(s,e=0,t=1/0){return _8(s,e,t,Uint8Array)}function _8(s,e,t,i){const n=x8(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const o=S8(s)?s.byteOffset:0,u=(o+s.byteLength)/r,c=(o+e)/r,d=Math.floor(Math.max(0,Math.min(c,u))),f=Math.floor(Math.min(d+Math.max(t,0),u));return new i(n,d,f-d)}function x8(s){return s instanceof ArrayBuffer?s:s.buffer}function S8(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function E8(s){const e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=s.data.subarray(1).indexOf(0);if(i===-1)return;const n=Sn(Hy(s.data,1,i)),r=s.data[2+i],o=s.data.subarray(3+i).indexOf(0);if(o===-1)return;const u=Sn(Hy(s.data,3+i,o));let c;return n==="-->"?c=Sn(Hy(s.data,4+i+o)):c=b8(s.data.subarray(4+i+o)),e.mimeType=n,e.pictureType=r,e.description=u,e.data=c,e}function A8(s){if(s.size<2)return;const e=Sn(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function C8(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=Sn(s.data.subarray(t),!0);t+=i.length+1;const n=Sn(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Sn(s.data.subarray(1));return{key:s.type,info:"",data:e}}function D8(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=Sn(s.data.subarray(t),!0);t+=i.length+1;const n=Sn(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Sn(s.data);return{key:s.type,info:"",data:e}}function w8(s){return s.type==="PRIV"?A8(s):s.type[0]==="W"?D8(s):s.type==="APIC"?E8(s):C8(s)}function L8(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Hm(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const tp=10,I8=10;function lL(s){let e=0;const t=[];for(;cb(s,e);){const i=Hm(s,e+6);s[e+5]>>6&1&&(e+=tp),e+=tp;const n=e+i;for(;e+I80&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:xn.audioId3,duration:Number.POSITIVE_INFINITY});n{if(Qe(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let ip=null;const O8=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],P8=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],M8=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],N8=[0,1,1,4];function cL(s,e,t,i,n){if(t+24>e.length)return;const r=dL(e,t);if(r&&t+r.frameLength<=e.length){const o=r.samplesPerFrame*9e4/r.sampleRate,u=i+n*o,c={unit:e.subarray(t,t+r.frameLength),pts:u,dts:u};return s.config=[],s.channelCount=r.channelCount,s.samplerate=r.sampleRate,s.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function dL(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,n=s[e+2]>>4&15,r=s[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&r!==3){const o=s[e+2]>>1&1,u=s[e+3]>>6,c=t===3?3-i:i===3?3:4,d=O8[c*14+n-1]*1e3,m=P8[(t===3?0:t===2?1:2)*3+r],g=u===3?1:2,v=M8[t][i],b=N8[i],_=v*8*b,E=Math.floor(v*d/m+o)*b;if(ip===null){const w=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ip=w?parseInt(w[1]):0}return ip&&ip<=87&&i===2&&d>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:m,channelCount:g,frameLength:E,samplesPerFrame:_}}}function pb(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function hL(s,e){return e+1{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=s[e];const u=Math.min(i,8),c=8-u;r[0]=4278190080>>>24+c<>c,t=t?t<e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const u=[48e3,44100,32e3][r],c=e[t+4]&63,f=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+r]*2;if(t+f>e.length)return-1;const m=e[t+6]>>5;let g=0;m===2?g+=2:(m&1&&m!==1&&(g+=2),m&4&&(g+=2));const v=(e[t+6]<<8|e[t+7])>>12-g&1,_=[2,1,2,3,3,4,4,5][m]+v,E=e[t+5]>>3,L=e[t+5]&7,I=new Uint8Array([r<<6|E<<1|L>>2,(L&3)<<6|m<<3|v<<2|c>>4,c<<4&224]),w=1536/u*9e4,F=i+n*w,U=e.subarray(t,t+f);return s.config=I,s.channelCount=_,s.samplerate=u,s.samples.push({unit:U,pts:F}),f}class $8 extends fb{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=eh(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&hb(t)!==void 0&&pL(e,i)<=16)return!1;for(let n=e.length;i{const o=YB(r);if(j8.test(o.schemeIdUri)){const u=d2(o,t);let c=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=o.payload;i.samples.push({data:d,len:d.byteLength,dts:u,pts:u,type:xn.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const u=d2(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:u,pts:u,type:xn.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function d2(s,e){return Qe(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class G8{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new nb(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ao.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const r=n.subarray(16,n.length-n.length%16),o=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(o).then(u=>{const c=new Uint8Array(u);n.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let r=32;r{r.data=this.getAvcDecryptedUnit(o,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)}).catch(n)}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const r=e[t].units;for(;!(i>=r.length);i++){const o=r[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,n,o),!this.decrypter.isSync()))return}}}}class gL{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;n=r[r.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const r=i[n-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let r=e.naluState||0;const o=r,u=[];let c=0,d,f,m,g=-1,v=0;for(r===-1&&(g=0,v=this.getNALuType(t,0),r=0,c=1);c=0){const b={data:t.subarray(g,f),type:v};u.push(b)}else{const b=this.getLastNalUnit(e.samples);b&&(o&&c<=4-o&&b.state&&(b.data=b.data.subarray(0,b.data.byteLength-o)),f>0&&(b.data=Fn(b.data,t.subarray(0,f)),b.state=0))}c=0&&r>=0){const b={data:t.subarray(g,n),type:v,state:r};u.push(b)}if(u.length===0){const b=this.getLastNalUnit(e.samples);b&&(b.data=Fn(b.data,t))}return e.naluState=r,u}}class Gd{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,n=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");n.set(e.subarray(i,i+r)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&Zt.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class V8 extends gL{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let o=this.VideoSample,u,c=!1;i.data=null,o&&r.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(d=>{var f,m;switch(d.type){case 1:{let _=!1;u=!0;const E=d.data;if(c&&E.length>4){const L=this.readSliceType(E);(L===2||L===4||L===7||L===9)&&(_=!0)}if(_){var g;(g=o)!=null&&g.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=_;break}case 5:u=!0,(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:{u=!0,eb(d.data,1,i.pts,t.samples);break}case 7:{var v,b;u=!0,c=!0;const _=d.data,E=this.readSPS(_);if(!e.sps||e.width!==E.width||e.height!==E.height||((v=e.pixelRatio)==null?void 0:v[0])!==E.pixelRatio[0]||((b=e.pixelRatio)==null?void 0:b[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[_];const L=_.subarray(1,4);let I="avc1.";for(let w=0;w<3;w++){let F=L[w].toString(16);F.length<2&&(F="0"+F),I+=F}e.codec=I}break}case 8:u=!0,e.pps=[d.data];break;case 9:u=!0,e.audFound=!0,(m=o)!=null&&m.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}o&&u&&o.units.push(d)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Gd(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let o=0;o{var f,m;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,u=!0;break;case 16:case 17:case 18:case 21:if(u=!0,c){var g;(g=o)!=null&&g.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:u=!0,(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:u=!0,eb(d.data,2,i.pts,t.samples);break;case 32:u=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ni(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(u=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const v=this.readSPS(d.data);e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const b in v.params)e.params[b]=v.params[b]}this.pushParameterSet(e.sps,d.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(u=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const v=this.readPPS(d.data);for(const b in v)e.params[b]=v[b]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:u=!0,e.audFound=!0,(m=o)!=null&&m.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:u=!1;break}o&&u&&o.units.push(d)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Gd(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:n}}readSPS(e){const t=new Gd(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),r=t.readBoolean(),o=t.readBits(5),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),f=t.readUByte(),m=t.readUByte(),g=t.readUByte(),v=t.readUByte(),b=t.readUByte(),_=t.readUByte(),E=t.readUByte(),L=t.readUByte(),I=[],w=[];for(let Fe=0;Fe0)for(let Fe=i;Fe<8;Fe++)t.readBits(2);for(let Fe=0;Fe1&&t.readEG();for(let $e=0;$e<_e;$e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const te=t.readUEG();let oe=0;for(let Fe=0;Fe0&&He<16?(ie=Xe[He-1],he=We[He-1]):He===255&&(ie=t.readBits(16),he=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Ee=t.readBoolean(),Ee&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(be=t.readBits(32),Ue=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const We=t.readBoolean(),pt=t.readBoolean();let mt=!1;(We||pt)&&(mt=t.readBoolean(),mt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),mt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let jt=0;jt<=i;jt++){Ce=t.readBoolean();const fi=Ce||t.readBoolean();let Ai=!1;fi?t.readEG():Ai=t.readBoolean();const Yi=Ai?1:t.readUEG()+1;if(We)for(let ts=0;ts>Fe&1)<<31-Fe)>>>0;let st=Je.toString(16);return o===1&&st==="2"&&(st="6"),{codecString:`hvc1.${lt}${o}.${st}.${r?"H":"L"}${L}.B0`,params:{general_tier_flag:r,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[u,c,d,f],general_constraint_indicator_flags:[m,g,v,b,_,E],general_level_idc:L,bit_depth:X+8,bit_depth_luma_minus8:X,bit_depth_chroma_minus8:ee,min_spatial_segmentation_idc:$,chroma_format_idc:F,frame_rate:{fixed:Ce,fps:Ue/be}},width:Ve,height:tt,pixelRatio:[ie,he]}}readPPS(e){const t=new Gd(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),r=t.readBoolean();let o=1;return r&&n?o=0:r?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const ls=188;class go{constructor(e,t,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(e,t){const i=go.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(ls*5,t-ls)+1,n=0;for(;n1&&(o===0&&u>2||c+ls>i))return o}else{if(u)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:xw[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=go.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=go.createTrack("audio",n),this._id3Track=go.createTrack("id3"),this._txtTrack=go.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let r;const o=this._videoTrack,u=this._audioTrack,c=this._id3Track,d=this._txtTrack;let f=o.pid,m=o.pesData,g=u.pid,v=c.pid,b=u.pesData,_=c.pesData,E=null,L=this.pmtParsed,I=this._pmtId,w=e.length;if(this.remainderData&&(e=Fn(this.remainderData,e),w=e.length,this.remainderData=null),w>4;let K;if(R>1){if(K=B+5+e[B+4],K===B+ls)continue}else K=B+4;switch(k){case f:q&&(m&&(r=Cu(m,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,d,r,!1)),m={data:[],size:0}),m&&(m.data.push(e.subarray(K,B+ls)),m.size+=B+ls-K);break;case g:if(q){if(b&&(r=Cu(b,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,r);break;case"mp3":this.parseMPEGPES(u,r);break;case"ac3":this.parseAC3PES(u,r);break}b={data:[],size:0}}b&&(b.data.push(e.subarray(K,B+ls)),b.size+=B+ls-K);break;case v:q&&(_&&(r=Cu(_,this.logger))&&this.parseID3PES(c,r),_={data:[],size:0}),_&&(_.data.push(e.subarray(K,B+ls)),_.size+=B+ls-K);break;case 0:q&&(K+=e[K]+1),I=this._pmtId=z8(e,K);break;case I:{q&&(K+=e[K]+1);const X=K8(e,K,this.typeSupported,i,this.observer,this.logger);f=X.videoPid,f>0&&(o.pid=f,o.segmentCodec=X.segmentVideoCodec),g=X.audioPid,g>0&&(u.pid=g,u.segmentCodec=X.segmentAudioCodec),v=X.id3Pid,v>0&&(c.pid=v),E!==null&&!L&&(this.logger.warn(`MPEG-TS PMT found at ${B} after unknown PID '${E}'. Backtracking to sync byte @${F} to parse all TS packets.`),E=null,B=F-188),L=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=k;break}}else U++;U>0&&Zv(this.observer,new Error(`Found ${U} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=m,u.pesData=b,c.pesData=_;const V={audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};return n&&this.extractRemainingSamples(V),V}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:r}=e,o=i.pesData,u=t.pesData,c=n.pesData;let d;if(o&&(d=Cu(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,d,!0),i.pesData=null)):i.pesData=o,u&&(d=Cu(u,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else u!=null&&u.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=u;c&&(d=Cu(c,this.logger))?(this.parseID3PES(n,d),n.pesData=null):n.pesData=c}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new G8(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new V8:e==="hevc"&&(this.videoParser=new q8))}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:r}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let r=t.data;if(n){this.aacOverFlow=null;const m=n.missing,g=n.sample.unit.byteLength;if(m===-1)r=Fn(n.sample.unit,r);else{const v=g-m;n.sample.unit.set(r.subarray(0,m),v),e.samples.push(n.sample),i=n.missing}}let o,u;for(o=i,u=r.length;o0;)u+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=ni({},t,{type:this._videoTrack?xn.emsg:xn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Qv(s,e){return((s[e+1]&31)<<8)+s[e+2]}function z8(s,e){return(s[e+10]&31)<<8|s[e+11]}function K8(s,e,t,i,n,r){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=(s[e+1]&15)<<8|s[e+2],c=e+3+u-4,d=(s[e+10]&15)<<8|s[e+11];for(e+=12+d;e0){let g=e+5,v=m;for(;v>2;){s[g]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=f,o.segmentAudioCodec="ac3"));const _=s[g+1]+2;g+=_,v-=_}}break;case 194:case 135:return Zv(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),o;case 36:o.videoPid===-1&&(o.videoPid=f,o.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=m+5}return o}function Zv(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(N.ERROR,N.ERROR,{type:ot.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Gy(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Cu(s,e){let t=0,i,n,r,o,u;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Fn(c[0],c[1]),c.splice(1,1);if(i=c[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>s.size-6)return null;const f=i[7];f&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,f&64?(u=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-u>60*9e4&&(e.warn(`${Math.round((o-u)/9e4)}s delta between PTS and DTS, align them`),o=u)):u=o),r=i[8];let m=r+9;if(s.size<=m)return null;s.size-=m;const g=new Uint8Array(s.size);for(let v=0,b=c.length;v_){m-=_;continue}else i=i.subarray(m),_-=m,m=0;g.set(i,t),t+=_}return n&&(n-=r+3),{data:g,pts:o,dts:u,len:n}}return null}class Y8{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const co=Math.pow(2,32)-1;class ge{static init(){ge.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in ge.types)ge.types.hasOwnProperty(e)&&(ge.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);ge.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);ge.STTS=ge.STSC=ge.STCO=r,ge.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ge.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),ge.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),ge.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),u=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);ge.FTYP=ge.box(ge.types.ftyp,o,c,o,u),ge.DINF=ge.box(ge.types.dinf,ge.box(ge.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=i&255,o.set(e,4),n=0,i=8;n>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return ge.box(ge.types.mdia,ge.mdhd(e.timescale||0,e.duration||0),ge.hdlr(e.type),ge.minf(e))}static mfhd(e){return ge.box(ge.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?ge.box(ge.types.minf,ge.box(ge.types.smhd,ge.SMHD),ge.DINF,ge.stbl(e)):ge.box(ge.types.minf,ge.box(ge.types.vmhd,ge.VMHD),ge.DINF,ge.stbl(e))}static moof(e,t,i){return ge.box(ge.types.moof,ge.mfhd(e),ge.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=ge.trak(e[t]);return ge.box.apply(null,[ge.types.moov,ge.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(ge.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=ge.trex(e[t]);return ge.box.apply(null,[ge.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(co+1)),n=Math.floor(t%(co+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return ge.box(ge.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,r;for(n=0;n>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(r));const u=ge.box(ge.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),c=e.width,d=e.height,f=e.pixelRatio[0],m=e.pixelRatio[1];return ge.box(ge.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u,ge.box(ge.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ge.box(ge.types.pasp,new Uint8Array([f>>24,f>>16&255,f>>8&255,f&255,m>>24,m>>16&255,m>>8&255,m&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return ge.box(ge.types.mp4a,ge.audioStsd(e),ge.box(ge.types.esds,ge.esds(e)))}static mp3(e){return ge.box(ge.types[".mp3"],ge.audioStsd(e))}static ac3(e){return ge.box(ge.types["ac-3"],ge.audioStsd(e),ge.box(ge.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return ge.box(ge.types.stsd,ge.STSD,ge.mp4a(e));if(t==="ac3"&&e.config)return ge.box(ge.types.stsd,ge.STSD,ge.ac3(e));if(t==="mp3"&&e.codec==="mp3")return ge.box(ge.types.stsd,ge.STSD,ge.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return ge.box(ge.types.stsd,ge.STSD,ge.avc1(e));if(t==="hevc"&&e.vps)return ge.box(ge.types.stsd,ge.STSD,ge.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,r=e.height||0,o=Math.floor(i/(co+1)),u=Math.floor(i%(co+1));return ge.box(ge.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,u>>24,u>>16&255,u>>8&255,u&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=ge.sdtp(e),n=e.id,r=Math.floor(t/(co+1)),o=Math.floor(t%(co+1));return ge.box(ge.types.traf,ge.box(ge.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),ge.box(ge.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,o>>24,o>>16&255,o>>8&255,o&255])),ge.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,ge.box(ge.types.trak,ge.tkhd(e),ge.mdia(e))}static trex(e){const t=e.id;return ge.box(ge.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,r=12+16*n,o=new Uint8Array(r);let u,c,d,f,m,g;for(t+=8+r,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),u=0;u>>24&255,d>>>16&255,d>>>8&255,d&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255,m.isLeading<<2|m.dependsOn,m.isDependedOn<<6|m.hasRedundancy<<4|m.paddingValue<<1|m.isNonSync,m.degradPrio&61440,m.degradPrio&15,g>>>24&255,g>>>16&255,g>>>8&255,g&255],12+16*u);return ge.box(ge.types.trun,o)}static initSegment(e){ge.types||ge.init();const t=ge.moov(e);return Fn(ge.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let o=r.length;for(let b=0;b>8,i[b][_].length&255]),o),o+=2,u.set(i[b][_],o),o+=i[b][_].length}const d=ge.box(ge.types.hvcC,u),f=e.width,m=e.height,g=e.pixelRatio[0],v=e.pixelRatio[1];return ge.box(ge.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,f&255,m>>8&255,m&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,ge.box(ge.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ge.box(ge.types.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,g&255,v>>24,v>>16&255,v>>8&255,v&255])))}}ge.types=void 0;ge.HDLR_TYPES=void 0;ge.STTS=void 0;ge.STSC=void 0;ge.STCO=void 0;ge.STSZ=void 0;ge.VMHD=void 0;ge.SMHD=void 0;ge.STSD=void 0;ge.FTYP=void 0;ge.DINF=void 0;const yL=9e4;function mb(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function W8(s,e,t=1,i=!1){return mb(s,e,1/t,i)}function Ed(s,e=!1){return mb(s,1e3,1/yL,e)}function X8(s,e=1){return mb(s,yL,1/e)}function h2(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const Q8=10*1e3,Z8=1024,J8=1152,eU=1536;let Du=null,Vy=null;function f2(s,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class xp extends jn{constructor(e,t,i,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Du===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Du=o?parseInt(o[1]):0}if(Vy===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Vy=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&h2(t)} > ${e&&h2(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((r,o)=>{let u=o.pts,c=u-r;return c<-4294967296&&(t=!0,u=_n(u,i),c=u-r),c>0?r:u},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,o,u,c){let d,f,m,g,v,b,_=r,E=r;const L=e.pid>-1,I=t.pid>-1,w=t.samples.length,F=e.samples.length>0,U=u&&w>0||w>1;if((!L||F)&&(!I||U)||this.ISGenerated||u){if(this.ISGenerated){var B,q,k,R;const le=this.videoTrackConfig;(le&&(t.width!==le.width||t.height!==le.height||((B=t.pixelRatio)==null?void 0:B[0])!==((q=le.pixelRatio)==null?void 0:q[0])||((k=t.pixelRatio)==null?void 0:k[1])!==((R=le.pixelRatio)==null?void 0:R[1]))||!le&&U||this.nextAudioTs===null&&F)&&this.resetInitSegment()}this.ISGenerated||(m=this.generateIS(e,t,r,o));const K=this.isVideoContiguous;let X=-1,ee;if(U&&(X=tU(t.samples),!K&&this.config.forceKeyFrameOnDiscontinuity))if(b=!0,X>0){this.warn(`Dropped ${X} out of ${w} video samples due to a missing keyframe`);const le=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(X),t.dropped+=X,E+=(t.samples[0].pts-le)/t.inputTimeScale,ee=E}else X===-1&&(this.warn(`No keyframe found out of ${w} video samples`),b=!1);if(this.ISGenerated){if(F&&U){const le=this.getVideoStartPts(t.samples),Y=(_n(e.samples[0].pts,le)-le)/t.inputTimeScale;_+=Math.max(0,Y),E+=Math.max(0,-Y)}if(F){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),m=this.generateIS(e,t,r,o)),f=this.remuxAudio(e,_,this.isAudioContiguous,o,I||U||c===it.AUDIO?E:void 0),U){const le=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),m=this.generateIS(e,t,r,o)),d=this.remuxVideo(t,E,K,le)}}else U&&(d=this.remuxVideo(t,E,K,0));d&&(d.firstKeyFrame=X,d.independent=X!==-1,d.firstKeyFramePTS=ee)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(v=vL(i,r,this._initPTS,this._initDTS)),n.samples.length&&(g=TL(n,r,this._initPTS))),{audio:f,video:d,initSegment:m,independent:b,text:g,id3:v}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let o=_n(e,r);if(o0?$-1:$].dts&&(I=!0)}I&&o.sort(function($,ie){const he=$.dts-ie.dts,Ce=$.pts-ie.pts;return he||Ce}),b=o[0].dts,_=o[o.length-1].dts;const F=_-b,U=F?Math.round(F/(c-1)):v||e.inputTimeScale/30;if(i){const $=b-w,ie=$>U,he=$<-1;if((ie||he)&&(ie?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ed($,!0)} ms (${$}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ed(-$,!0)} ms (${$}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!he||w>=o[0].pts||Du)){b=w;const Ce=o[0].pts-$;if(ie)o[0].dts=b,o[0].pts=Ce;else{let be=!0;for(let Ue=0;UeCe&&be);Ue++){const Ee=o[Ue].pts;if(o[Ue].dts-=$,o[Ue].pts-=$,Ue0?ie.dts-o[$-1].dts:U;if(be=$>0?ie.pts-o[$-1].pts:U,Ee.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ve=Math.floor(Ee.maxBufferHole*r),tt=(n?E+n*r:this.nextAudioTs+f)-ie.pts;tt>Ve?(v=tt-je,v<0?v=je:X=!0,this.log(`It is approximately ${tt/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=je}else v=je}const Ue=Math.round(ie.pts-ie.dts);ee=Math.min(ee,v),ae=Math.max(ae,v),le=Math.min(le,be),Y=Math.max(Y,be),u.push(f2(ie.key,v,Ce,Ue))}if(u.length){if(Du){if(Du<70){const $=u[0].flags;$.dependsOn=2,$.isNonSync=0}}else if(Vy&&Y-le0&&(n&&Math.abs(w-(L+I))<9e3||Math.abs(_n(_[0].pts,w)-(L+I))<20*f),_.forEach(function(Y){Y.pts=_n(Y.pts,w)}),!i||L<0){const Y=_.length;if(_=_.filter(Q=>Q.pts>=0),Y!==_.length&&this.warn(`Removed ${_.length-Y} of ${Y} samples (initPTS ${I} / ${o})`),!_.length)return;r===0?L=0:n&&!b?L=Math.max(0,w-I):L=_[0].pts-I}if(e.segmentCodec==="aac"){const Y=this.config.maxAudioFramesDrift;for(let Q=0,te=L+I;Q<_.length;Q++){const oe=_[Q],de=oe.pts,$=de-te,ie=Math.abs(1e3*$/o);if($<=-Y*f&&b)Q===0&&(this.warn(`Audio frame @ ${(de/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*$/o)} ms.`),this.nextAudioTs=L=de-I,te=de);else if($>=Y*f&&ie0){B+=E;try{V=new Uint8Array(B)}catch(ie){this.observer.emit(N.ERROR,N.ERROR,{type:ot.MUX_ERROR,details:ve.REMUX_ALLOC_ERROR,fatal:!1,error:ie,bytes:B,reason:`fail allocating audio mdat ${B}`});return}g||(new DataView(V.buffer).setUint32(0,B),V.set(ge.types.mdat,4))}else return;V.set(oe,E);const $=oe.byteLength;E+=$,v.push(f2(!0,d,$,0)),U=de}const k=v.length;if(!k)return;const R=v[v.length-1];L=U-I,this.nextAudioTs=L+c*R.duration;const K=g?new Uint8Array(0):ge.moof(e.sequenceNumber++,F/c,ni({},e,{samples:v}));e.samples=[];const X=(F-I)/o,ee=this.nextAudioTs/o,ae={data1:K,data2:V,startPTS:X,endPTS:ee,startDTS:X,endDTS:ee,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,ae}}function _n(s,e){let t;if(e===null)return s;for(e4294967296;)s+=t;return s}function tU(s){for(let e=0;eo.pts-u.pts);const r=s.samples;return s.samples=[],{samples:r}}class iU extends jn{constructor(e,t,i,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:o}=this.initData=Aw(e);if(t)GB(e,t);else{const c=r||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(i=p2(r,oi.AUDIO,this)),o&&(n=p2(o,oi.VIDEO,this));const u={};r&&o?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:r?u.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}remux(e,t,i,n,r,o){var u,c;let{initPTS:d,lastEndTime:f}=this;const m={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};Qe(f)||(f=this.lastEndTime=r||0);const g=t.samples;if(!g.length)return m;const v={initPTS:void 0,timescale:void 0,trackId:void 0};let b=this.initData;if((u=b)!=null&&u.length||(this.generateInitSegment(g),b=this.initData),!((c=b)!=null&&c.length))return this.warn("Failed to generate initSegment."),m;this.emitInitSegment&&(v.tracks=this.initTracks,this.emitInitSegment=!1);const _=qB(g,b,this),E=b.audio?_[b.audio.id]:null,L=b.video?_[b.video.id]:null,I=sp(L,1/0),w=sp(E,1/0),F=sp(L,0,!0),U=sp(E,0,!0);let V=r,B=0;const q=E&&(!L||!d&&w0?this.lastEndTime=K:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const X=!!b.audio,ee=!!b.video;let le="";X&&(le+="audio"),ee&&(le+="video");const ae=(b.audio?b.audio.encrypted:!1)||(b.video?b.video.encrypted:!1),Y={data1:g,startPTS:R,startDTS:R,endPTS:K,endDTS:K,type:le,hasAudio:X,hasVideo:ee,nb:1,dropped:0,encrypted:ae};m.audio=X&&!ee?Y:void 0,m.video=ee?Y:void 0;const Q=L?.sampleCount;if(Q){const te=L.keyFrameIndex,oe=te!==-1;Y.nb=Q,Y.dropped=te===0||this.isVideoContiguous?0:oe?te:Q,Y.independent=oe,Y.firstKeyFrame=te,oe&&L.keyFrameStart&&(Y.firstKeyFramePTS=(L.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(m.independent=oe),this.isVideoContiguous||(this.isVideoContiguous=oe),Y.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${te}/${Q} dropped: ${Y.dropped} start: ${Y.firstKeyFramePTS||"NA"}`)}return m.initSegment=v,m.id3=vL(i,r,d,d),n.samples.length&&(m.text=TL(n,r,d)),m}}function sp(s,e,t=!1){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function sU(s,e,t,i){if(s===null)return!0;const n=Math.max(i,1),r=e-s.baseTime/s.timescale;return Math.abs(r-t)>n}function p2(s,e,t){const i=s.codec;return i&&i.length>4?i:e===oi.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Zp(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let fa;try{fa=self.performance.now.bind(self.performance)}catch{fa=Date.now}const Sp=[{demux:H8,remux:iU},{demux:go,remux:xp},{demux:F8,remux:xp},{demux:$8,remux:xp}];Sp.splice(2,0,{demux:U8,remux:xp});class m2{constructor(e,t,i,n,r,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=fa();let o=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:f,trackSwitch:m,accurateTimeOffset:g,timeOffset:v,initSegmentChange:b}=n||u,{audioCodec:_,videoCodec:E,defaultInitPts:L,duration:I,initSegmentData:w}=c,F=nU(o,t);if(F&&Ku(F.method)){const q=this.getDecrypter(),k=ab(F.method);if(q.isSync()){let R=q.softwareDecrypt(o,F.key.buffer,F.iv.buffer,k);if(i.part>-1){const X=q.flush();R=X&&X.buffer}if(!R)return r.executeEnd=fa(),qy(i);o=new Uint8Array(R)}else return this.asyncResult=!0,this.decryptionPromise=q.webCryptoDecrypt(o,F.key.buffer,F.iv.buffer,k).then(R=>{const K=this.push(R,null,i);return this.decryptionPromise=null,K}),this.decryptionPromise}const U=this.needsProbing(f,m);if(U){const q=this.configureTransmuxer(o);if(q)return this.logger.warn(`[transmuxer] ${q.message}`),this.observer.emit(N.ERROR,N.ERROR,{type:ot.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,fatal:!1,error:q,reason:q.message}),r.executeEnd=fa(),qy(i)}(f||m||b||U)&&this.resetInitSegment(w,_,E,I,t),(f||b||U)&&this.resetInitialTimestamp(L),d||this.resetContiguity();const V=this.transmux(o,F,v,g,i);this.asyncResult=th(V);const B=this.currentTransmuxState;return B.contiguous=!0,B.discontinuity=!1,B.trackSwitch=!1,r.executeEnd=fa(),V}flush(e){const t=e.transmuxing;t.executeStart=fa();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const o=[],{timeOffset:u}=n;if(i){const m=i.flush();m&&o.push(this.push(m.buffer,null,e))}const{demuxer:c,remuxer:d}=this;if(!c||!d){t.executeEnd=fa();const m=[qy(e)];return this.asyncResult?Promise.resolve(m):m}const f=c.flush(u);return th(f)?(this.asyncResult=!0,f.then(m=>(this.flushRemux(o,m,e),o))):(this.flushRemux(o,f,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:o,textTrack:u}=t,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===it.MAIN?"level":"track"} ${i.level}`);const f=this.remuxer.remux(n,r,o,u,d,c,!0,this.id);e.push({remuxResult:f,chunkMeta:i}),i.transmuxing.executeEnd=fa()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,r){const{demuxer:o,remuxer:u}=this;!o||!u||(o.resetInitSegment(e,t,i,n),u.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,r){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,n,r):o=this.transmuxUnencrypted(e,i,n,r),o}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:o,id3Track:u,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,o,u,c,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let r;for(let m=0,g=Sp.length;m0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const qy=s=>({remuxResult:{},chunkMeta:s});function th(s){return"then"in s&&s.then instanceof Function}class rU{constructor(e,t,i,n,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=n,this.defaultInitPts=r||null}}class aU{constructor(e,t,i,n,r,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=r,this.initSegmentChange=o}}let g2=0;class bL{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=g2++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,f=this.hls;if(!(!f||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var m;const g=(m=this.workerContext)==null?void 0:m.objectURL;g&&self.URL.revokeObjectURL(g);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{f.logger[d.data.logType]&&f.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,f.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===N.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new ub,this.observer.on(N.FRAG_DECRYPTED,o),this.observer.on(N.ERROR,o);const u=k1(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||c8()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=h8(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=d8());const{worker:f}=this.workerContext;f.addEventListener("message",this.onWorkerMessage),f.addEventListener("error",this.onWorkerError),f.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:t,config:ui(r)})}catch(f){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,f),this.terminateWorker(),this.error=null,this.transmuxer=new m2(this.observer,u,r,"",t,e.logger)}return}}this.transmuxer=new m2(this.observer,u,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=g2++;const t=this.hls.config,i=k1(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:ui(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),f8(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,r,o,u,c,d,f){var m,g;d.transmuxing.start=self.performance.now();const{instanceNo:v,transmuxer:b}=this,_=o?o.start:r.start,E=r.decryptdata,L=this.frag,I=!(L&&r.cc===L.cc),w=!(L&&d.level===L.level),F=L?d.sn-L.sn:-1,U=this.part?d.part-this.part.index:-1,V=F===0&&d.id>1&&d.id===L?.stats.chunkCount,B=!w&&(F===1||F===0&&(U===1||V&&U<=0)),q=self.performance.now();(w||F||r.stats.parsing.start===0)&&(r.stats.parsing.start=q),o&&(U||!B)&&(o.stats.parsing.start=q);const k=!(L&&((m=r.initSegment)==null?void 0:m.url)===((g=L.initSegment)==null?void 0:g.url)),R=new aU(I,B,c,w,_,k);if(!B||I||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===it.MAIN?"level":"track"}: ${d.level} id: ${d.id} - discontinuity: ${I} - trackSwitch: ${w} - contiguous: ${B} - accurateTimeOffset: ${c} - timeOffset: ${_} - initSegmentChange: ${k}`);const K=new rU(i,n,t,u,f);this.configureTransmuxer(K)}if(this.frag=r,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:v,cmd:"demux",data:e,decryptdata:E,chunkMeta:d,state:R},e instanceof ArrayBuffer?[e]:[]);else if(b){const K=b.push(e,E,d,R);th(K)?K.then(X=>{this.handleTransmuxComplete(X)}).catch(X=>{this.transmuxerError(X,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(K)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const n=i.flush(e);th(n)?n.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const y2=100;class oU extends lb{constructor(e,t,i){super(e,t,i,"audio-stream-controller",it.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(N.LEVEL_LOADED,this.onLevelLoaded,this),e.on(N.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(N.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(N.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(N.BUFFER_RESET,this.onBufferReset,this),e.on(N.BUFFER_CREATED,this.onBufferCreated,this),e.on(N.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(N.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(N.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(N.FRAG_LOADING,this.onFragLoading,this),e.on(N.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(N.LEVEL_LOADED,this.onLevelLoaded,this),e.off(N.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(N.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(N.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(N.BUFFER_RESET,this.onBufferReset,this),e.off(N.BUFFER_CREATED,this.onBufferCreated,this),e.off(N.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(N.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(N.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(N.FRAG_LOADING,this.onFragLoading,this),e.off(N.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:o}){if(i===it.MAIN){const u=t.cc,c=this.fragCurrent;if(this.initPTS[u]={baseTime:n,timescale:r,trackId:o},this.log(`InitPTS for cc: ${u} found from main: ${n/r} (${n}/${r}) trackId: ${o}`),this.mainAnchor=t,this.state===Pe.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==u)&&this.syncWithAnchor(t,d?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==u?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===Pe.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const n=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&n?.cc===t.cc)return;const r=(n||e).cc,o=this.getLevelDetails(),u=this.getLoadPosition(),c=Nw(o,r,u);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===Pe.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Pe.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(y2),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Pe.IDLE):this.state=Pe.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Pe.IDLE:this.doTickIdle();break;case Pe.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e?.[t],n=i?.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=Pe.WAITING_INIT_PTS}break}case Pe.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Pe.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,o=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Pe.FRAG_LOADING;const u=n.flush().buffer,c={frag:t,part:i,payload:u,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,e.frag)}else this.state=Pe.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:r}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[r]))return;const u=i[r],c=u.details;if(!c||this.waitForLive(u)||this.waitForCdnTuneIn(c)){this.state=Pe.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,oi.AUDIO,it.AUDIO));const f=this.getFwdBufferInfo(d,it.AUDIO);if(f===null)return;if(!this.switchingTrack&&this._streamEnded(f,c)){t.trigger(N.BUFFER_EOS,{type:"audio"}),this.state=Pe.ENDED;return}const m=f.len,g=t.maxBufferLength,v=c.fragments,b=v[0].start,_=this.getLoadPosition(),E=this.flushing?_:f.end;if(this.switchingTrack&&n){const w=_;c.PTSKnown&&wb||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=b+.05)}if(m>=g&&!this.switchingTrack&&EI.end){const F=this.fragmentTracker.getFragAtPos(E,it.MAIN);F&&F.end>I.end&&(I=F,this.mainFragLoading={frag:F,targetBufferTime:null})}if(L.start>I.end)return}this.loadFragment(L,u,E)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Zd(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Pe.STOPPED&&(this.setInterval(y2),this.state=Pe.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(N.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:o,groupId:u,track:c}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${c.name}" of "${u}"`);return}const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==Pe.STOPPED&&(this.state=Pe.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${c.name}" of "${u}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const f=n[o];let m=0;if(r.live||(i=f.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(f.details){var g;m=this.alignPlaylists(r,f.details,(g=this.levelLastLoaded)==null?void 0:g.details)}r.alignedSliding||(eL(r,d),r.alignedSliding||rm(r,d),m=r.fragmentStart)}f.details=r,this.levelLastLoaded=f,this.startFragRequested||this.setStartPosition(d,m),this.hls.trigger(N.AUDIO_TRACK_UPDATED,{details:r,id:o,groupId:t.groupId}),this.state===Pe.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=Pe.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:o,trackId:u,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const d=c[u];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const f=d.details;if(!f){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const m=o.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let g=this.transmuxer;g||(g=this.transmuxer=new bL(this.hls,it.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const v=this.initPTS[i.cc],b=(t=i.initSegment)==null?void 0:t.data;if(v!==void 0){const E=n?n.index:-1,L=E!==-1,I=new rb(i.level,i.sn,i.stats.chunkCount,r.byteLength,E,L);g.push(r,b,m,"",i,n,f.totalduration,!1,I,v)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${f.startSN} ,${f.endSN}],track ${u}`);const{cache:_}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new tL,complete:!1};_.push(new Uint8Array(r)),this.state!==Pe.STOPPED&&(this.state=Pe.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===it.MAIN&&Ui(t.frag)&&(this.mainFragLoading=t,this.state===Pe.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==it.AUDIO){!this.audioOnly&&i.type===it.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ui(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(N.AUDIO_TRACK_SWITCHED,Qt({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=Pe.ERROR;return}switch(t.details){case ve.FRAG_GAP:case ve.FRAG_PARSING_ERROR:case ve.FRAG_DECRYPT_ERROR:case ve.FRAG_LOAD_ERROR:case ve.FRAG_LOAD_TIMEOUT:case ve.KEY_LOAD_ERROR:case ve.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(it.AUDIO,t);break;case ve.AUDIO_TRACK_LOAD_ERROR:case ve.AUDIO_TRACK_LOAD_TIMEOUT:case ve.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Pe.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Rt.AUDIO_TRACK&&(this.state=Pe.IDLE);break;case ve.BUFFER_ADD_CODEC_ERROR:case ve.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case ve.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ve.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==oi.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==oi.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Pe.ENDED&&(this.state=Pe.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,it.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:o}=e,u=this.getCurrentContext(o);if(!u){this.resetWhenMissingContext(o);return}const{frag:c,part:d,level:f}=u,{details:m}=f,{audio:g,text:v,id3:b,initSegment:_}=r;if(this.fragContextChanged(c)||!m){this.fragmentTracker.removeFragment(c);return}if(this.state=Pe.PARSING,this.switchingTrack&&g&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const E=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(f,_.tracks,E,o),n.trigger(N.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:_.tracks})}if(g){const{startPTS:E,endPTS:L,startDTS:I,endDTS:w}=g;d&&(d.elementaryStreams[oi.AUDIO]={startPTS:E,endPTS:L,startDTS:I,endDTS:w}),c.setElementaryStreamInfo(oi.AUDIO,E,L,I,w),this.bufferFragmentData(g,c,d,o)}if(b!=null&&(t=b.samples)!=null&&t.length){const E=ni({id:i,frag:c,details:m},b);n.trigger(N.FRAG_PARSING_METADATA,E)}if(v){const E=ni({id:i,frag:c,details:m},v);n.trigger(N.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,i,n){if(this.state!==Pe.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=it.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${o}/${r.codec}]`),o&&o.split(",").length===1&&(r.levelCodec=o),this.hls.trigger(N.BUFFER_CODECS,t);const u=r.initSegment;if(u!=null&&u.byteLength){const c={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:u};this.hls.trigger(N.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===Ji.NOT_LOADED||n===Ji.PARTIAL){var r;if(!Ui(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Pe.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&rm(t.details,o)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u}=this.bufferedTrack;xl({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u},e,dl)||(em(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(N.AUDIO_TRACK_SWITCHED,Qt({},e))}}class gb extends jn{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t?.renditionReports;if(n){let r=-1;for(let o=0;o=0&&f>t.partTarget&&(c+=1)}const d=i&&R1(i);return new O1(u,c>=0?c:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:r}=t,o=self.performance.now(),u=r.loading.first?Math.max(0,o-r.loading.first):0;n.advancedDateTime=Date.now()-u;const c=this.hls.config.timelineOffset;if(c!==n.appliedTimelineOffset){const f=Math.max(c||0,0);n.appliedTimelineOffset=f,n.fragments.forEach(m=>{m.setStart(m.playlistOffset+f)})}if(n.live||i!=null&&i.live){const f="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(i),i&&n.fragments.length>0){JF(i,n,this);const I=n.playlistParsingError;if(I){this.warn(I);const w=this.hls;if(!w.config.ignorePlaylistParsingErrors){var d;const{networkDetails:F}=t;w.trigger(N.ERROR,{type:ot.NETWORK_ERROR,details:ve.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:I,reason:I.message,level:t.level||void 0,parent:(d=n.fragments[0])==null?void 0:d.type,networkDetails:F,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const m=this.hls.mainForwardBufferInfo,g=m?m.end-m.len:0,v=(n.edge-g)*1e3,b=Ww(n,v);if(n.requestScheduled+b0){if(k>n.targetduration*3)this.log(`Playlist last advanced ${q.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,L=void 0;else if(i!=null&&i.tuneInGoal&&k-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${R} with playlist age: ${n.age}`),R=0;else{const K=Math.floor(R/n.targetduration);if(E+=K,L!==void 0){const X=Math.round(R%n.targetduration/n.partTarget);L+=X}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${q.toFixed(2)}s goal: ${R} skip sn ${K} to part ${L}`)}n.tuneInGoal=R}if(_=this.getDeliveryDirectives(n,t.deliveryDirectives,E,L),I||!B){n.requestScheduled=o,this.loadingPlaylist(f,_);return}}else(n.canBlockReload||n.canSkipUntil)&&(_=this.getDeliveryDirectives(n,t.deliveryDirectives,E,L));_&&E!==void 0&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(b-u*2,b/2)),this.scheduleLoading(f,_,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const r=self.performance.now(),o=n.requestScheduled;if(r>=o){this.loadingPlaylist(e,t);return}const u=o-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(u)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),u)}getDeliveryDirectives(e,t,i,n){let r=R1(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=bp.No),new O1(i,n,r)}checkRetry(e){const t=e.details,i=tm(e),n=e.errorAction,{action:r,retryCount:o=0,retryConfig:u}=n||{},c=!!n&&!!u&&(r===ys.RetryRequest||!n.resolved&&r===ys.SendAlternateToPenaltyBox);if(c){var d;if(o>=u.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const f=sb(u,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),f),this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" in ${f}ms`)}e.levelRetry=!0,n.resolved=!0}return c}}function _L(s,e){if(s.length!==e.length)return!1;for(let t=0;ts[n]!==e[n])}function Jv(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class lU extends gb{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.MANIFEST_PARSED,this.onManifestParsed,this),e.on(N.LEVEL_LOADING,this.onLevelLoading,this),e.on(N.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(N.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(N.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.MANIFEST_PARSED,this.onManifestParsed,this),e.off(N.LEVEL_LOADING,this.onLevelLoading,this),e.off(N.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(N.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(N.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${o?.groupId}`);return}const u=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,u)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||n?.length!==i?.length||i!=null&&i.some(u=>n?.indexOf(u)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const u=this.tracks.filter(g=>!i||i.indexOf(g.groupId)!==-1);if(u.length)this.selectDefaultTrack&&!u.some(g=>g.default)&&(this.selectDefaultTrack=!1),u.forEach((g,v)=>{g.id=v});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const c=this.hls.config.audioPreference;if(!r&&c){const g=Rr(c,u,dl);if(g>-1)r=u[g];else{const v=Rr(c,this.tracks);r=this.tracks[v]}}let d=this.findTrackId(r);d===-1&&r&&(d=this.findTrackId(null));const f={audioTracks:u};this.log(`Updating audio tracks, ${u.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(N.AUDIO_TRACKS_UPDATED,f);const m=this.trackId;if(d!==-1&&m===-1)this.setAudioTrack(d);else if(u.length&&m===-1){var o;const g=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${u.length}`);this.warn(g.message),this.hls.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:g})}}}onError(e,t){t.fatal||!t.context||t.context.type===Rt.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&xl(e,n,dl))return n;const r=Rr(e,this.tracksInGroup,dl);if(r>-1){const o=this.tracksInGroup[r];return this.setAudioTrack(r),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const u=bF(e,t.levels,i,o,dl);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const o=Rr(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],r=n.details&&!n.details.live;if(e===this.trackId&&n===i&&r||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(N.AUDIO_TRACK_SWITCHING,Qt({},n)),r))return;const o=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(r){var i;if(n.onError(r),this.queues===null||this.tracks===null)return;const o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"":` -${this.list("video")} -${this.list("audio")} -${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],n=i?.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const v2=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,xL="HlsJsTrackRemovedError";class cU extends Error{constructor(e){super(e),this.name=xL}}class dU extends jn{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:n,mediaSource:r}=this;i&&this.log("Media source opened"),!(!n||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(N.MEDIA_ATTACHED,{media:n,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:n}=this;i!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=OB(Eo(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.MANIFEST_PARSED,this.onManifestParsed,this),e.on(N.BUFFER_RESET,this.onBufferReset,this),e.on(N.BUFFER_APPENDING,this.onBufferAppending,this),e.on(N.BUFFER_CODECS,this.onBufferCodecs,this),e.on(N.BUFFER_EOS,this.onBufferEos,this),e.on(N.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(N.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(N.FRAG_PARSED,this.onFragParsed,this),e.on(N.FRAG_CHANGED,this.onFragChanged,this),e.on(N.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.MANIFEST_PARSED,this.onManifestParsed,this),e.off(N.BUFFER_RESET,this.onBufferReset,this),e.off(N.BUFFER_APPENDING,this.onBufferAppending,this),e.off(N.BUFFER_CODECS,this.onBufferCodecs,this),e.off(N.BUFFER_EOS,this.onBufferEos,this),e.off(N.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(N.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(N.FRAG_PARSED,this.onFragParsed,this),e.off(N.FRAG_CHANGED,this.onFragChanged,this),e.off(N.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const o=this.isQueued();(r||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?ni(i,n.tracks):this.sourceBuffers.forEach(r=>{const[o]=r;o&&(i[o]=ni({},this.tracks[o]),this.removeBuffer(o)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const n=Eo(this.appendSource);if(n){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(o),r)this._objectUrl=i.src,this.attachTransferred();else{const u=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");const c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&o instanceof c,T2(i),hU(i,u),i.load()}catch{i.src=u}else i.src=u}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,n=t.tracks,r=n?Object.keys(n):null,o=r?r.length:0,u=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) -required tracks: ${ui(i,(c,d)=>c==="initSegment"?void 0:d)}; -transfer tracks: ${ui(n,(c,d)=>c==="initSegment"?void 0:d)}}`),!vw(n,i)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,d=this.details,f=Math.max(c,d?.fragments[0].start||0);if(f-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${f}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${f} currentTime: ${c}`),this.onMediaDetaching(N.MEDIA_DETACHING,{}),this.onMediaAttaching(N.MEDIA_ATTACHING,t),e.currentTime=f;return}this.transferData=void 0,r.forEach(c=>{const d=c,f=n[d];if(f){const m=f.buffer;if(m){const g=this.fragmentTracker,v=f.id;if(g.hasFragments(v)||g.hasParts(v)){const E=_t.getBuffered(m);g.detectEvictedFragments(d,E,v,null,!0)}const b=zy(d),_=[d,m];this.sourceBuffers[b]=_,m.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,f)}}}),u(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),u()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:r,_objectUrl:o}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([u])=>{u&&this.removeBuffer(u)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const u=r.readyState==="open";try{const c=r.sourceBuffers;for(let d=c.length;d--;)u&&c[d].abort(),r.removeSourceBuffer(c[d]);u&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&T2(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(N.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[zy(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new uU(this.tracks)}onBufferCodecs(e,t){var i;const n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const o="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),u=!o&&this.sourceBufferCount&&this.media&&r.some(c=>!n[c]);if(o||u){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var d,f;const m=t[c],{id:g,codec:v,levelCodec:b,container:_,metadata:E,supplemental:L}=m;let I=n[c];const w=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],F=w!=null&&w.buffer?w:I,U=F?.pendingCodec||F?.codec,V=F?.levelCodec;I||(I=n[c]={buffer:void 0,listeners:[],codec:v,supplemental:L,container:_,levelCodec:b,metadata:E,id:g});const B=Tp(U,V),q=B?.replace(v2,"$1");let k=Tp(v,b);const R=(f=k)==null?void 0:f.replace(v2,"$1");k&&B&&q!==R&&(c.slice(0,5)==="audio"&&(k=Zp(k,this.appendSource)),this.log(`switching codec ${U} to ${k}`),k!==(I.pendingCodec||I.codec)&&(I.pendingCodec=k),I.container=_,this.appendChangeType(c,_,k))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,r={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const u=o.buffer;u!=null&&u.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),u.changeType(n),o.codec=i,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,it.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var u;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&_t.isBuffered(c.buffer,n)||((u=this.fragmentTracker.getAppendedFrag(n,it.MAIN))==null?void 0:u.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:u=>{this.warn("Error executing block-audio operation",u)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:r,parent:o,frag:u,part:c,chunkMeta:d,offset:f}=t,m=d.buffering[r],{sn:g,cc:v}=u,b=self.performance.now();m.start=b;const _=u.stats.buffering,E=c?c.stats.buffering:null;_.start===0&&(_.start=b),E&&E.start===0&&(E.start=b);const L=i.audio;let I=!1;r==="audio"&&L?.container==="audio/mpeg"&&(I=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const w=i.video,F=w?.buffer;if(F&&g!=="initSegment"){const B=c||u,q=this.blockedAudioAppend;if(r==="audio"&&o!=="main"&&!this.blockedAudioAppend&&!(w.ending||w.ended)){const R=B.start+B.duration*.05,K=F.buffered,X=this.currentOp("video");!K.length&&!X?this.blockAudio(B):!X&&!_t.isBuffered(F,R)&&this.lastVideoAppendEndR||k{var B;m.executeStart=self.performance.now();const q=(B=this.tracks[r])==null?void 0:B.buffer;q&&(I?this.updateTimestampOffset(q,U,.1,r,g,v):f!==void 0&&Qe(f)&&this.updateTimestampOffset(q,f,1e-6,r,g,v)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const B=self.performance.now();m.executeEnd=m.end=B,_.first===0&&(_.first=B),E&&E.first===0&&(E.first=B);const q={};this.sourceBuffers.forEach(([k,R])=>{k&&(q[k]=_t.getBuffered(R))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(N.BUFFER_APPENDED,{type:r,frag:u,part:c,chunkMeta:d,parent:u.type,timeRanges:q})},onError:B=>{var q;const k={type:ot.MEDIA_ERROR,parent:u.type,details:ve.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:u,part:c,chunkMeta:d,error:B,err:B,fatal:!1},R=(q=this.media)==null?void 0:q.error;if(B.code===DOMException.QUOTA_EXCEEDED_ERR||B.name=="QuotaExceededError"||"quota"in B)k.details=ve.BUFFER_FULL_ERROR;else if(B.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!R)k.errorAction=zu(!0);else if(B.name===xL&&this.sourceBufferCount===0)k.errorAction=zu(!0);else{const K=++this.appendErrors[r];this.warn(`Failed ${K}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${R||"no media error"})`),(K>=this.hls.config.appendErrorMaxRetry||R)&&(k.fatal=!0)}this.hls.trigger(N.ERROR,k)}};this.log(`queuing "${r}" append sn: ${g}${c?" p: "+c.index:""} of ${u.type===it.MAIN?"level":"track"} ${u.level} cc: ${v}`),this.append(V,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(N.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:r}=t;i?this.append(this.getFlushOp(i,n,r),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,r),o)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],o=n?n.elementaryStreams:i.elementaryStreams;o[oi.AUDIOVIDEO]?r.push("audiovideo"):(o[oi.AUDIO]&&r.push("audio"),o[oi.VIDEO]&&r.push("video"));const u=()=>{const c=self.performance.now();i.stats.buffering.end=c,n&&(n.stats.buffering.end=c);const d=n?n.stats:i.stats;this.hls.trigger(N.FRAG_BUFFERED,{frag:i,part:n,stats:d,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(u,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){const u=this.tracks[o];(!t.type||t.type===o)&&(u.ending=!0,u.ended||(u.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var u;return o&&!((u=this.tracks[o])!=null&&u.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(N.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(N.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===ve.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;Qe(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,r=i.currentTime,o=t.levelTargetDuration,u=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(Qe(u)&&u>=0){const d=Math.max(u,o),f=Math.floor(r/o)*o-d;this.flushBackBuffer(r,o,f)}const c=n.frontBufferFlushThreshold;if(Qe(c)&&c>0){const d=Math.max(n.maxBufferLength,c),f=Math.max(d,o),m=Math.floor(r/o)*o+f;this.flushFrontBuffer(r,o,m)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const u=_t.getBuffered(r);if(u.length>0&&i>u.start(0)){var o;this.hls.trigger(N.BACK_BUFFER_REACHED,{bufferEnd:i});const c=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(N.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(c!=null&&c.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(N.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const o=_t.getBuffered(r),u=o.length;if(u<2)return;const c=o.start(u-1),d=o.end(u-1);if(i>c||e>=c&&e<=d)return;this.hls.trigger(N.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const d=Math.max(0,t.fragmentStart),f=Math.max(d,n);return{duration:1/0,start:d,end:f}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return Qe(r)?{duration:r}:null;const o=this.media.duration,u=Qe(i.duration)?i.duration:0;return n>u&&n>o||!Qe(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(Qe(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${i}.`),n.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ui(i)}`),this.tracksReady){var n;const r=(n=this.transferData)==null?void 0:n.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const n=this.tracks[t];e[t]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(N.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const o=r,u=e[o];if(this.isPending(u)){const c=this.getTrackCodec(u,o),d=`${u.container};codecs=${c}`;u.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(o)?" Queued":""} ${ui(u)}`);try{const f=i.addSourceBuffer(d),m=zy(o),g=[o,f];t[m]=g,u.buffer=f}catch(f){var n;this.error(`error while trying to add sourceBuffer: ${f.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:f,sourceBufferName:o,mimeType:d,parent:u.id});return}this.trackSourceBuffer(o,u)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Xd(i,"video")&&(n=tF(n,i));const r=Tp(n,e.levelCodec);return r?t.slice(0,5)==="audio"?Zp(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,o)=>{const u=o.removedRanges;u!=null&&u.length&&this.hls.trigger(N.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${n}`,t),this.hls.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,o){const u=t-e.timestampOffset;Math.abs(u)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${o})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,o=this.tracks[e],u=o?.buffer;if(!n||!r||!u){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=Qe(n.duration)?n.duration:1/0,d=Qe(r.duration)?r.duration:1/0,f=Math.max(0,t),m=Math.min(i,c,d);m>f&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${f},${m}] from the ${e} SourceBuffer`),u.remove(f,m)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i?.buffer;if(!n)throw new cU(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const r=n.buffer;if(!r)return;const o=i.bind(this,e);n.listeners.push({event:t,listener:o}),r.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function T2(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function hU(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function zy(s){return s==="audio"?1:0}class yb{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(N.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(N.MANIFEST_PARSED,this.onManifestParsed,this),e.on(N.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(N.BUFFER_CODECS,this.onBufferCodecs,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(N.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(N.MANIFEST_PARSED,this.onManifestParsed,this),e.off(N.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(N.BUFFER_CODECS,this.onBufferCodecs,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Qe(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,r)=>this.isLevelAllowed(n)&&r<=e);return this.clientRect=null,yb.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(u,c)=>c?u.width!==c.width||u.height!==c.height:!0;let r=e.length-1;const o=Math.max(t,i);for(let u=0;u=o||c.height>=o)&&n(c,e[u+1])){r=u;break}}return r}}const fU={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Qs=fU,pU={HLS:"h"},mU=pU;class Fr{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Fr?i:new Fr(i))),this.value=e,this.params=t}}const gU="Dict";function yU(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function vU(s,e,t,i){return new Error(`failed to ${s} "${yU(e)}" as ${t}`,{cause:i})}function Ur(s,e,t){return vU("serialize",s,e,t)}class SL{constructor(e){this.description=e}}const b2="Bare Item",TU="Boolean";function bU(s){if(typeof s!="boolean")throw Ur(s,TU);return s?"?1":"?0"}function _U(s){return btoa(String.fromCharCode(...s))}const xU="Byte Sequence";function SU(s){if(ArrayBuffer.isView(s)===!1)throw Ur(s,xU);return`:${_U(s)}:`}const EU="Integer";function AU(s){return s<-999999999999999||99999999999999912)throw Ur(s,DU);const t=e.toString();return t.includes(".")?t:`${t}.0`}const LU="String",IU=/[\x00-\x1f\x7f]+/;function kU(s){if(IU.test(s))throw Ur(s,LU);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function RU(s){return s.description||s.toString().slice(7,-1)}const OU="Token";function _2(s){const e=RU(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ur(e,OU);return e}function eT(s){switch(typeof s){case"number":if(!Qe(s))throw Ur(s,b2);return Number.isInteger(s)?EL(s):wU(s);case"string":return kU(s);case"symbol":return _2(s);case"boolean":return bU(s);case"object":if(s instanceof Date)return CU(s);if(s instanceof Uint8Array)return SU(s);if(s instanceof SL)return _2(s);default:throw Ur(s,b2)}}const PU="Key";function tT(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Ur(s,PU);return s}function vb(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${tT(e)}`:`;${tT(e)}=${eT(t)}`).join("")}function CL(s){return s instanceof Fr?`${eT(s.value)}${vb(s.params)}`:eT(s)}function MU(s){return`(${s.value.map(CL).join(" ")})${vb(s.params)}`}function NU(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw Ur(s,gU);const t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Fr||(r=new Fr(r));let o=tT(n);return r.value===!0?o+=vb(r.params):(o+="=",Array.isArray(r.value)?o+=MU(r):o+=CL(r)),o}).join(`,${i}`)}function DL(s,e){return NU(s,e)}const xr="CMCD-Object",Ii="CMCD-Request",ol="CMCD-Session",ho="CMCD-Status",BU={br:xr,ab:xr,d:xr,ot:xr,tb:xr,tpb:xr,lb:xr,tab:xr,lab:xr,url:xr,pb:Ii,bl:Ii,tbl:Ii,dl:Ii,ltc:Ii,mtp:Ii,nor:Ii,nrr:Ii,rc:Ii,sn:Ii,sta:Ii,su:Ii,ttfb:Ii,ttfbb:Ii,ttlb:Ii,cmsdd:Ii,cmsds:Ii,smrt:Ii,df:Ii,cs:Ii,ts:Ii,cid:ol,pr:ol,sf:ol,sid:ol,st:ol,v:ol,msd:ol,bs:ho,bsd:ho,cdn:ho,rtp:ho,bg:ho,pt:ho,ec:ho,e:ho},FU={REQUEST:Ii};function UU(s){return Object.keys(s).reduce((e,t)=>{var i;return(i=s[t])===null||i===void 0||i.forEach(n=>e[n]=t),e},{})}function $U(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?UU(e):{};return i.reduce((r,o)=>{var u;const c=BU[o]||n[o]||FU.REQUEST,d=(u=r[c])!==null&&u!==void 0?u:r[c]={};return d[o]=s[o],r},t)}function jU(s){return["ot","sf","st","e","sta"].includes(s)}function HU(s){return typeof s=="number"?Qe(s):s!=null&&s!==""&&s!==!1}const wL="event";function GU(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const n=t.pathname.split("/").slice(1),r=i.pathname.split("/").slice(1,-1);for(;n[0]===r[0];)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.join("/")+t.search+t.hash}const Ep=s=>Math.round(s),iT=(s,e)=>Array.isArray(s)?s.map(t=>iT(t,e)):s instanceof Fr&&typeof s.value=="string"?new Fr(iT(s.value,e),s.params):(e.baseUrl&&(s=GU(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),np=s=>Ep(s/100)*100,VU=(s,e)=>{let t=s;return e.version>=2&&(s instanceof Fr&&typeof s.value=="string"?t=new Fr([s]):typeof s=="string"&&(t=[s])),iT(t,e)},qU={br:Ep,d:Ep,bl:np,dl:np,mtp:np,nor:VU,rtp:np,tb:Ep},LL="request",IL="response",Tb=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],zU=["e"],KU=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Gm(s){return KU.test(s)}function YU(s){return Tb.includes(s)||zU.includes(s)||Gm(s)}const kL=["d","dl","nor","ot","rtp","su"];function WU(s){return Tb.includes(s)||kL.includes(s)||Gm(s)}const XU=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function QU(s){return Tb.includes(s)||kL.includes(s)||XU.includes(s)||Gm(s)}const ZU=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function JU(s){return ZU.includes(s)||Gm(s)}const e6={[IL]:QU,[wL]:YU,[LL]:WU};function RL(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||LL,r=i===1?JU:e6[n];let o=Object.keys(s).filter(r);const u=e.filter;typeof u=="function"&&(o=o.filter(u));const c=n===IL||n===wL;c&&!o.includes("ts")&&o.push("ts"),i>1&&!o.includes("v")&&o.push("v");const d=ni({},qU,e.formatters),f={version:i,reportingMode:n,baseUrl:e.baseUrl};return o.sort().forEach(m=>{let g=s[m];const v=d[m];if(typeof v=="function"&&(g=v(g,f)),m==="v"){if(i===1)return;g=i}m=="pr"&&g===1||(c&&m==="ts"&&!Qe(g)&&(g=Date.now()),HU(g)&&(jU(m)&&typeof g=="string"&&(g=new SL(g)),t[m]=g))}),t}function t6(s,e={}){const t={};if(!s)return t;const i=RL(s,e),n=$U(i,e?.customHeaderMap);return Object.entries(n).reduce((r,[o,u])=>{const c=DL(u,{whitespace:!1});return c&&(r[o]=c),r},t)}function i6(s,e,t){return ni(s,t6(e,t))}const s6="CMCD";function n6(s,e={}){return s?DL(RL(s,e),{whitespace:!1}):""}function r6(s,e={}){if(!s)return"";const t=n6(s,e);return encodeURIComponent(t)}function a6(s,e={}){if(!s)return"";const t=r6(s,e);return`${s6}=${t}`}const x2=/CMCD=[^&#]+/;function o6(s,e,t){const i=a6(e,t);if(!i)return s;if(x2.test(s))return s.replace(x2,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class l6{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=n=>{try{this.apply(n,{ot:Qs.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=n=>{try{const{frag:r,part:o}=n,u=this.hls.levels[r.level],c=this.getObjectType(r),d={d:(o||r).duration*1e3,ot:c};(c===Qs.VIDEO||c===Qs.AUDIO||c==Qs.MUXED)&&(d.br=u.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const f=o?this.getNextPart(o):this.getNextFrag(r);f!=null&&f.url&&f.url!==r.url&&(d.nor=f.url),this.apply(n,d)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(N.MEDIA_DETACHED,this.onMediaDetached,this),e.on(N.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(N.MEDIA_DETACHED,this.onMediaDetached,this),e.off(N.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:mU.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ni(t,this.createData());const i=t.ot===Qs.INIT||t.ot===Qs.VIDEO||t.ot===Qs.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((o,u)=>(n.includes(u)&&(o[u]=t[u]),o),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),i6(e.headers,t,r)):e.url=o6(e.url,t,r)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t;const{index:i,fragment:n}=e,r=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:o}=n;for(let u=r.length-1;u>=0;u--){const c=r[u];if(c.index===i&&c.fragment.sn===o)return r[u+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Qs.TIMED_TEXT;if(e.sn==="initSegment")return Qs.INIT;if(t==="audio")return Qs.AUDIO;if(t==="main")return this.hls.audioTracks.length?Qs.VIDEO:Qs.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Qs.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,o=r>-1?r+1:n.levels.length;i=n.levels.slice(0,o)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Qs.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:_t.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,u){t(r),this.loader.load(r,o,u)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,u){t(r),this.loader.load(r,o,u)}}}}const u6=3e5;class c6 extends jn{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(N.MANIFEST_PARSED,this.onManifestParsed,this),e.on(N.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(N.MANIFEST_PARSED,this.onManifestParsed,this),e.off(N.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if(i?.action===ys.SendAlternateToPenaltyBox&&i.flags===bn.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:u,pathwayId:c,type:d}=t.context;u&&n?o=this.getPathwayForGroupId(u,d,o):c&&(o=c)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==o),t.details===ve.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${ui(r)} penalized: ${ui(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(r=>{n-i[r]>u6&&delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Zw(t),this.hls.trigger(N.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[u];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=u);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r{const{ID:o,"BASE-ID":u,"URI-REPLACEMENT":c}=r;if(t.some(f=>f.pathwayId===o))return;const d=this.getLevelsForPathway(u).map(f=>{const m=new _i(f.attrs);m["PATHWAY-ID"]=o;const g=m.AUDIO&&`${m.AUDIO}_clone_${o}`,v=m.SUBTITLES&&`${m.SUBTITLES}_clone_${o}`;g&&(i[m.AUDIO]=g,m.AUDIO=g),v&&(n[m.SUBTITLES]=v,m.SUBTITLES=v);const b=OL(f.uri,m["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new Zd({attrs:m,audioCodec:f.audioCodec,bitrate:f.bitrate,height:f.height,name:f.name,url:b,videoCodec:f.videoCodec,width:f.width});if(f.audioGroups)for(let E=1;E{this.log(`Loaded steering manifest: "${n}"`);const b=f.data;if(b?.VERSION!==1){this.log(`Steering VERSION ${b.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=b.TTL;const{"RELOAD-URI":_,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":L}=b;if(_)try{this.uri=new self.URL(_,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${_}`);return}this.scheduleRefresh(this.uri||g.url),E&&this.clonePathways(E);const I={steeringManifest:b,url:n.toString()};this.hls.trigger(N.STEERING_MANIFEST_LOADED,I),L&&this.updatePathwayPriority(L)},onError:(f,m,g,v)=>{if(this.log(`Error loading steering manifest: ${f.code} ${f.text} (${m.url})`),this.stopLoad(),f.code===410){this.enabled=!1,this.log(`Steering manifest ${m.url} no longer available`);return}let b=this.timeToLoad*1e3;if(f.code===429){const _=this.loader;if(typeof _?.getResponseHeader=="function"){const E=_.getResponseHeader("Retry-After");E&&(b=parseFloat(E)*1e3)}this.log(`Steering manifest ${m.url} rate limited`);return}this.scheduleRefresh(this.uri||m.url,b)},onTimeout:(f,m,g)=>{this.log(`Timeout loading steering manifest (${m.url})`),this.scheduleRefresh(this.uri||m.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,c,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const n=(i=this.hls)==null?void 0:i.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function S2(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(o=>o.groupId===n).map(o=>{const u=ni({},o);return u.details=void 0,u.attrs=new _i(u.attrs),u.url=u.attrs.URI=OL(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),u.groupId=u.attrs["GROUP-ID"]=e[n],u.attrs["PATHWAY-ID"]=i,u});s.push(...r)})}function OL(s,e,t,i){const{HOST:n,PARAMS:r,[t]:o}=i;let u;e&&(u=o?.[e],u&&(s=u));const c=new self.URL(s);return n&&!u&&(c.host=n),r&&Object.keys(r).sort().forEach(d=>{d&&c.searchParams.set(d,r[d])}),c.href}class Yu extends jn{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Yu.CDMCleanupPromise?[Yu.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,r=`"${t.type}" event: init data type: "${i}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=kd(this.config));const u=o.map(Fy).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(o=>{const u=_p(o);if(i!=="sinf"||u!==xi.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}let c;try{const v=Zi(new Uint8Array(n)),b=ob(JSON.parse(v).sinf),_=Dw(b);if(!_)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(_.subarray(8,24))}catch(v){this.warn(`${r} Failed to parse sinf: ${v}`);return}const d=Ts(c),{keyIdToKeySessionPromise:f,mediaKeySessions:m}=this;let g=f[d];for(let v=0;vthis.generateRequestWithPreferredKeySession(b,i,n,"encrypted-event-key-match")),g.catch(L=>this.handleError(L));break}}g||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${m.length}.`))}).catch(o=>this.handleError(o))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(N.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(N.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(N.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(N.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(N.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(N.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(N.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(N.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(N.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(N.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t?.[e];if(n)return n.licenseUrl;if(e===xi.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t?.[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(o,u,c)=>!!o&&c.indexOf(o)===u,n=t.map(o=>o.audioCodec).filter(i),r=t.map(o=>o.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((o,u)=>{const c=d=>{const f=d.shift();this.getMediaKeysPromise(f,n,r).then(m=>o({keySystem:f,mediaKeys:m})).catch(m=>{d.length?c(d):m instanceof vn?u(m):u(new vn({type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_ACCESS,error:m,fatal:!0},m.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Vw===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){var n;const r=VF(e,t,i,this.config.drmSystemOptions||{});let o=this.keySystemAccessPromises[e],u=(n=o)==null?void 0:n.keySystemAccess;if(!u){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ui(r)}`),u=this.requestMediaKeySystemAccess(e,r);const c=o=this.keySystemAccessPromises[e]={keySystemAccess:u};return u.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),u.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const f=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const m=c.mediaKeys=d.createMediaKeys().then(g=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,f.then(v=>v?this.setMediaKeysServerCertificate(g,e,v):g)));return m.catch(g=>{this.error(`Failed to create media-keys for "${e}"}: ${g}`)}),m})}return u.then(()=>o.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Ts(e.keyId||[])} keyUri: ${e.uri}`);const n=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=rp(t),r="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Ts(e.decryptdata.keyId||[])} - } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Fy(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:n})=>{const r=Fy(n);r?t(r):i(new Error(`Unable to find format for key-system "${n}"`))}).catch(i)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=kd(this.config),i=e.map(_p).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:t}))))).then(c=>{const d="cenc",f=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,f,"playlist-key")});return u.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[i]=u,u}return o.catch(u=>{if(u instanceof vn){const c=Qt({},u.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const d=new vn(c,u.message);this.handleError(d,e.frag)}}),o}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof vn){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${Ts(i.keyId||[])})`:""}`),this.hls.trigger(N.ERROR,e.data)}else this.error(e.message),this.hls.trigger(N.ERROR,{type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=rp(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=_p(e.keyFormat),r=n?[n]:kd(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=kd(this.config)),e.length===0)throw new vn({type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ui({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,o)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return o(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(o)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var r;const o=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(o)try{const b=o.call(this.hls,t,i,e);if(!b)throw new Error("Invalid response from configured generateRequest filter");t=b.initDataType,i=b.initData?b.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(b){if(this.warn(b.message),this.hls&&this.hls.config.debug)throw b}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const u=rp(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${u} URI: ${c} (init data type: ${t} length: ${i.byteLength})`);const d=new ub,f=e._onmessage=b=>{const _=e.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:E,message:L}=b;this.log(`"${E}" message event for session "${_.sessionId}" message size: ${L.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,L).catch(I=>{d.eventNames().length?d.emit("error",I):this.handleError(I)}):E==="license-release"?e.keySystem===xi.FAIRPLAY&&this.updateKeySession(e,Yv("acknowledged")).then(()=>this.removeSession(e)).catch(I=>this.handleError(I)):this.warn(`unhandled media key message type "${E}"`)},m=(b,_)=>{_.keyStatus=b;let E;b.startsWith("usable")?d.emit("resolved"):b==="internal-error"||b==="output-restricted"||b==="output-downscaled"?E=E2(b,_.decryptdata):b==="expired"?E=new Error(`key expired (keyId: ${u})`):b==="released"?E=new Error("key released"):b==="status-pending"||this.warn(`unhandled key status change "${b}" (keyId: ${u})`),E&&(d.eventNames().length?d.emit("error",E):this.handleError(E))},g=e._onkeystatuseschange=b=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const E=this.getKeyStatuses(e);if(!Object.keys(E).some(F=>E[F]!=="status-pending"))return;if(E[u]==="expired"){this.log(`Expired key ${ui(E)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let I=E[u];if(I)m(I,e);else{var w;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(w=e.keyStatusTimeouts)[u]||(w[u]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const U=this.getKeyStatus(e.decryptdata);if(U&&U!=="status-pending")return this.log(`No status for keyId ${u} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${U} from other session.`),m(U,e);this.log(`key status for ${u} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),I="internal-error",m(I,e)},1e3)),this.log(`No status for keyId ${u} (${ui(E)}).`)}};Fs(e.mediaKeysSession,"message",f),Fs(e.mediaKeysSession,"keystatuseschange",g);const v=new Promise((b,_)=>{d.on("error",_),d.on("resolved",b)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${u} URI: ${c}`)}).catch(b=>{throw new vn({type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_SESSION,error:b,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${b}`)}).then(()=>v).catch(b=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw b}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((i,n)=>{if(typeof n=="string"&&typeof i=="object"){const u=n;n=i,i=u}const r="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===xi.PLAYREADY&&r.length===16){const u=Ts(r);t[u]=i,Hw(r)}const o=Ts(r);i==="internal-error"&&(this.bannedKeyIds[o]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${e.mediaKeysSession.sessionId}"`),t[o]=i}),t}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,u)=>{const c={responseType:"arraybuffer",url:r},d=t.certLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(g,v,b,_)=>{o(g.data)},onError:(g,v,b,_)=>{u(new vn({type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:Qt({url:c.url,data:void 0},g)},`"${e}" certificate request failed (${r}). Status: ${g.code} (${g.text})`))},onTimeout:(g,v,b)=>{u(new vn({type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(g,v,b)=>{u(new Error("aborted"))}};n.load(c,f,m)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),n(e)}).catch(o=>{r(new vn({type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new vn({type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(i,"application/xml"),r=n.querySelectorAll("HttpHeader");if(r.length>0){let f;for(let m=0,g=r.length;m in key message");return Yv(atob(d))}setupLicenseXHR(e,t,i,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,n)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((n,r)=>{const o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);const u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(u.readyState===4)if(u.status===200){this._requestLicenseFailureCount=0;let c=u.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,u,o,e)}catch(f){this.error(f)}n(c)}else{const c=i.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||u.status>=400&&u.status<500)r(new vn({type:ot.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:u,response:{url:o,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${o}). Status: ${u.status} (${u.statusText})`));else{const f=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${f} attempts left`),this.requestLicense(e,t).then(n,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=u,this.setupLicenseXHR(u,o,e,t).then(({xhr:c,licenseChallenge:d})=>{e.keySystem==xi.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,Fs(i,"encrypted",this.onMediaEncrypted),Fs(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(sn(e,"encrypted",this.onMediaEncrypted),sn(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,_o.clearKeyUriToKeyIdMap();const r=n.length;Yu.CDMCleanupPromise=Promise.all(n.map(o=>this.removeSession(o)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(o=>{this.log(`Could not clear media keys: ${o}`),this.hls&&this.hls.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${o}`)})}))||Promise.resolve())).catch(o=>{this.log(`Could not close sessions and clear media keys: ${o}`),this.hls&&this.hls.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${o}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,r)=>(n.indexOf(r.keyFormat)===-1&&n.push(r.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Ts(n?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:o}=e;o&&Object.keys(o).forEach(d=>self.clearTimeout(o[d]));const{drmSystemOptions:u}=this.config;return(zF(u)?new Promise((d,f)=>{self.setTimeout(()=>f(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(f)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}Yu.CDMCleanupPromise=void 0;function rp(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Ts(s.keyId)}function d6(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}class vn extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function E2(s,e){const t=s==="output-restricted",i=t?ve.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ve.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new vn({type:ot.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class h6{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(N.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(N.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(N.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(N.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const r=n-this.lastTime,o=i-this.lastDroppedFrames,u=t-this.lastDecodedFrames,c=1e3*o/r,d=this.hls;if(d.trigger(N.FPS_DROP,{currentDropped:o,currentDecoded:u,totalDroppedFrames:i}),c>0&&o>d.config.fpsDroppedMonitoringThreshold*u){let f=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+f),f>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=f)&&(f=f-1,d.trigger(N.FPS_DROP_LEVEL_CAPPING,{level:f,droppedLevel:d.currentLevel}),d.autoLevelCapping=f,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function PL(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function ML(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Zt.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,s.addCue(n)}catch(n){Zt.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function Mu(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t)}function sT(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=p6(s.cues,e,t);for(let o=0;os[t].endTime)return-1;let i=0,n=t,r;for(;i<=n;)if(r=Math.floor((n+i)/2),es[r].startTime&&i-1)for(let r=n,o=s.length;r=e&&u.endTime<=t)i.push(u);else if(u.startTime>t)return i}return i}function Ap(s){const e=[];for(let t=0;tthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Ap(this.media.textTracks);for(let r=0;r-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.MANIFEST_PARSED,this.onManifestParsed,this),e.on(N.LEVEL_LOADING,this.onLevelLoading,this),e.on(N.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(N.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(N.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.MANIFEST_PARSED,this.onManifestParsed,this),e.off(N.LEVEL_LOADING,this.onLevelLoading,this),e.off(N.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(N.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(N.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;Ap(i.textTracks).forEach(o=>{Mu(o)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${o?.groupId}`);return}const u=o.details;o.details=t.details,this.log(`Subtitle track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,u)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||n?.length!==i?.length||i!=null&&i.some(o=>n?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(f=>!i||i.indexOf(f.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(f=>f.default)&&(this.selectDefaultTrack=!1),o.forEach((f,m)=>{f.id=m});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const f=Rr(u,o);if(f>-1)r=o[f];else{const m=Rr(u,this.tracks);r=this.tracks[m]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const d={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(N.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n-1){const r=this.tracksInGroup[n];return this.setSubtitleTrack(n),r}else{if(i)return null;{const r=Rr(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,r=this.getUrlWithDirectives(e.url,t),o=e.details,u=o?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${u&&o.live?" age "+u.toFixed(1)+(o.type&&" "+o.type||""):""} ${r}`),this.hls.trigger(N.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Ap(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>Jv(i,r))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==n&&(r.mode="disabled")}),n){const r=this.subtitleDisplay?"showing":"hidden";n.mode!==r&&(n.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!Qe(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(N.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!n.details&&!n.details.live;if(e===this.trackId&&n===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:u="",name:c,type:d,url:f}=n;this.hls.trigger(N.SUBTITLE_TRACK_SWITCH,{id:o,groupId:u,name:c,type:d,url:f});const m=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(m)}}function g6(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?r:r&3|8).toString(16)})}}}function Vd(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const Wu=.025;let om=(function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s})({});function y6(s,e,t){return`${s.identifier}-${t+1}-${Vd(e)}`}class v6{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Ky(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=Ky(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=Qe(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Ky(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return T6(this)}}function Ky(s,e){return s-e.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function ku(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class b6{constructor(e,t,i,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(N.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const o=()=>{this.hasDetails=!0};r.once(N.LEVEL_LOADED,o),r.once(N.AUDIO_TRACK_LOADED,o),r.once(N.SUBTITLE_TRACK_LOADED,o),r.on(N.MEDIA_ATTACHING,(u,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(N.BUFFER_APPENDED,()=>{const f=this.bufferedEnd;this.reachedPlayout(f)&&(this._bufferedEosTime=f,r.trigger(N.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=NL(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,r=_t.bufferInfo(e,n,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=_t.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,i){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,i){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ku(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const A2=.033;class _6 extends jn{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=n[i])!=null&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let n=0;nr.start&&e1)for(let r=0;ru&&(t!u.includes(d.identifier)):[];o.length&&o.sort((d,f)=>{const m=d.cue.pre,g=d.cue.post,v=f.cue.pre,b=f.cue.post;if(m&&!v)return-1;if(v&&!m||g&&!b)return 1;if(b&&!g)return-1;if(!m&&!v&&!g&&!b){const _=d.startTime,E=f.startTime;if(_!==E)return _-E}return d.dateRange.tagOrder-f.dateRange.tagOrder}),this.events=o,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],i=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const r=this.items,o=this.parseSchedule(n,e);(i||t.length||r?.length!==o.length||o.some((c,d)=>Math.abs(c.playout.start-r[d].playout.start)>.005||Math.abs(c.playout.end-r[d].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let o=0;o!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,d=0;if(e.forEach((f,m)=>{const g=f.cue.pre,v=f.cue.post,b=e[m-1]||null,_=f.appendInPlace,E=v?r:f.startOffset,L=f.duration,I=f.timelineOccupancy===om.Range?L:0,w=f.resumptionOffset,F=b?.startTime===E,U=E+f.cumulativeDuration;let V=_?U+L:E+w;if(g||!v&&E<=0){const q=d;d+=I,f.timelineStart=U;const k=o;o+=L,i.push({event:f,start:U,end:V,playout:{start:k,end:o},integrated:{start:q,end:d}})}else if(E<=r){if(!F){const R=E-c;if(R>A2){const K=c,X=d;d+=R;const ee=o;o+=R;const le={previousEvent:e[m-1]||null,nextEvent:f,start:K,end:K+R,playout:{start:ee,end:o},integrated:{start:X,end:d}};i.push(le)}else R>0&&b&&(b.cumulativeDuration+=R,i[i.length-1].end=E)}v&&(V=U),f.timelineStart=U;const q=d;d+=I;const k=o;o+=L,i.push({event:f,start:U,end:V,playout:{start:k,end:o},integrated:{start:q,end:d}})}else return;const B=f.resumeTime;v||B>r?c=r:c=B}),c{const d=u.cue.pre,f=u.cue.post,m=d?0:f?n:u.startTime;this.updateAssetDurations(u),o===m?u.cumulativeDuration=r:(r=0,o=m),!f&&u.snapOptions.in&&(u.resumeAnchor=Cl(null,i.fragments,u.startOffset+u.resumptionOffset,0,0)||void 0),u.appendInPlace&&!u.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(u,t)||(u.appendInPlace=!1)),!u.appendInPlace&&c+1Wu?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(o=>{const u=t[o].details,c=u.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${o} playlist end ${c}`),!1;const d=Cl(null,u.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${o} playlist (${u.fragStart}-${u.fragmentEnd})`),!0;const f=o==="audio"?.175:0;return Math.abs(d.start-i){const E=g.data,L=E?.ASSETS;if(!Array.isArray(L)){const I=this.assignAssetListError(e,ve.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),b.url,v,_);this.hls.trigger(N.ERROR,I);return}e.assetListResponse=E,this.hls.trigger(N.ASSET_LIST_LOADED,{event:e,assetListResponse:E,networkDetails:_})},onError:(g,v,b,_)=>{const E=this.assignAssetListError(e,ve.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${g.code} ${g.text} (${v.url})`),v.url,_,b);this.hls.trigger(N.ERROR,E)},onTimeout:(g,v,b)=>{const _=this.assignAssetListError(e,ve.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${v.url})`),v.url,g,b);this.hls.trigger(N.ERROR,_)}};return u.load(c,f,m),this.hls.trigger(N.ASSET_LIST_LOADING,{event:e}),u}assignAssetListError(e,t,i,n,r,o){return e.error=i,{type:ot.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:o,stats:r}}}function C2(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function ap(s,e){return`[${s}] Advancing timeline position to ${e}`}class S6 extends jn{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const n=i-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const u=this.playingItem;if(!u){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),o&&i=u.end){var c;const v=this.findItemIndex(u);let b=this.schedule.findItemIndexAtTime(i);if(b===-1&&(b=v+(o?-1:1),this.log(`seeked ${o?"back ":""}to position not covered by schedule ${i} (resolving from ${v} to ${b})`)),!this.isInterstitial(u)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!o&&b>v){const _=this.schedule.findJumpRestrictedIndex(v+1,b);if(_>v){this.setSchedulePosition(_);return}}this.setSchedulePosition(b);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(u)){const v=u.event.assetList[0];v&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,v))}return}const f=d.timelineStart,m=d.duration||0;if(o&&i=f+m){var g;(g=u.event)!=null&&g.appendInPlace&&(this.clearAssetPlayers(u.event,u),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(i>=n.end){this.timelinePos=n.end;const u=this.findItemIndex(n);this.setSchedulePosition(u+1)}const r=this.playingAsset;if(!r)return;const o=r.timelineStart+(r.duration||0);i>=o&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const o=this.playingItem,u=r.events||[],c=r.items||[],d=r.durations,f=i.map(_=>_.identifier),m=!!(u.length||f.length);(m||n)&&this.log(`INTERSTITIALS_UPDATED (${u.length}): ${u} -Schedule: ${c.map(_=>Qn(_))} pos: ${this.timelinePos}`),f.length&&this.log(`Removed events ${f}`);let g=null,v=null;o&&(g=this.updateItem(o,this.timelinePos),this.itemsMatch(o,g)?this.playingItem=g:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const b=this.bufferingItem;if(b&&(v=this.updateItem(b,this.bufferedPos),this.itemsMatch(b,v)?this.bufferingItem=v:b.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(b.event,null))),i.forEach(_=>{_.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const E=_.assetItem.timelineStart,L=_.timelineOffset-E;if(L)try{_.timelineOffset=E}catch(I){Math.abs(L)>Wu&&this.warn(`${I} ("${_.assetId}" ${_.timelineOffset}->${E})`)}}}),m||n){if(this.hls.trigger(N.INTERSTITIALS_UPDATED,{events:u.slice(0),schedule:c.slice(0),durations:d,removedIds:f}),this.isInterstitial(o)&&f.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}o&&this.trimInPlace(g,o),b&&v!==g&&this.trimInPlace(v,b),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new x6(e),this.schedule=new _6(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(N.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(N.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(N.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(N.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(N.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(N.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(N.BUFFER_APPENDED,this.onBufferAppended,this),e.on(N.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(N.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(N.MEDIA_ENDED,this.onMediaEnded,this),e.on(N.ERROR,this.onError,this),e.on(N.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(N.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(N.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(N.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(N.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(N.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(N.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(N.BUFFER_CODECS,this.onBufferCodecs,this),e.off(N.BUFFER_APPENDED,this.onBufferAppended,this),e.off(N.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(N.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(N.MEDIA_ENDED,this.onMediaEnded,this),e.off(N.ERROR,this.onError,this),e.off(N.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){sn(e,"play",this.onPlay),sn(e,"pause",this.onPause),sn(e,"seeking",this.onSeeking),sn(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Fs(i,"seeking",this.onSeeking),Fs(i,"timeupdate",this.onTimeupdate),Fs(i,"play",this.onPlay),Fs(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!n){this.clearScheduleState();const r=this.findItemIndex(i);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=m=>m&&e.getAssetPlayer(m.identifier),n=(m,g,v,b,_)=>{if(m){let E=m[g].start;const L=m.event;if(L){if(g==="playout"||L.timelineOccupancy!==om.Point){const I=i(v);I?.interstitial===L&&(E+=I.assetItem.startOffset+I[_])}}else{const I=b==="bufferedPos"?o():e[b];E+=I-m.start}return E}return 0},r=(m,g)=>{var v;if(m!==0&&g!=="primary"&&(v=e.schedule)!=null&&v.length){var b;const _=e.schedule.findItemIndexAtTime(m),E=(b=e.schedule.items)==null?void 0:b[_];if(E){const L=E[g].start-E.start;return m+L}}return m},o=()=>{const m=e.bufferedPos;return m===Number.MAX_VALUE?u("primary"):Math.max(m,0)},u=m=>{var g,v;return(g=e.primaryDetails)!=null&&g.live?e.primaryDetails.edge:((v=e.schedule)==null?void 0:v.durations[m])||0},c=(m,g)=>{var v,b;const _=e.effectivePlayingItem;if(_!=null&&(v=_.event)!=null&&v.restrictions.skip||!e.schedule)return;e.log(`seek to ${m} "${g}"`);const E=e.effectivePlayingItem,L=e.schedule.findItemIndexAtTime(m,g),I=(b=e.schedule.items)==null?void 0:b[L],w=e.getBufferingPlayer(),F=w?.interstitial,U=F?.appendInPlace,V=E&&e.itemsMatch(E,I);if(E&&(U||V)){const B=i(e.playingAsset),q=B?.media||e.primaryMedia;if(q){const k=g==="primary"?q.currentTime:n(E,g,e.playingAsset,"timelinePos","currentTime"),R=m-k,K=(U?k:q.currentTime)+R;if(K>=0&&(!B||U||K<=B.duration)){q.currentTime=K;return}}}if(I){let B=m;if(g!=="primary"){const k=I[g].start,R=m-k;B=I.start+R}const q=!e.isInterstitial(I);if((!e.isInterstitial(E)||E.event.appendInPlace)&&(q||I.event.appendInPlace)){const k=e.media||(U?w?.media:null);k&&(k.currentTime=B)}else if(E){const k=e.findItemIndex(E);if(L>k){const K=e.schedule.findJumpRestrictedIndex(k+1,L);if(K>k){e.setSchedulePosition(K);return}}let R=0;if(q)e.timelinePos=B,e.checkBuffer();else{const K=I.event.assetList,X=m-(I[g]||I).start;for(let ee=K.length;ee--;){const le=K[ee];if(le.duration&&X>=le.startOffset&&X{const m=e.effectivePlayingItem;if(e.isInterstitial(m))return m;const g=t();return e.isInterstitial(g)?g:null},f={get bufferedEnd(){const m=t(),g=e.bufferingItem;if(g&&g===m){var v;return n(g,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-g.playout.start||((v=e.bufferingAsset)==null?void 0:v.startOffset)||0}return 0},get currentTime(){const m=d(),g=e.effectivePlayingItem;return g&&g===m?n(g,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-g.playout.start:0},set currentTime(m){const g=d(),v=e.effectivePlayingItem;v&&v===g&&c(m+v.playout.start,"playout")},get duration(){const m=d();return m?m.playout.end-m.playout.start:0},get assetPlayers(){var m;const g=(m=d())==null?void 0:m.event.assetList;return g?g.map(v=>e.getAssetPlayer(v.identifier)):[]},get playingIndex(){var m;const g=(m=d())==null?void 0:m.event;return g&&e.effectivePlayingAsset?g.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var m;return((m=e.schedule)==null||(m=m.events)==null?void 0:m.slice(0))||[]},get schedule(){var m;return((m=e.schedule)==null||(m=m.items)==null?void 0:m.slice(0))||[]},get interstitialPlayer(){return d()?f:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const m=t();return e.findItemIndex(m)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const m=e.effectivePlayingItem;return e.findItemIndex(m)},primary:{get bufferedEnd(){return o()},get currentTime(){const m=e.timelinePos;return m>0?m:0},set currentTime(m){c(m,"primary")},get duration(){return u("primary")},get seekableStart(){var m;return((m=e.primaryDetails)==null?void 0:m.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(m){c(m,"integrated")},get duration(){return u("integrated")},get seekableStart(){var m;return r(((m=e.primaryDetails)==null?void 0:m.fragmentStart)||0,"integrated")}},skip:()=>{const m=e.effectivePlayingItem,g=m?.event;if(g&&!g.restrictions.skip){const v=e.findItemIndex(m);if(g.appendInPlace){const b=m.playout.start+m.event.duration;c(b+.001,"playout")}else e.advanceAfterAssetEnded(g,v,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const r=(t=n)==null?void 0:t.currentTime;if(!(r===void 0||!Qe(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,n=e.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ui(r)}`),this.detachedData=r}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var i,n;if(e.media===t)return;let r=null;const o=this.hls,u=e!==o,c=u&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource;let f;if(o.media)c&&(r=o.transferMedia(),this.detachedData=r),f="Primary";else if(d){const b=this.getBufferingPlayer();b?(r=b.transferMedia(),f=`${b}`):f="detached MediaSource"}else f="detached media";if(!r){if(d)r=this.detachedData,this.log(`using detachedData: MediaSource ${ui(r)}`);else if(!this.detachedData||o.media===t){const b=this.playerQueue;b.length>1&&b.forEach(_=>{if(u&&_.interstitial.appendInPlace!==c){const E=_.interstitial;this.clearInterstitial(_.interstitial,null),E.appendInPlace=!1,E.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${E}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const m=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",g=m&&r?r:t;this.log(`${m?"transfering MediaSource":"attaching media"} to ${u?e:"Primary"} from ${f} (media.currentTime: ${t.currentTime})`);const v=this.schedule;if(g===r&&v){const b=u&&e.assetId===v.assetIdAtEnd;g.overrides={duration:v.duration,endOfStream:!u||b,cueRemoval:!u}}e.attachMedia(g)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,n=this.effectivePlayingItem;if(i===-1){const r=this.hls.startPosition;if(this.log(ap("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(r>=0||!this.primaryLive){const o=this.timelinePos=r>0?r:0,u=e.findItemIndexAtTime(o);this.setSchedulePosition(u)}}else if(n&&!this.playingItem){const r=e.findItemIndex(n);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const i=e.event,n=i.findAssetIndex(t),r=Yy(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var o;const u=(o=this.schedule.items)==null?void 0:o[this.findItemIndex(e)+1];u&&this.bufferedToItem(u)}}advanceAfterAssetEnded(e,t,i){const n=Yy(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const o=t+1,u=r.length;if(o>=u){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Qn(r)}) pos: ${this.timelinePos}`);const o=this.waitingItem||this.playingItem,u=this.playingLastItem;if(this.isInterstitial(o)){const f=o.event,m=this.playingAsset,g=m?.identifier,v=g?this.getAssetPlayer(g):null;if(v&&g&&(!this.eventItemsMatch(o,r)||t!==void 0&&g!==f.assetList[t].identifier)){var c;const b=f.findAssetIndex(m);if(this.log(`INTERSTITIAL_ASSET_ENDED ${b+1}/${f.assetList.length} ${ku(m)}`),this.endedAsset=m,this.playingAsset=null,this.hls.trigger(N.INTERSTITIAL_ASSET_ENDED,{asset:m,assetListIndex:b,event:f,schedule:n.slice(0),scheduleIndex:e,player:v}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(f,this.findItemIndex(this.playingItem),b);return}this.retreiveMediaSource(g,r),v.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&v.detachMedia()}if(!this.eventItemsMatch(o,r)&&(this.endedItem=o,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${f} ${Qn(o)}`),f.hasPlayed=!0,this.hls.trigger(N.INTERSTITIAL_ENDED,{event:f,schedule:n.slice(0),scheduleIndex:e}),f.cue.once)){var d;this.updateSchedule();const b=(d=this.schedule)==null?void 0:d.items;if(r&&b){const _=this.findItemIndex(r);this.advanceSchedule(_,b,t,o,u)}return}}this.advanceSchedule(e,n,t,o,u)}advanceSchedule(e,t,i,n,r){const o=this.schedule;if(!o)return;const u=t[e]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(f=>{const m=f.interstitial,g=o.findEventIndex(m.identifier);(ge+1)&&this.clearInterstitial(m,u)}),this.isInterstitial(u)){this.timelinePos=Math.min(Math.max(this.timelinePos,u.start),u.end);const f=u.event;if(i===void 0){i=o.findAssetIndex(f,this.timelinePos);const b=Yy(f,i-1);if(f.isAssetPastPlayoutLimit(b)||f.appendInPlace&&this.timelinePos===u.end){this.advanceAfterAssetEnded(f,e,i);return}i=b}const m=this.waitingItem;this.assetsBuffered(u,c)||this.setBufferingItem(u);let g=this.preloadAssets(f,i);if(this.eventItemsMatch(u,m||n)||(this.waitingItem=u,this.log(`INTERSTITIAL_STARTED ${Qn(u)} ${f.appendInPlace?"append in place":""}`),this.hls.trigger(N.INTERSTITIAL_STARTED,{event:f,schedule:t.slice(0),scheduleIndex:e})),!f.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${f}`);return}if(f.assetListLoader&&(f.assetListLoader.destroy(),f.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${f}`);return}this.waitingItem=this.endedItem=null,this.playingItem=u;const v=f.assetList[i];if(!v){this.advanceAfterAssetEnded(f,e,i||0);return}if(g||(g=this.getAssetPlayer(v.identifier)),g===null||g.destroyed){const b=f.assetList.length;this.warn(`asset ${i+1}/${b} player destroyed ${f}`),g=this.createAssetPlayer(f,v,i),g.loadSource()}if(!this.eventItemsMatch(u,this.bufferingItem)&&f.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(g,i,t,e,c),this.shouldPlay&&C2(g.media)}else u?(this.resumePrimary(u,e,n),this.shouldPlay&&C2(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(o.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var n,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Qn(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let u=this.timelinePos;(u=e.end)&&(u=this.getPrimaryResumption(e,t),this.log(ap("resumePrimary",u)),this.timelinePos=u),this.attachPrimary(u,e)}if(!i)return;const o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Qn(e)}`),this.hls.trigger(N.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(in.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:_t.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,n),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(ap("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((i=n.mainForwardBufferInfo)==null?void 0:i.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(N.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(N.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const n=Qt(Qt({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Qt(Qt({},this.altSelection),{},{audio:i});return}const r=Qt(Qt({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Qt(Qt({},this.altSelection),{},{subtitles:i});return}const r=Qt(Qt({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=M1(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=M1(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((r,o)=>{e.event.isAssetPastPlayoutLimit(o)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=_t.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Qn(e)} (was ${Qn(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const n=_t.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,i,e)}updateBufferedPos(e,t,i){const n=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const o=this.playingItem,u=this.findItemIndex(o);let c=n.findItemIndexAtTime(e);if(this.bufferedPos=r.end||(d=g.event)!=null&&d.appendInPlace&&e+.01>=g.start)&&(c=m),this.isInterstitial(r)){const v=r.event;if(m-u>1&&v.appendInPlace===!1||v.assetList.length===0&&v.assetListLoader)return}if(this.bufferedPos=e,c>f&&c>u)this.bufferedToItem(g);else{const v=this.primaryDetails;this.primaryLive&&v&&e>v.edge-v.targetduration&&g.start{const r=this.getAssetPlayer(n.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:n,events:r}=i;if(!n||!r)return t;const o=this.isInterstitial(e),u=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=u?u.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Qn(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(o){const d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((f,m)=>{const g=this.getAssetPlayer(f.identifier);g&&(m===d&&g.loadSource(),g.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(N.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,n=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(n||!r){const o=this.preloadAssets(i,t);if(o!=null&&o.interstitial.appendInPlace){const u=this.primaryMedia;u&&this.bufferAssetPlayer(o,u)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,o=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var u;const g=this.playingItem;!this.isInterstitial(g)&&(g==null||(u=g.nextEvent)==null?void 0:u.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let d,f=0;if(!this.playingItem&&this.primaryLive&&(f=this.hls.startPosition,f===-1&&(f=this.hls.liveSyncPosition||0)),f&&!(e.cue.pre||e.cue.post)){const g=f-c;g>0&&(d=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:n} ${e}${d?` live-start: ${f} start-offset: ${d}`:""}`),i)return this.createAsset(e,0,0,c,e.duration,i);const m=this.assetListLoader.loadAssetList(e,d);m&&(e.assetListLoader=m)}else if(!o&&n){for(let d=t;d{this.hls.trigger(N.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i1){const U=t.duration;U&&F{if(F.live){var U;const q=new Error(`Interstitials MUST be VOD assets ${e}`),k={fatal:!0,type:ot.OTHER_ERROR,details:ve.INTERSTITIAL_ASSET_ITEM_ERROR,error:q},R=((U=this.schedule)==null?void 0:U.findEventIndex(e.identifier))||-1;this.handleAssetItemError(k,e,R,i,q.message);return}const V=F.edge-F.fragmentStart,B=t.duration;(_||B===null||V>B)&&(_=!1,this.log(`Interstitial asset "${m}" duration change ${B} > ${V}`),t.duration=V,this.updateSchedule())};b.on(N.LEVEL_UPDATED,(F,{details:U})=>E(U)),b.on(N.LEVEL_PTS_UPDATED,(F,{details:U})=>E(U)),b.on(N.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const L=(F,U)=>{const V=this.getAssetPlayer(m);if(V&&U.tracks){V.off(N.BUFFER_CODECS,L),V.tracks=U.tracks;const B=this.primaryMedia;this.bufferingAsset===V.assetItem&&B&&!V.media&&this.bufferAssetPlayer(V,B)}};b.on(N.BUFFER_CODECS,L);const I=()=>{var F;const U=this.getAssetPlayer(m);if(this.log(`buffered to end of asset ${U}`),!U||!this.schedule)return;const V=this.schedule.findEventIndex(e.identifier),B=(F=this.schedule.items)==null?void 0:F[V];this.isInterstitial(B)&&this.advanceAssetBuffering(B,t)};b.on(N.BUFFERED_TO_END,I);const w=F=>()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;this.shouldPlay=!0;const V=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,V,F)};return b.once(N.MEDIA_ENDED,w(i)),b.once(N.PLAYOUT_LIMIT_REACHED,w(1/0)),b.on(N.ERROR,(F,U)=>{if(!this.schedule)return;const V=this.getAssetPlayer(m);if(U.details===ve.BUFFER_STALLED_ERROR){if(V!=null&&V.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(U,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${U.error} ${e}`)}),b.on(N.DESTROYING,()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;const U=new Error(`Asset player destroyed unexpectedly ${m}`),V={fatal:!0,type:ot.OTHER_ERROR,details:ve.INTERSTITIAL_ASSET_ITEM_ERROR,error:U};this.handleAssetItemError(V,e,this.schedule.findEventIndex(e.identifier),i,U.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ku(t)}`),this.hls.trigger(N.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:b}),b}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const n=this.playerQueue[i];this.log(`clear ${n} toSegment: ${t&&Qn(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(i,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,n,r){const{interstitial:o,assetItem:u,assetId:c}=e,d=o.assetList.length,f=this.playingAsset;this.endedAsset=null,this.playingAsset=u,(!f||f.identifier!==c)&&(f&&(this.clearAssetPlayer(f.identifier,i[n]),delete f.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${ku(u)}`),this.hls.trigger(N.INTERSTITIAL_ASSET_STARTED,{asset:u,assetListIndex:t,event:o,schedule:i.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,n;if(!this.schedule)return;const{interstitial:r,assetItem:o}=e,u=this.schedule.findEventIndex(r.identifier),c=(i=this.schedule.items)==null?void 0:i[u];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=o;const d=this.getBufferingPlayer();if(d===e)return;const f=r.appendInPlace;if(f&&d?.interstitial.appendInPlace===!1)return;const m=d?.tracks||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(f&&o!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(m&&!vw(m,e.tracks)){const g=new Error(`Asset ${ku(o)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(m)}')`),v={fatal:!0,type:ot.OTHER_ERROR,details:ve.INTERSTITIAL_ASSET_ITEM_ERROR,error:g},b=r.findAssetIndex(o);this.handleAssetItemError(v,r,u,b,g.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const n=i.currentTime,r=t.findAssetIndex(e,n),o=e.assetList[r];if(o){const u=this.getAssetPlayer(o.identifier);if(u){const c=u.currentTime||n-o.timelineStart,d=u.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${u} ${e} (media.currentTime: ${n})`),c&&(d/i.playbackRate<.5||u.bufferedInPlaceToEnd(i))&&u.hls){const f=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,f,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime!_.error))t.error=b;else for(let _=n;_{const L=parseFloat(_.DURATION);this.createAsset(r,E,f,c+f,L,_.URI),f+=L}),r.duration=f,this.log(`Loaded asset-list with duration: ${f} (was: ${d}) ${r}`);const m=this.waitingItem,g=m?.event.identifier===o;this.updateSchedule();const v=(n=this.bufferingItem)==null?void 0:n.event;if(g){var b;const _=this.schedule.findEventIndex(o),E=(b=this.schedule.items)==null?void 0:b[_];if(E){if(!this.playingItem&&this.timelinePos>E.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==_){r.error=new Error(`Interstitial ${u.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(E)}this.setSchedulePosition(_)}else if(v?.identifier===o){const _=r.assetList[0];if(_){const E=this.getAssetPlayer(_.identifier);if(v.appendInPlace){const L=this.primaryMedia;E&&L&&this.bufferAssetPlayer(E,L)}else E&&E.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case ve.ASSET_LIST_PARSING_ERROR:case ve.ASSET_LIST_LOAD_ERROR:case ve.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case ve.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const D2=500;class E6 extends lb{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",it.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(N.LEVEL_LOADED,this.onLevelLoaded,this),e.on(N.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(N.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(N.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(N.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(N.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(N.LEVEL_LOADED,this.onLevelLoaded,this),e.off(N.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(N.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(N.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(N.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(N.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Pe.IDLE,this.setInterval(D2),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(this.fragContextChanged(i)||(Ui(i)&&(this.fragPrevious=i),this.state=Pe.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let o;const u=i.start;for(let d=0;d=r[d].start&&u<=r[d].end){o=r[d];break}const c=i.start+i.duration;o?o.end=c:(o={start:u,end:c},r.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const r=n-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(o=>{for(let u=0;unew Zd(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new Zd(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,it.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==Pe.STOPPED&&this.setInterval(D2)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:o,id:u}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${u}`);return}const c=r[u];if(u>=r.length||!c)return;this.log(`Subtitle track ${u} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(o.live||(i=c.details)!=null&&i.live){if(o.deltaUpdateFailed)return;const m=this.mainDetails;if(!m){this.startFragRequested=!1;return}const g=m.fragments[0];if(!c.details)o.hasProgramDateTime&&m.hasProgramDateTime?(rm(o,m),d=o.fragmentStart):g&&(d=g.start,Xv(o,d));else{var f;d=this.alignPlaylists(o,c.details,(f=this.levelLastLoaded)==null?void 0:f.details),d===0&&g&&(d=g.start,Xv(o,d))}m&&!this.startFragRequested&&this.setStartPosition(m,d)}c.details=o,this.levelLastLoaded=c,u===n&&(this.hls.trigger(N.SUBTITLE_TRACK_UPDATED,{details:o,id:u,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===Pe.IDLE&&(Cl(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,n=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&Ku(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,ab(n.method)).catch(u=>{throw r.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:t}),u}).then(u=>{const c=performance.now();r.trigger(N.FRAG_DECRYPTED,{frag:t,payload:u,stats:{tstart:o,tdecrypt:c}})}).catch(u=>{this.warn(`${u.name}: ${u.message}`),this.state=Pe.IDLE})}}doTick(){if(!this.media){this.state=Pe.IDLE;return}if(this.state===Pe.IDLE){const{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:n}=this,r=this.getLoadPosition(),o=_t.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:c}=o,d=i.details,f=this.hls.maxBufferLength+d.levelTargetDuration;if(c>f)return;const m=d.fragments,g=m.length,v=d.edge;let b=null;const _=this.fragPrevious;if(uv-I?0:I;b=Cl(_,m,Math.max(m[0].start,u),w),!b&&_&&_.start{if(n=n>>>0,n>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const C6={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},BL=s=>String.fromCharCode(C6[s]||s),Zn=15,da=100,D6={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},w6={17:2,18:4,21:6,22:8,23:10,19:13,20:15},L6={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},I6={25:2,26:4,29:6,30:8,31:10,27:13,28:15},k6=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class R6{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;Zt.log(`${this.time} [${e}] ${i}`)}}}const ll=function(e){const t=[];for(let i=0;ida&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=da)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=BL(e);if(this.pos>=da){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t"pacData = "+ui(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+ui(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",n=-1;for(let r=0;r0&&(e?i="["+t.join(" | ")+"]":i=t.join(` -`)),i}getTextAndFormat(){return this.rows}}class w2{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Wy(i),this.nonDisplayedMemory=new Wy(i),this.lastOutputScreen=new Wy(i),this.currRollUpRow=this.displayedMemory.rows[Zn-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Zn-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;it+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[i]}this.logger.log(2,"MIDROW: "+ui(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class L2{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=N6(),this.logger=void 0;const n=this.logger=new R6;this.channels=[null,new w2(e,t,n),new w2(e+1,i,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i"["+ll([t[i],t[i+1]])+"] -> ("+ll([n,r])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(M6(n,r,c)){op(null,null,c),this.logger.log(3,()=>"Repeated command ("+ll([n,r])+") is dropped");continue}op(n,r,this.cmdHistory),o=this.parseCmd(n,r),o||(o=this.parseMidrow(n,r)),o||(o=this.parsePAC(n,r)),o||(o=this.parseBackgroundAttributes(n,r))}else op(null,null,c);if(!o&&(u=this.parseChars(n,r),u)){const f=this.currentChannel;f&&f>0?this.channels[f].insertChars(u):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!u&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ll([n,r])+" orig: "+ll([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(i||n))return!1;const r=e===20||e===21||e===23?1:2,o=this.channels[r];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[i];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+ll([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(n||r))return!1;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?D6[e]:L6[e]:i=o===1?w6[e]:I6[e];const u=this.channels[o];return u?(u.setPAC(this.interpretPAC(i,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,n.underline=(i&1)===1,i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((i-16)/2)*4,n}parseChars(e,t){let i,n=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let o;r===17?o=t+80:r===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+BL(o)+"' in channel "+i),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+ll(n).join(",")),n}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(i||n))return!1;let r;const o={};e===16||e===24?(r=Math.floor((t-32)/2),o.background=k6[r],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const u=e<=23?1:2;return this.channels[u].setBkgData(o),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");V=R,this.hasBeenReset=!0}})),Object.defineProperty(f,"positionAlign",r({},m,{get:function(){return B},set:function(R){const K=n(R);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");B=K,this.hasBeenReset=!0}})),Object.defineProperty(f,"size",r({},m,{get:function(){return q},set:function(R){if(R<0||R>100)throw new Error("Size must be between 0 and 100.");q=R,this.hasBeenReset=!0}})),Object.defineProperty(f,"align",r({},m,{get:function(){return k},set:function(R){const K=n(R);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");k=K,this.hasBeenReset=!0}})),f.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})();class B6{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function UL(s){function e(i,n,r,o){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(o||0)}const t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class F6{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let n=0;n=0&&i<=100)return this.set(e,i),!0}return!1}}function $L(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const o=n[r].split(t);if(o.length!==2)continue;const u=o[0],c=o[1];e(u,c)}}const nT=new bb(0,0,""),lp=nT.align==="middle"?"middle":"center";function U6(s,e,t){const i=s;function n(){const u=UL(s);if(u===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),u}function r(u,c){const d=new F6;$L(u,function(g,v){let b;switch(g){case"region":for(let _=t.length-1;_>=0;_--)if(t[_].id===v){d.set(g,t[_].region);break}break;case"vertical":d.alt(g,v,["rl","lr"]);break;case"line":b=v.split(","),d.integer(g,b[0]),d.percent(g,b[0])&&d.set("snapToLines",!1),d.alt(g,b[0],["auto"]),b.length===2&&d.alt("lineAlign",b[1],["start",lp,"end"]);break;case"position":b=v.split(","),d.percent(g,b[0]),b.length===2&&d.alt("positionAlign",b[1],["start",lp,"end","line-left","line-right","auto"]);break;case"size":d.percent(g,v);break;case"align":d.alt(g,v,["start",lp,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let f=d.get("line","auto");f==="auto"&&nT.line===-1&&(f=-1),c.line=f,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",lp);let m=d.get("position","auto");m==="auto"&&nT.position===50&&(m=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=m}function o(){s=s.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),o(),e.endTime=n(),o(),r(s,e)}function jL(s){return s.replace(//gi,` -`)}class $6{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new B6,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,o=0;for(r=jL(r);o")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{U6(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const u=r.indexOf("-->")!==-1;if(!r||u&&(o=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` -`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` - -`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const j6=/\r\n|\n\r|\n|\r/g,Xy=function(e,t,i=0){return e.slice(i,i+t.length)===t},H6=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!Qe(t)||!Qe(i)||!Qe(n)||!Qe(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=3600*1e3*r,t};function _b(s,e,t){return Vd(s.toString())+Vd(e.toString())+Vd(t)}const G6=function(e,t,i){let n=e[t],r=e[n.prevCC];if(!r||!r.new&&n.new){e.ccOffset=e.presentationOffset=n.start,n.new=!1;return}for(;(o=r)!=null&&o.new;){var o;e.ccOffset+=n.start-r.start,n.new=!1,n=r,r=e[n.prevCC]}e.presentationOffset=i};function V6(s,e,t,i,n,r,o){const u=new $6,c=Sn(new Uint8Array(s)).trim().replace(j6,` -`).split(` -`),d=[],f=e?X8(e.baseTime,e.timescale):0;let m="00:00.000",g=0,v=0,b,_=!0;u.oncue=function(E){const L=t[i];let I=t.ccOffset;const w=(g-f)/9e4;if(L!=null&&L.new&&(v!==void 0?I=t.ccOffset=L.start:G6(t,i,w)),w){if(!e){b=new Error("Missing initPTS for VTT MPEGTS");return}I=w-t.presentationOffset}const F=E.endTime-E.startTime,U=_n((E.startTime+I-v)*9e4,n*9e4)/9e4;E.startTime=Math.max(U,0),E.endTime=Math.max(U+F,0);const V=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(V)),E.id||(E.id=_b(E.startTime,E.endTime,V)),E.endTime>0&&d.push(E)},u.onparsingerror=function(E){b=E},u.onflush=function(){if(b){o(b);return}r(d)},c.forEach(E=>{if(_)if(Xy(E,"X-TIMESTAMP-MAP=")){_=!1,E.slice(16).split(",").forEach(L=>{Xy(L,"LOCAL:")?m=L.slice(6):Xy(L,"MPEGTS:")&&(g=parseInt(L.slice(7)))});try{v=H6(m)/1e3}catch(L){b=L}return}else E===""&&(_=!1);u.parse(E+` -`)}),u.flush()}const Qy="stpp.ttml.im1t",HL=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,GL=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,q6={left:"start",center:"center",right:"end",start:"start",end:"end"};function I2(s,e,t,i){const n=kt(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>Sn(u)),o=W8(e.baseTime,1,e.timescale);try{r.forEach(u=>t(z6(u,o)))}catch(u){i(u)}}function z6(s,e){const n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(r).reduce((m,g)=>(m[g]=n.getAttribute(`ttp:${g}`)||r[g],m),{}),u=n.getAttribute("xml:space")!=="preserve",c=k2(Zy(n,"styling","style")),d=k2(Zy(n,"layout","region")),f=Zy(n,"body","[begin]");return[].map.call(f,m=>{const g=VL(m,u);if(!g||!m.hasAttribute("begin"))return null;const v=ev(m.getAttribute("begin"),o),b=ev(m.getAttribute("dur"),o);let _=ev(m.getAttribute("end"),o);if(v===null)throw R2(m);if(_===null){if(b===null)throw R2(m);_=v+b}const E=new bb(v-e,_-e,g);E.id=_b(E.startTime,E.endTime,E.text);const L=d[m.getAttribute("region")],I=c[m.getAttribute("style")],w=K6(L,I,c),{textAlign:F}=w;if(F){const U=q6[F];U&&(E.lineAlign=U),E.align=F}return ni(E,w),E}).filter(m=>m!==null)}function Zy(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function k2(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function VL(s,e){return[].slice.call(s.childNodes).reduce((t,i,n)=>{var r;return i.nodeName==="br"&&n?t+` -`:(r=i.childNodes)!=null&&r.length?VL(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function K6(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(n=t[o]),r.reduce((u,c)=>{const d=Jy(e,i,c)||Jy(s,i,c)||Jy(n,i,c);return d&&(u[c]=d),u},{})}function Jy(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function R2(s){return new Error(`Could not parse ttml timestamp ${s}`)}function ev(s,e){if(!s)return null;let t=UL(s);return t===null&&(HL.test(s)?t=Y6(s,e):GL.test(s)&&(t=W6(s,e))),t}function Y6(s,e){const t=HL.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function W6(s,e){const t=GL.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class up{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class X6{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=P2(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(N.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(N.FRAG_LOADING,this.onFragLoading,this),e.on(N.FRAG_LOADED,this.onFragLoaded,this),e.on(N.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(N.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(N.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(N.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(N.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(N.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(N.FRAG_LOADING,this.onFragLoading,this),e.off(N.FRAG_LOADED,this.onFragLoaded,this),e.off(N.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(N.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(N.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(N.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(N.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new up(this,"textTrack1"),t=new up(this,"textTrack2"),i=new up(this,"textTrack3"),n=new up(this,"textTrack4");this.cea608Parser1=new L2(1,e,t),this.cea608Parser2=new L2(3,i,n)}addCues(e,t,i,n,r){let o=!1;for(let u=r.length;u--;){const c=r[u],d=Q6(c[0],c[1],t,i);if(d>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),o=!0,d/(i-t)>.5))return}if(o||r.push([t,i]),this.config.renderTextTracksNatively){const u=this.captionsTracks[e];this.Cues.newCue(u,t,i,n)}else{const u=this.Cues.newCue(null,t,i,n);this.hls.trigger(N.CUES_PARSED,{type:"captions",cues:u,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:o}){const{unparsedVttFrags:u}=this;i===it.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:o}),u.length&&(this.unparsedVttFrags=[],u.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(N.FRAG_LOADED,c):this.hls.trigger(N.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let n=0;n{Mu(n[r]),delete n[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=P2(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;ir.textCodec===Qy);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(_L(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media,u=o?Ap(o.textTracks):null;if(this.tracks.forEach((c,d)=>{let f;if(u){let m=null;for(let g=0;gd!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(u=>({label:u.name,kind:u.type.toLowerCase(),default:u.default,subtitleTrack:u}));this.hls.trigger(N.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const n=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!n)return;const r=`textTrack${n[1]}`,o=this.captionsProperties[r];o&&(o.label=i.name,i.lang&&(o.languageCode=i.lang),o.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===it.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:o,lastSn:u}=this,{cc:c,sn:d}=t.frag,f=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&o&&(d!==u+1||d===u&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),o.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===it.SUBTITLE)if(n.byteLength){const r=i.decryptdata,o="stats"in t;if(r==null||!r.encrypted||o){const u=this.tracks[i.level],c=this.vttCCs;c[i.cc]||(c[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),u&&u.textCodec===Qy?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(N.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;I2(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(N.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger(N.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:o}=this,u=r.length-1;if(!r[i.cc]&&u===-1){o.push(e);return}const c=this.hls,d=(t=i.initSegment)!=null&&t.data?Fn(i.initSegment.data,new Uint8Array(n)).buffer:n;V6(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger(N.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const m=f.message==="Missing initPTS for VTT MPEGTS";m?o.push(e):this._fallbackToIMSC1(i,n),c.logger.log(`Failed to parse VTT cue: ${f}`),!(m&&u>i.cc)&&c.trigger(N.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||I2(t,this.initPTS[e.cc],()=>{i.textCodec=Qy,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(r=>ML(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(N.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===it.SUBTITLE&&this.onFragLoaded(N.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:n}=t;if(!(i.type===it.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;rsT(u[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(c=>sT(u[c],t,n))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let n=2;for(let r=0;r=16?c--:c++;const v=jL(d.trim()),b=_b(e,t,v);s!=null&&(m=s.cues)!=null&&m.getCueById(b)||(o=new f(e,t,v),o.id=b,o.line=g+1,o.align="left",o.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(o))}return s&&n.length&&(n.sort((g,v)=>g.line==="auto"||v.line==="auto"?0:g.line>8&&v.line>8?v.line-g.line:g.line-v.line),n.forEach(g=>ML(s,g))),n}};function e$(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const t$=/(\d+)-(\d+)\/(\d+)/;class M2{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||r$,this.controller=new self.AbortController,this.stats=new JT}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const r=i$(e,this.controller.signal),o=e.responseType==="arraybuffer",u=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&Qe(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(th(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(m=>{var g;this.response=this.loader=m;const v=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},d-(v-n.loading.start)),!m.ok){const{status:_,statusText:E}=m;throw new a$(E||"fetch, bad network response",_,m)}n.loading.first=v,n.total=n$(m.headers)||n.total;const b=(g=this.callbacks)==null?void 0:g.onProgress;return b&&Qe(t.highWaterMark)?this.loadProgressively(m,n,e,t.highWaterMark,b):o?m.arrayBuffer():e.responseType==="json"?m.json():m.text()}).then(m=>{var g,v;const b=this.response;if(!b)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const _=m[u];_&&(n.loaded=n.total=_);const E={url:b.url,data:m,code:b.status},L=(g=this.callbacks)==null?void 0:g.onProgress;L&&!Qe(t.highWaterMark)&&L(n,e,m,b),(v=this.callbacks)==null||v.onSuccess(E,n,e,b)}).catch(m=>{var g;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const v=m&&m.code||0,b=m?m.message:null;(g=this.callbacks)==null||g.onError({code:v,text:b},e,m?m.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,n=0,r){const o=new tL,u=e.body.getReader(),c=()=>u.read().then(d=>{if(d.done)return o.dataLength&&r(t,i,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=d.value,m=f.length;return t.loaded+=m,m=n&&r(t,i,o.flush().buffer,e)):r(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function i$(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ni({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function s$(s){const e=t$.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function n$(s){const e=s.get("Content-Range");if(e){const i=s$(e);if(Qe(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function r$(s,e){return new self.Request(s.url,e)}class a$ extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const o$=/^age:\s*[\d.]+\s*$/im;class zL{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new JT,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(o=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(o=>{var u;(u=this.callbacks)==null||u.onError({code:i.status,text:o.message},t,i,n)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:o}=i.loadPolicy;if(n)for(const u in n)e.setRequestHeader(u,n[u]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&Qe(r)?r:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const n=t.readyState,r=this.config;if(!i.aborted&&n>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const d=t.status,f=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const b=f??t.response;if(b!=null){var o,u;i.loading.end=Math.max(self.performance.now(),i.loading.first);const _=t.responseType==="arraybuffer"?b.byteLength:b.length;i.loaded=i.total=_,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const E=(o=this.callbacks)==null?void 0:o.onProgress;E&&E(i,e,b,t);const L={url:t.responseURL,data:b,code:d};(u=this.callbacks)==null||u.onSuccess(L,i,e,t);return}}const m=r.loadPolicy.errorRetry,g=i.retry,v={url:e.url,data:void 0,code:d};if(im(m,g,!1,v))this.retry(m);else{var c;Zt.error(`${d} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:d,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(im(e,t,!0))this.retry(e);else{var i;Zt.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=sb(e,i.retry),i.retry++,Zt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&o$.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const l$={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},u$=Qt(Qt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:zL,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:_F,bufferController:dU,capLevelController:yb,errorController:CF,fpsController:h6,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Vw,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:l$},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},c$()),{},{subtitleStreamController:E6,subtitleTrackController:m6,timelineController:X6,audioStreamController:oU,audioTrackController:lU,emeController:Yu,cmcdController:l6,contentSteeringController:c6,interstitialsController:S6});function c$(){return{cueHandler:J6,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function d$(s,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=rT(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(o=>{const u=`${o==="level"?"playlist":o}LoadPolicy`,c=e[u]===void 0,d=[];r.forEach(f=>{const m=`${o}Loading${f}`,g=e[m];if(g!==void 0&&c){d.push(m);const v=i[u].default;switch(e[u]={default:v},f){case"TimeOut":v.maxLoadTimeMs=g,v.maxTimeToFirstByteMs=g;break;case"MaxRetry":v.errorRetry.maxNumRetry=g,v.timeoutRetry.maxNumRetry=g;break;case"RetryDelay":v.errorRetry.retryDelayMs=g,v.timeoutRetry.retryDelayMs=g;break;case"MaxRetryTimeout":v.errorRetry.maxRetryDelayMs=g,v.timeoutRetry.maxRetryDelayMs=g;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${u}": ${ui(e[u])}`)}),Qt(Qt({},i),e)}function rT(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(rT):Object.keys(s).reduce((e,t)=>(e[t]=rT(s[t]),e),{}):s}function h$(s,e){const t=s.loader;t!==M2&&t!==zL?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):e$()&&(s.loader=M2,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Cp=2,f$=.1,p$=.05,m$=100;class g$ extends Uw{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(N.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(N.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(N.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(m$),this.mediaSource=t.mediaSource;const i=this.media=t.media;Fs(i,"playing",this.onMediaPlaying),Fs(i,"waiting",this.onMediaWaiting),Fs(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(sn(i,"playing",this.onMediaPlaying),sn(i,"waiting",this.onMediaWaiting),sn(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,n;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const o=this.media;if(!o)return;const{seeking:u}=o,c=this.seeking&&!u,d=!this.seeking&&u,f=o.paused&&!u||o.ended||o.playbackRate===0;if(this.seeking=u,e!==t){t&&(this.ended=0),this.moved=!0,u||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!f&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||c){c&&this.stallResolved(e);return}if(f){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(N.MEDIA_ENDED,{stalled:!1}));return}if(!_t.getBuffered(o).length){this.nudgeRetry=0;return}const m=_t.bufferInfo(o,e,0),g=m.nextStart||0,v=this.fragmentTracker;if(u&&v&&this.hls){const V=N2(this.hls.inFlightFragments,e),B=m.len>Cp,q=!g||V||g-e>Cp&&!v.getPartialFragment(e);if(B||q)return;this.moved=!1}const b=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&v){if(!(m.len>0)&&!g)return;const B=Math.max(g,m.start||0)-e,k=!!(b!=null&&b.live)?b.targetduration*2:Cp,R=cp(e,v);if(B>0&&(B<=k||R)){o.paused||this._trySkipBufferHole(R);return}}const _=r.detectStallWithCurrentTimeMs,E=self.performance.now(),L=this.waiting;let I=this.stalled;if(I===null)if(L>0&&E-L<_)I=this.stalled=L;else{this.stalled=E;return}const w=E-I;if(!u&&(w>=_||L)&&this.hls){var F;if(((F=this.mediaSource)==null?void 0:F.readyState)==="ended"&&!(b!=null&&b.live)&&Math.abs(e-(b?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(N.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(m),!this.media||!this.hls)return}const U=_t.bufferInfo(o,e,r.maxBufferHole);this._tryFixBufferStall(U,w,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(N.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&n&&n.length>1&&e>n.end(0)){const r=_t.bufferedInfo(_t.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const o=_t.timeRangesToArray(n),u=_t.bufferedInfo(o,t,0).bufferedIndex;if(u>-1&&uu)&&f-d<1&&e-d<2){const m=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${f} buffered index: ${c}`);this.warn(m.message),this.media.currentTime+=1e-6;let g=cp(e,this.fragmentTracker);g&&"fragment"in g?g=g.fragment:g||(g=void 0);const v=_t.bufferInfo(this.media,e,0);this.hls.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,frag:g,buffer:v.len,bufferInfo:v})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:o,media:u}=this,c=(n=this.hls)==null?void 0:n.config;if(!u||!o||!c)return;const d=(r=this.hls)==null?void 0:r.latestLevelDetails,f=cp(i,o);if((f||d!=null&&d.live&&i1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-ic.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,n=e.nextStart;if(i&&n){const r=i.getFragAtPos(t,it.MAIN),o=i.getFragAtPos(n,it.MAIN);if(r&&o)return o.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:n,stalled:r}=this;if(!n&&r!==null&&i&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ui(e)})`);this.warn(o.message),t.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:n}=this,r=(t=this.hls)==null?void 0:t.config;if(!n||!i||!r)return 0;const o=n.currentTime,u=_t.bufferInfo(n,o,0),c=o0&&u.len<1&&n.readyState<3,g=c-o;if(g>0&&(f||m)){if(g>r.maxBufferHole){let b=!1;if(o===0){const _=i.getAppendedFrag(0,it.MAIN);_&&c<_.end&&(b=!0)}if(!b&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||N2(this.hls.inFlightFragments,c))return 0;let E=!1,L=e.end;for(;L"u"))return self.VTTCue||self.TextTrackCue}function tv(s,e,t,i,n){let r=new s(e,t,"");try{r.value=i,n&&(r.type=n)}catch{r=new s(e,t,ui(n?Qt({type:n},i):i))}return r}const dp=(()=>{const s=aT();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class v${constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(N.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(N.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(N.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(N.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(N.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(N.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(N.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(N.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Mu(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tdp&&(m=dp),m-f<=0&&(m=f+y$);for(let v=0;vf.type===xn.audioId3&&c:n==="video"?d=f=>f.type===xn.emsg&&u:d=f=>f.type===xn.audioId3&&c||f.type===xn.emsg&&u,sT(r,t,i,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:n,enableDateRangeMetadataCues:r,interstitialsController:o}=this.hls.config;if(!r)return;const u=aT();if(i&&n&&!o){const{fragmentStart:_,fragmentEnd:E}=e;let L=this.assetCue;L?(L.startTime=_,L.endTime=E):u&&(L=this.assetCue=tv(u,_,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),L&&(L.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(L),L.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=e,f=Object.keys(d);let m=this.dateRangeCuesAppended;if(c&&t){var g;if((g=c.cues)!=null&&g.length){const _=Object.keys(m).filter(E=>!f.includes(E));for(let E=_.length;E--;){var v;const L=_[E],I=(v=m[L])==null?void 0:v.cues;delete m[L],I&&Object.keys(I).forEach(w=>{const F=I[w];if(F){F.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(F)}catch{}}})}}else m=this.dateRangeCuesAppended={}}const b=e.fragments[e.fragments.length-1];if(!(f.length===0||!Qe(b?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(X!==L.id){const ee=d[X];if(ee.class===L.class&&ee.startDate>L.startDate&&(!K||L.startDate.01&&(X.startTime=I,X.endTime=V);else if(u){let ee=L.attr[K];$F(K)&&(ee=Tw(ee));const ae=tv(u,I,V,{key:K,data:ee},xn.dateRange);ae&&(ae.id=E,this.id3Track.addCue(ae),F[K]=ae,o&&(K==="X-ASSET-LIST"||K==="X-ASSET-URL")&&ae.addEventListener("enter",this.onEventCueEnter))}}m[E]={cues:F,dateRange:L,durationKnown:U}}}}}class T${constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:o}=this.config;if(!r||o===1||!i.live)return;const u=this.targetLatency;if(u===null)return;const c=n-u,d=Math.min(this.maxLatency,u+i.targetduration);if(c.05&&this.forwardBufferLength>1){const m=Math.min(2,Math.max(1,o)),g=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,v=Math.min(m,Math.max(1,g));this.changeMediaPlaybackRate(t,v)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:n}=e,{liveSyncDuration:r,liveSyncDurationCount:o,lowLatencyMode:u}=this.config,c=this.hls.userConfig;let d=u&&i||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=r!==void 0?r:o*n);const f=n;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,f)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const n=i.edge,r=e-t-this.edgeStalled,o=n-i.totalduration,u=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(o,r),u)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(N.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(N.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(N.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(N.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===ve.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,n;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class b$ extends gb{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(N.LEVEL_LOADED,this.onLevelLoaded,this),e.on(N.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(N.FRAG_BUFFERED,this.onFragBuffered,this),e.on(N.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(N.LEVEL_LOADED,this.onLevelLoaded,this),e.off(N.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(N.FRAG_BUFFERED,this.onFragBuffered,this),e.off(N.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,n=[],r={},o={};let u=!1,c=!1,d=!1;t.levels.forEach(f=>{const m=f.attrs;let{audioCodec:g,videoCodec:v}=f;g&&(f.audioCodec=g=Zp(g,i)||void 0),v&&(v=f.videoCodec=iF(v));const{width:b,height:_,unknownCodecs:E}=f,L=E?.length||0;if(u||(u=!!(b&&_)),c||(c=!!v),d||(d=!!g),L||g&&!this.isAudioSupported(g)||v&&!this.isVideoSupported(v)){this.log(`Some or all CODECS not supported "${m.CODECS}"`);return}const{CODECS:I,"FRAME-RATE":w,"HDCP-LEVEL":F,"PATHWAY-ID":U,RESOLUTION:V,"VIDEO-RANGE":B}=m,k=`${`${U||"."}-`}${f.bitrate}-${V}-${w}-${I}-${B}-${F}`;if(r[k])if(r[k].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const R=o[k]+=1;f.attrs["PATHWAY-ID"]=new Array(R+1).join(".");const K=this.createLevel(f);r[k]=K,n.push(K)}else r[k].addGroupId("audio",m.AUDIO),r[k].addGroupId("text",m.SUBTITLES);else{const R=this.createLevel(f);r[k]=R,o[k]=1,n.push(R)}}),this.filterAndSortMediaOptions(n,t,u,c,d)}createLevel(e){const t=new Zd(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(n.message),t.supportedResult=kw(n,[])}return t}isAudioSupported(e){return Xd(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Xd(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var o;let u=[],c=[],d=e;const f=((o=t.stats)==null?void 0:o.parsing)||{};if((i||n)&&r&&(d=d.filter(({videoCodec:I,videoRange:w,width:F,height:U})=>(!!I||!!(F&&U))&&hF(w))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let I="no level with compatible codecs found in manifest",w=I;t.levels.length&&(w=`one or more CODECS in variant not supported: ${ui(t.levels.map(U=>U.attrs.CODECS).filter((U,V,B)=>B.indexOf(U)===V))}`,this.warn(w),I+=` (${w})`);const F=new Error(I);this.hls.trigger(N.ERROR,{type:ot.MEDIA_ERROR,details:ve.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:F,reason:w})}}),f.end=performance.now();return}t.audioTracks&&(u=t.audioTracks.filter(I=>!I.audioCodec||this.isAudioSupported(I.audioCodec)),F2(u)),t.subtitles&&(c=t.subtitles,F2(c));const m=d.slice(0);d.sort((I,w)=>{if(I.attrs["HDCP-LEVEL"]!==w.attrs["HDCP-LEVEL"])return(I.attrs["HDCP-LEVEL"]||"")>(w.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&I.height!==w.height)return I.height-w.height;if(I.frameRate!==w.frameRate)return I.frameRate-w.frameRate;if(I.videoRange!==w.videoRange)return Jp.indexOf(I.videoRange)-Jp.indexOf(w.videoRange);if(I.videoCodec!==w.videoCodec){const F=L1(I.videoCodec),U=L1(w.videoCodec);if(F!==U)return U-F}if(I.uri===w.uri&&I.codecSet!==w.codecSet){const F=Qp(I.codecSet),U=Qp(w.codecSet);if(F!==U)return U-F}return I.averageBitrate!==w.averageBitrate?I.averageBitrate-w.averageBitrate:0});let g=m[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==m.length)){for(let I=0;IF&&F===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=U)}break}const b=r&&!n,_=this.hls.config,E=!!(_.audioStreamController&&_.audioTrackController),L={levels:d,audioTracks:u,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:n,altAudio:E&&!b&&u.some(I=>!!I.url)};f.end=performance.now(),this.hls.trigger(N.MANIFEST_PARSED,L)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const f=new Error("invalid level idx"),m=e<0;if(this.hls.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.LEVEL_SWITCH_ERROR,level:e,fatal:m,error:f,reason:f.message}),m)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],u=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,i===e&&n&&r===u)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${u?" with Pathway "+u:""} from level ${i}${r?" with Pathway "+r:""}`);const c={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(N.LEVEL_SWITCHING,c);const d=o.details;if(!d||d.live){const f=this.switchParams(o.uri,n?.details,d);this.loadPlaylist(f)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===Rt.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===it.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var i;const{level:n,details:r}=t,o=t.levelInfo;if(!o){var u;this.warn(`Invalid level index ${n}`),(u=t.deliveryDirectives)!=null&&u.skip&&(r.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let c=o.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(n,t,c)}else(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],o=e.details,u=o?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${u&&o.live?" age "+u.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger(N.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const i=this._levels.filter((r,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(u=>u.level=-1)),!1));Zw(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(N.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(N.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function F2(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function KL(){return self.SourceBuffer||self.WebKitSourceBuffer}function YL(){if(!Eo())return!1;const e=KL();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function _$(){if(!YL())return!1;const s=Eo();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Qd(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Qd(e,"audio"))))}function x$(){var s;const e=KL();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const S$=100;class E$ extends lb{constructor(e,t,i){super(e,t,i,"stream-controller",it.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,r=n?n.currentTime:null;if(r===null||!Qe(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const o=this.getFwdBufferInfoAtPos(n,r,it.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(N.MANIFEST_PARSED,this.onManifestParsed,this),e.on(N.LEVEL_LOADING,this.onLevelLoading,this),e.on(N.LEVEL_LOADED,this.onLevelLoaded,this),e.on(N.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(N.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(N.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(N.BUFFER_CREATED,this.onBufferCreated,this),e.on(N.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(N.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(N.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(N.MANIFEST_PARSED,this.onManifestParsed,this),e.off(N.LEVEL_LOADED,this.onLevelLoaded,this),e.off(N.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(N.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(N.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(N.BUFFER_CREATED,this.onBufferCreated,this),e.off(N.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(N.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(N.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:n}=this;if(this.stopLoad(),this.setInterval(S$),this.level=-1,!this.startFragRequested){let r=n.startLevel;r===-1&&(n.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=n.firstAutoLevel),n.nextLoadLevel=r,this.level=n.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=Pe.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Pe.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Pe.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e?.[t],n=i?.details;if(n&&(!n.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(n))break;this.state=Pe.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Pe.IDLE;break}break}case Pe.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Pe.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const o=i[r],u=this.getMainFwdBufferInfo();if(u===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(u,c)){const _={};this.altAudio===2&&(_.type="video"),this.hls.trigger(N.BUFFER_EOS,_),this.state=Pe.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const d=o.details;if(!d||this.state===Pe.WAITING_LEVEL||this.waitForLive(o)){this.level=r,this.state=Pe.WAITING_LEVEL,this.startFragRequested=!1;return}const f=u.len,m=this.getMaxBufferLength(o.maxBitrate);if(f>=m)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const g=this.backtrackFragment?this.backtrackFragment.start:u.end;let v=this.getNextFragment(g,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&Ui(v)&&this.fragmentTracker.getState(v)!==Ji.OK){var b;const E=((b=this.backtrackFragment)!=null?b:v).sn-d.startSN,L=d.fragments[E-1];L&&v.cc===L.cc&&(v=L,this.fragmentTracker.removeFragment(L))}else this.backtrackFragment&&u.len&&(this.backtrackFragment=null);if(v&&this.isLoopLoading(v,g)){if(!v.gap){const E=this.audioOnly&&!this.altAudio?oi.AUDIO:oi.VIDEO,L=(E===oi.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;L&&this.afterBufferFlushed(L,E,it.MAIN)}v=this.getNextFragmentLoopLoading(v,d,u,it.MAIN,m)}v&&(v.initSegment&&!v.initSegment.data&&!this.bitrateTest&&(v=v.initSegment),this.loadFragment(v,o,g))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===Ji.NOT_LOADED||n===Ji.PARTIAL?Ui(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,it.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const u=this.getMainFwdBufferInfo();if(!u||u.len=o-t.maxFragLookUpTolerance&&r<=u;if(n!==null&&i.duration>n&&(r{this.hls&&this.hls.trigger(N.AUDIO_TRACK_SWITCHED,t)}),i.trigger(N.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(N.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=em(t.url,this.hls);if(i){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let n,r,o=!1;for(const u in i){const c=i[u];if(c.id==="main"){if(r=u,n=c,u==="video"){const d=i[u];d&&(this.videoBuffer=d.buffer)}}else o=!0}o&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:n}=t,r=i.type===it.MAIN;if(r){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Pe.PARSED&&(this.state=Pe.IDLE);return}const u=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*u.total/(u.buffering.end-u.loading.first)),Ui(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const o=this.media;o&&(!this._hasEnoughToStart&&_t.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=Pe.ERROR;return}switch(t.details){case ve.FRAG_GAP:case ve.FRAG_PARSING_ERROR:case ve.FRAG_DECRYPT_ERROR:case ve.FRAG_LOAD_ERROR:case ve.FRAG_LOAD_TIMEOUT:case ve.KEY_LOAD_ERROR:case ve.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(it.MAIN,t);break;case ve.LEVEL_LOAD_ERROR:case ve.LEVEL_LOAD_TIMEOUT:case ve.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Pe.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Rt.LEVEL&&(this.state=Pe.IDLE);break;case ve.BUFFER_ADD_CODEC_ERROR:case ve.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ve.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case ve.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Pe.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==oi.AUDIO||!this.altAudio){const i=(t===oi.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,it.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(c{const{hls:n}=this,r=i?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=Pe.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=r.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),n.trigger(N.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===Pe.STOPPED||this.state===Pe.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,o=this.getCurrentContext(r);if(!o){this.resetWhenMissingContext(r);return}const{frag:u,part:c,level:d}=o,{video:f,text:m,id3:g,initSegment:v}=n,{details:b}=d,_=this.altAudio?void 0:n.audio;if(this.fragContextChanged(u)){this.fragmentTracker.removeFragment(u);return}if(this.state=Pe.PARSING,v){const E=v.tracks;if(E){const F=u.initSegment||u;if(this.unhandledEncryptionError(v,u))return;this._bufferInitSegment(d,E,F,r),i.trigger(N.FRAG_PARSING_INIT_SEGMENT,{frag:F,id:t,tracks:E})}const L=v.initPTS,I=v.timescale,w=this.initPTS[u.cc];if(Qe(L)&&(!w||w.baseTime!==L||w.timescale!==I)){const F=v.trackId;this.initPTS[u.cc]={baseTime:L,timescale:I,trackId:F},i.trigger(N.INIT_PTS_FOUND,{frag:u,id:t,initPTS:L,timescale:I,trackId:F})}}if(f&&b){_&&f.type==="audiovideo"&&this.logMuxedErr(u);const E=b.fragments[u.sn-1-b.startSN],L=u.sn===b.startSN,I=!E||u.cc>E.cc;if(n.independent!==!1){const{startPTS:w,endPTS:F,startDTS:U,endDTS:V}=f;if(c)c.elementaryStreams[f.type]={startPTS:w,endPTS:F,startDTS:U,endDTS:V};else if(f.firstKeyFrame&&f.independent&&r.id===1&&!I&&(this.couldBacktrack=!0),f.dropped&&f.independent){const B=this.getMainFwdBufferInfo(),q=(B?B.end:this.getLoadPosition())+this.config.maxBufferHole,k=f.firstKeyFramePTS?f.firstKeyFramePTS:w;if(!L&&qCp&&(u.gap=!0);u.setElementaryStreamInfo(f.type,w,F,U,V),this.backtrackFragment&&(this.backtrackFragment=u),this.bufferFragmentData(f,u,c,r,L||I)}else if(L||I)u.gap=!0;else{this.backtrack(u);return}}if(_){const{startPTS:E,endPTS:L,startDTS:I,endDTS:w}=_;c&&(c.elementaryStreams[oi.AUDIO]={startPTS:E,endPTS:L,startDTS:I,endDTS:w}),u.setElementaryStreamInfo(oi.AUDIO,E,L,I,w),this.bufferFragmentData(_,u,c,r)}if(b&&g!=null&&g.samples.length){const E={id:t,frag:u,details:b,samples:g.samples};i.trigger(N.FRAG_PARSING_METADATA,E)}if(b&&m){const E={id:t,frag:u,details:b,samples:m.samples};i.trigger(N.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${Ui(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==Pe.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:o,audiovideo:u}=t;if(r){const d=e.audioCodec;let f=Tp(r.codec,d);f==="mp4a"&&(f="mp4a.40.5");const m=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){f&&(f.indexOf("mp4a.40.5")!==-1?f="mp4a.40.2":f="mp4a.40.5");const g=r.metadata;g&&"channelCount"in g&&(g.channelCount||1)!==1&&m.indexOf("firefox")===-1&&(f="mp4a.40.5")}f&&f.indexOf("mp4a.40.5")!==-1&&m.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(f="mp4a.40.2",this.log(`Android: force audio codec to ${f}`)),d&&d!==f&&this.log(`Swapping manifest audio codec "${d}" for "${f}"`),r.levelCodec=f,r.id=it.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${f||""}/${d||""}/${r.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=it.MAIN;const d=o.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${o.codec!==d?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo}u&&(this.log(`Init audiovideo buffer, container:${u.container}, codecs[level/parsed]=[${e.codecs}/${u.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(N.BUFFER_CODECS,t),!this.hls)return;c.forEach(d=>{const m=t[d].initSegment;m!=null&&m.byteLength&&this.hls.trigger(N.BUFFER_APPENDING,{type:d,data:m,frag:i,part:null,chunkMeta:n,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,it.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Pe.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(_t.isBuffered(e,i)?t=this.getAppendedFrag(i):_t.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,r=t.level;(!n||t.sn!==n.sn||n.level!==r)&&(this.fragPlaying=t,this.hls.trigger(N.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(N.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return Qe(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Qe(t)){const i=this.getLevelDetails(),n=this.currentFrag||(i?Cl(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const o=r+(t-n.start)*1e3;return new Date(o)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class A$ extends jn{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[i].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=ve.KEY_LOAD_ERROR,i,n,r){return new ha({type:ot.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:n})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,r=t.length;n{if(!this.emeController)return;o.setKeyFormat(u);const c=_p(u);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const n=kd(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,n;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,ve.KEY_LOAD_ERROR,d))}const o=r.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,ve.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));const u=iv(r);let c=this.keyIdToKeyInfo[u];if((i=c)!=null&&i.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(n=c)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(f=>{const{keyInfo:m}=f;return r.key=m.decryptdata.key,{frag:e,keyInfo:m}})}switch(this.log(`${this.keyIdToKeyInfo[u]?"Rel":"L"}oading${r.keyId?" keyId: "+Ts(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[u]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,ve.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const o=VB(t.initSegment.data);if(o.length){let u=o[0];u.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Ts(u)}`),_o.setKeyIdForUri(e.decryptdata.uri,u)):(u=_o.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Ts(u)}`)),e.decryptdata.keyId=u}}if(!e.decryptdata.keyId&&!Ui(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(o=>(e.mediaKeySessionContext=o,i))).catch(o=>{throw e.keyLoadPromise=null,"data"in o&&(o.data.frag=t),o})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,n=i.loader,r=new n(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((o,u)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(g,v,b,_)=>{const{frag:E,keyInfo:L}=b,I=iv(L.decryptdata);if(!E.decryptdata||L!==this.keyIdToKeyInfo[I])return u(this.createKeyLoadError(E,ve.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));L.decryptdata.key=E.decryptdata.key=new Uint8Array(g.data),E.keyLoader=null,L.loader=null,o({frag:E,keyInfo:L})},onError:(g,v,b,_)=>{this.resetLoader(v),u(this.createKeyLoadError(t,ve.KEY_LOAD_ERROR,new Error(`HTTP Error ${g.code} loading key ${g.text}`),b,Qt({url:c.url,data:void 0},g)))},onTimeout:(g,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,ve.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),b))},onAbort:(g,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,ve.INTERNAL_ABORTED,new Error("key loading aborted"),b))}};r.load(c,f,m)})}resetLoader(e){const{frag:t,keyInfo:i,url:n}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const o=iv(i.decryptdata)||n;delete this.keyIdToKeyInfo[o],r&&r.destroy()}}function iv(s){if(s.keyFormat!==bs.FAIRPLAY){const e=s.keyId;if(e)return Ts(e)}return s.uri}function U2(s){const{type:e}=s;switch(e){case Rt.AUDIO_TRACK:return it.AUDIO;case Rt.SUBTITLE_TRACK:return it.SUBTITLE;default:return it.MAIN}}function sv(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class C${constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(N.MANIFEST_LOADING,this.onManifestLoading,this),e.on(N.LEVEL_LOADING,this.onLevelLoading,this),e.on(N.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(N.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(N.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(N.MANIFEST_LOADING,this.onManifestLoading,this),e.off(N.LEVEL_LOADING,this.onLevelLoading,this),e.off(N.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(N.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(N.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,o=new r(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Rt.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:o,deliveryDirectives:u,levelInfo:c}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:Rt.LEVEL,url:o,deliveryDirectives:u,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Rt.AUDIO_TRACK,url:r,deliveryDirectives:o,levelOrTrack:u})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Rt.SUBTITLE_TRACK,url:r,deliveryDirectives:o,levelOrTrack:u})}onLevelsUpdated(e,t){const i=this.loaders[Rt.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[Rt.LEVEL])}}load(e){var t;const i=this.hls.config;let n=this.getInternalLoader(e);if(n){const d=this.hls.logger,f=n.context;if(f&&f.levelOrTrack===e.levelOrTrack&&(f.url===e.url||f.deliveryDirectives&&!e.deliveryDirectives)){f.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${f.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(e.type===Rt.MANIFEST?r=i.manifestLoadPolicy.default:r=ni({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),Qe((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Rt.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Rt.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Rt.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const f=d.partTarget,m=d.targetduration;if(f&&m){const g=Math.max(f*3,m*.8)*1e3;r=ni({},r,{maxTimeToFirstByteMs:Math.min(g,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(g,r.maxTimeToFirstByteMs)})}}}const o=r.errorRetry||r.timeoutRetry||{},u={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(d,f,m,g)=>{const v=this.getInternalLoader(m);this.resetInternalLoader(m.type);const b=d.data;f.parsing.start=performance.now(),Or.isMediaPlaylist(b)||m.type!==Rt.MANIFEST?this.handleTrackOrLevelPlaylist(d,f,m,g||null,v):this.handleMasterPlaylist(d,f,m,g)},onError:(d,f,m,g)=>{this.handleNetworkError(f,m,!1,d,g)},onTimeout:(d,f,m)=>{this.handleNetworkError(f,m,!0,void 0,d)}};n.load(e,u,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,n){const r=this.hls,o=e.data,u=sv(e,i),c=Or.parseMasterPlaylist(o,u);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,c.playlistParsingError,n,t);return}const{contentSteering:d,levels:f,sessionData:m,sessionKeys:g,startTimeOffset:v,variableList:b}=c;this.variableList=b,f.forEach(I=>{const{unknownCodecs:w}=I;if(w){const{preferManagedMediaSource:F}=this.hls.config;let{audioCodec:U,videoCodec:V}=I;for(let B=w.length;B--;){const q=w[B];Xd(q,"audio",F)?(I.audioCodec=U=U?`${U},${q}`:q,rc.audio[U.substring(0,4)]=2,w.splice(B,1)):Xd(q,"video",F)&&(I.videoCodec=V=V?`${V},${q}`:q,rc.video[V.substring(0,4)]=2,w.splice(B,1))}}});const{AUDIO:_=[],SUBTITLES:E,"CLOSED-CAPTIONS":L}=Or.parseMasterPlaylistMedia(o,u,c);_.length&&!_.some(w=>!w.url)&&f[0].audioCodec&&!f[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),_.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new _i({}),bitrate:0,url:""})),r.trigger(N.MANIFEST_LOADED,{levels:f,audioTracks:_,subtitles:E,captions:L,contentSteering:d,url:u,stats:t,networkDetails:n,sessionData:m,sessionKeys:g,startTimeOffset:v,variableList:b})}handleTrackOrLevelPlaylist(e,t,i,n,r){const o=this.hls,{id:u,level:c,type:d}=i,f=sv(e,i),m=Qe(c)?c:Qe(u)?u:0,g=U2(i),v=Or.parseLevelPlaylist(e.data,f,m,g,0,this.variableList);if(d===Rt.MANIFEST){const b={attrs:new _i({}),bitrate:0,details:v,name:"",url:f};v.requestScheduled=t.loading.start+Ww(v,0),o.trigger(N.MANIFEST_LOADED,{levels:[b],audioTracks:[],url:f,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=v,this.handlePlaylistLoaded(v,e,t,i,n,r)}handleManifestParsingError(e,t,i,n,r){this.hls.trigger(N.ERROR,{type:ot.NETWORK_ERROR,details:ve.MANIFEST_PARSING_ERROR,fatal:t.type===Rt.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:n,stats:r})}handleNetworkError(e,t,i=!1,n,r){let o=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Rt.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===Rt.AUDIO_TRACK||e.type===Rt.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const u=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let c=ve.UNKNOWN,d=!1;const f=this.getInternalLoader(e);switch(e.type){case Rt.MANIFEST:c=i?ve.MANIFEST_LOAD_TIMEOUT:ve.MANIFEST_LOAD_ERROR,d=!0;break;case Rt.LEVEL:c=i?ve.LEVEL_LOAD_TIMEOUT:ve.LEVEL_LOAD_ERROR,d=!1;break;case Rt.AUDIO_TRACK:c=i?ve.AUDIO_TRACK_LOAD_TIMEOUT:ve.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Rt.SUBTITLE_TRACK:c=i?ve.SUBTITLE_TRACK_LOAD_TIMEOUT:ve.SUBTITLE_LOAD_ERROR,d=!1;break}f&&this.resetInternalLoader(e.type);const m={type:ot.NETWORK_ERROR,details:c,fatal:d,url:e.url,loader:f,context:e,error:u,networkDetails:t,stats:r};if(n){const g=t?.url||e.url;m.response=Qt({url:g,data:void 0},n)}this.hls.trigger(N.ERROR,m)}handlePlaylistLoaded(e,t,i,n,r,o){const u=this.hls,{type:c,level:d,levelOrTrack:f,id:m,groupId:g,deliveryDirectives:v}=n,b=sv(t,n),_=U2(n);let E=typeof n.level=="number"&&_===it.MAIN?d:void 0;const L=e.playlistParsingError;if(L){if(this.hls.logger.warn(`${L} ${e.url}`),!u.config.ignorePlaylistParsingErrors){u.trigger(N.ERROR,{type:ot.NETWORK_ERROR,details:ve.LEVEL_PARSING_ERROR,fatal:!1,url:b,error:L,reason:L.message,response:t,context:n,level:E,parent:_,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const I=e.playlistParsingError=new Error("No Segments found in Playlist");u.trigger(N.ERROR,{type:ot.NETWORK_ERROR,details:ve.LEVEL_EMPTY_ERROR,fatal:!1,url:b,error:I,reason:I.message,response:t,context:n,level:E,parent:_,networkDetails:r,stats:i});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Rt.MANIFEST:case Rt.LEVEL:if(E){if(!f)E=0;else if(f!==u.levels[E]){const I=u.levels.indexOf(f);I>-1&&(E=I)}}u.trigger(N.LEVEL_LOADED,{details:e,levelInfo:f||u.levels[0],level:E||0,id:m||0,stats:i,networkDetails:r,deliveryDirectives:v,withoutMultiVariant:c===Rt.MANIFEST});break;case Rt.AUDIO_TRACK:u.trigger(N.AUDIO_TRACK_LOADED,{details:e,track:f,id:m||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:v});break;case Rt.SUBTITLE_TRACK:u.trigger(N.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:m||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:v});break}}}class Jn{static get version(){return Jd}static isMSESupported(){return YL()}static isSupported(){return _$()}static getMediaSource(){return Eo()}static get Events(){return N}static get MetadataSchema(){return xn}static get ErrorTypes(){return ot}static get ErrorDetails(){return ve}static get DefaultConfig(){return Jn.defaultConfig?Jn.defaultConfig:u$}static set DefaultConfig(e){Jn.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ub,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=RB(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=d$(Jn.DefaultConfig,e,t);this.userConfig=e,i.progressive&&h$(i,t);const{abrController:n,bufferController:r,capLevelController:o,errorController:u,fpsController:c}=i,d=new u(this),f=this.abrController=new n(this),m=new DF(this),g=i.interstitialsController,v=g?this.interstitialsController=new g(this,Jn):null,b=this.bufferController=new r(this,m),_=this.capLevelController=new o(this),E=new c(this),L=new C$(this),I=i.contentSteeringController,w=I?new I(this):null,F=this.levelController=new b$(this,w),U=new v$(this),V=new A$(this.config,this.logger),B=this.streamController=new E$(this,m,V),q=this.gapController=new g$(this,m);_.setStreamController(B),E.setStreamController(B);const k=[L,F,B];v&&k.splice(1,0,v),w&&k.splice(1,0,w),this.networkControllers=k;const R=[f,b,q,_,E,U,m];this.audioTrackController=this.createController(i.audioTrackController,k);const K=i.audioStreamController;K&&k.push(this.audioStreamController=new K(this,m,V)),this.subtitleTrackController=this.createController(i.subtitleTrackController,k);const X=i.subtitleStreamController;X&&k.push(this.subtititleStreamController=new X(this,m,V)),this.createController(i.timelineController,R),V.emeController=this.emeController=this.createController(i.emeController,R),this.cmcdController=this.createController(i.cmcdController,R),this.latencyController=this.createController(T$,R),this.coreComponents=R,k.push(d);const ee=d.onErrorOut;typeof ee=="function"&&this.on(N.ERROR,ee,d),this.on(N.MANIFEST_LOADED,L.onManifestLoaded,L)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,n){this._emitter.off(e,t,i,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const n=e===N.ERROR;this.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.INTERNAL_EXCEPTION,fatal:n,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(N.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(N.ERROR,{type:ot.OTHER_ERROR,details:ve.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,n=t?e:{media:i};this._media=i,this.trigger(N.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(N.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(N.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=ZT.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&i&&(i!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(N.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", ":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[it.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[it.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[it.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=g6()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){dF(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let n=0;n=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,i)for(let r=n;r--;){const o=e[r].attrs["HDCP-LEVEL"];if(o&&o<=i)return r}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=Pw(t);return Rw(e,i,navigator.mediaCapabilities)}}Jn.defaultConfig=void 0;function D$({src:s,muted:e,className:t}){const i=j.useRef(null),[n,r]=j.useState(!1);return j.useEffect(()=>{let o=!1,u=null;const c=i.current;if(!c)return;r(!1),c.muted=e;async function d(){const m=Date.now();for(;!o&&Date.now()-m<2e4;){try{const g=await fetch(s,{cache:"no-store"});if(g.status!==204){if(g.ok)return!0}}catch{}await new Promise(g=>setTimeout(g,400))}return!1}async function f(m){if(!await d()||o){o||r(!0);return}if(m.canPlayType("application/vnd.apple.mpegurl")){m.src=s,m.play().catch(()=>{});return}if(!Jn.isSupported()){r(!0);return}u=new Jn({lowLatencyMode:!0,liveSyncDurationCount:2,maxBufferLength:4}),u.on(Jn.Events.ERROR,(v,b)=>{b.fatal&&r(!0)}),u.loadSource(s),u.attachMedia(m),u.on(Jn.Events.MANIFEST_PARSED,()=>{m.play().catch(()=>{})})}return f(c),()=>{o=!0,u?.destroy()}},[s,e]),n?O.jsx("div",{className:"text-xs text-gray-400 italic",children:"–"}):O.jsx("video",{ref:i,className:t,playsInline:!0,autoPlay:!0,muted:e,onClick:()=>{const o=i.current;o&&(o.muted=!1,o.play().catch(()=>{}))}})}function $2({jobId:s,thumbTick:e,autoTickMs:t=3e4,blur:i=!1}){const n=i?"blur-md":"",[r,o]=j.useState(0),[u,c]=j.useState(!1),d=j.useRef(null),[f,m]=j.useState(!1);j.useEffect(()=>{if(typeof e=="number"||!f||document.hidden)return;const _=window.setInterval(()=>{o(E=>E+1)},t);return()=>window.clearInterval(_)},[e,t,f]),j.useEffect(()=>{const _=d.current;if(!_)return;const E=new IntersectionObserver(L=>{const I=L[0];m(!!I?.isIntersecting)},{root:null,threshold:.1});return E.observe(_),()=>E.disconnect()},[]);const g=typeof e=="number"?e:r;j.useEffect(()=>{c(!1)},[g]);const v=j.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&v=${g}`,[s,g]),b=j.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&file=index_hq.m3u8`,[s]);return O.jsx(AA,{content:(_,{close:E})=>_&&O.jsx("div",{className:"w-[420px] max-w-[calc(100vw-1.5rem)]",children:O.jsxs("div",{className:"relative aspect-video overflow-hidden rounded-lg bg-black",children:[O.jsx(D$,{src:b,muted:!1,className:["w-full h-full relative z-0",n].filter(Boolean).join(" ")}),O.jsxs("div",{className:"absolute left-2 top-2 inline-flex items-center gap-1.5 rounded-full bg-red-600/90 px-2 py-1 text-[11px] font-semibold text-white shadow-sm",children:[O.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]}),O.jsx("button",{type:"button",className:"absolute right-2 top-2 z-20 inline-flex items-center justify-center rounded-md bg-black/45 p-1.5 text-white hover:bg-black/65 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white/70","aria-label":"Live-Vorschau schließen",title:"Vorschau schließen",onClick:L=>{L.preventDefault(),L.stopPropagation(),E()},children:O.jsx(LA,{className:"h-4 w-4"})})]})}),children:O.jsx("div",{ref:d,className:"w-20 h-16 rounded bg-gray-100 dark:bg-white/5 overflow-hidden flex items-center justify-center",children:u?O.jsx("div",{className:"text-[10px] text-gray-500 dark:text-gray-400 px-1 text-center",children:"keine Vorschau"}):O.jsx("img",{src:v,loading:"lazy",alt:"",className:["w-full h-full object-cover",n].filter(Boolean).join(" "),onError:()=>c(!0),onLoad:()=>c(!1)})})})}function w$({models:s}){const e=j.useMemo(()=>[{key:"model",header:"Model",cell:t=>O.jsx("span",{className:"truncate font-medium text-gray-900 dark:text-white",title:t.modelKey,children:t.modelKey})},{key:"status",header:"Status",cell:t=>O.jsx("span",{className:"font-medium",children:t.currentShow||"unknown"})},{key:"open",header:"Öffnen",srOnlyHeader:!0,align:"right",cell:t=>O.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"text-indigo-600 dark:text-indigo-400 hover:underline",onClick:i=>i.stopPropagation(),children:"Öffnen"})}],[]);return s.length===0?null:O.jsxs(O.Fragment,{children:[O.jsx("div",{className:"sm:hidden space-y-2",children:s.map(t=>O.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md bg-white/60 dark:bg-white/5 px-3 py-2",children:[O.jsxs("div",{className:"min-w-0",children:[O.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:t.modelKey}),O.jsxs("div",{className:"truncate text-xs text-gray-600 dark:text-gray-300",children:["Status: ",O.jsx("span",{className:"font-medium",children:t.currentShow||"unknown"})]})]}),O.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-xs text-indigo-600 dark:text-indigo-400 hover:underline",children:"Öffnen"})]},t.id))}),O.jsx("div",{className:"hidden sm:block",children:O.jsx(vm,{rows:s,columns:e,getRowKey:t=>t.id,striped:!0,fullWidth:!0})})]})}const oT=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",j2=s=>{const e=oT(s||"");if(!e)return"—";const t=e.replace(/\.[^.]+$/,""),i=t.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/);if(i?.[1])return i[1];const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t},L$=s=>{if(!Number.isFinite(s)||s<=0)return"—";const e=Math.floor(s/1e3),t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=e%60;return t>0?`${t}h ${i}m`:i>0?`${i}m ${n}s`:`${n}s`},H2=s=>{const e=Date.parse(String(s.startedAt||""));if(!Number.isFinite(e))return"—";const t=s.endedAt?Date.parse(String(s.endedAt)):Date.now();return Number.isFinite(t)?L$(t-e):"—"};function I$({jobs:s,pending:e=[],onOpenPlayer:t,onStopJob:i,blurPreviews:n}){const r=j.useMemo(()=>[{key:"preview",header:"Vorschau",cell:o=>O.jsx($2,{jobId:o.id,blur:n})},{key:"model",header:"Modelname",cell:o=>{const u=j2(o.output);return O.jsx("span",{className:"truncate",title:u,children:u})}},{key:"sourceUrl",header:"Source",cell:o=>O.jsx("a",{href:o.sourceUrl,target:"_blank",rel:"noreferrer",className:"text-indigo-600 dark:text-indigo-400 hover:underline",onClick:u=>u.stopPropagation(),children:o.sourceUrl})},{key:"output",header:"Datei",cell:o=>oT(o.output||"")},{key:"status",header:"Status"},{key:"runtime",header:"Dauer",cell:o=>H2(o)},{key:"actions",header:"Aktion",srOnlyHeader:!0,align:"right",cell:o=>O.jsx(es,{size:"md",variant:"primary",onClick:u=>{u.stopPropagation(),i(o.id)},children:"Stop"})}],[i]);return s.length===0&&e.length===0?O.jsx(Pn,{grayBody:!0,children:O.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine laufenden Downloads."})}):O.jsxs(O.Fragment,{children:[e.length>0&&O.jsx(Pn,{grayBody:!0,header:O.jsxs("div",{className:"flex items-center justify-between gap-3",children:[O.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Online (wartend – Download startet nur bei ",O.jsx("span",{className:"font-semibold",children:"public"}),")"]}),O.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:e.length})]}),children:O.jsx(w$,{models:e})}),s.length===0&&e.length>0&&O.jsx(Pn,{grayBody:!0,children:O.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Kein aktiver Download – wartet auf public."})}),s.length>0&&O.jsxs(O.Fragment,{children:[O.jsx("div",{className:"sm:hidden space-y-3",children:s.map(o=>{const u=j2(o.output),c=oT(o.output||""),d=H2(o);return O.jsx("div",{role:"button",tabIndex:0,className:"cursor-pointer",onClick:()=>t(o),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&t(o)},children:O.jsx(Pn,{header:O.jsxs("div",{className:"flex items-start justify-between gap-3",children:[O.jsxs("div",{className:"min-w-0",children:[O.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:u}),O.jsx("div",{className:"truncate text-xs text-gray-600 dark:text-gray-300",children:c||"—"})]}),O.jsx(es,{size:"sm",variant:"primary",onClick:f=>{f.stopPropagation(),i(o.id)},children:"Stop"})]}),children:O.jsxs("div",{className:"flex gap-3",children:[O.jsx("div",{className:"shrink-0",onClick:f=>f.stopPropagation(),children:O.jsx($2,{jobId:o.id,blur:n})}),O.jsxs("div",{className:"min-w-0 flex-1",children:[O.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Status: ",O.jsx("span",{className:"font-medium",children:o.status}),O.jsx("span",{className:"mx-2 opacity-60",children:"•"}),"Dauer: ",O.jsx("span",{className:"font-medium",children:d})]}),o.sourceUrl?O.jsx("a",{href:o.sourceUrl,target:"_blank",rel:"noreferrer",className:"mt-1 block truncate text-xs text-indigo-600 dark:text-indigo-400 hover:underline",onClick:f=>f.stopPropagation(),children:o.sourceUrl}):null]})]})})},o.id)})}),O.jsx("div",{className:"hidden sm:block",children:O.jsx(vm,{rows:s,columns:r,getRowKey:o=>o.id,striped:!0,fullWidth:!0,onRowClick:t})})]})]})}function k$({open:s,onClose:e,title:t,children:i,footer:n,icon:r}){return O.jsx(pp,{show:s,as:j.Fragment,children:O.jsxs(Nu,{as:"div",className:"relative z-50",onClose:e,children:[O.jsx(pp.Child,{as:j.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-200",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:O.jsx("div",{className:"fixed inset-0 bg-gray-500/75 dark:bg-gray-900/50"})}),O.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center px-4 py-6 sm:p-0",children:O.jsx(pp.Child,{as:j.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",enterTo:"opacity-100 translate-y-0 sm:scale-100",leave:"ease-in duration-200",leaveFrom:"opacity-100 translate-y-0 sm:scale-100",leaveTo:"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",children:O.jsxs(Nu.Panel,{className:"relative w-full max-w-lg transform overflow-hidden rounded-lg bg-white p-6 text-left shadow-xl transition-all dark:bg-gray-800 dark:outline dark:-outline-offset-1 dark:outline-white/10",children:[r&&O.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-500/10",children:r}),t&&O.jsx(Nu.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:t}),O.jsx("div",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:i}),n&&O.jsx("div",{className:"mt-6 flex justify-end gap-3",children:n})]})})})]})})}function G2(s,e,t){return Math.max(e,Math.min(t,s))}function nv(s,e){const t=[];for(let i=s;i<=e;i++)t.push(i);return t}function R$(s,e,t,i){if(s<=1)return[1];const n=1,r=s,o=nv(n,Math.min(t,r)),u=nv(Math.max(r-t+1,t+1),r),c=Math.max(Math.min(e-i,r-t-i*2-1),t+1),d=Math.min(Math.max(e+i,t+i*2+2),r-t),f=[];f.push(...o),c>t+1?f.push("ellipsis"):t+1t&&f.push(r-t),f.push(...u);const m=new Set;return f.filter(g=>{const v=String(g);return m.has(v)?!1:(m.add(v),!0)})}function O$({active:s,disabled:e,rounded:t,onClick:i,children:n,title:r}){const o=t==="l"?"rounded-l-md":t==="r"?"rounded-r-md":"";return O.jsx("button",{type:"button",disabled:e,onClick:e?void 0:i,title:r,className:Ht("relative inline-flex items-center px-4 py-2 text-sm font-semibold focus:z-20 focus:outline-offset-0",o,e?"opacity-50 cursor-not-allowed":"cursor-pointer",s?"z-10 bg-indigo-600 text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:focus-visible:outline-indigo-500":"text-gray-900 inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:text-gray-200 dark:inset-ring-gray-700 dark:hover:bg-white/5"),"aria-current":s?"page":void 0,children:n})}function P$({page:s,pageSize:e,totalItems:t,onPageChange:i,siblingCount:n=1,boundaryCount:r=1,showSummary:o=!0,className:u,ariaLabel:c="Pagination",prevLabel:d="Previous",nextLabel:f="Next"}){const m=Math.max(1,Math.ceil((t||0)/Math.max(1,e||1))),g=G2(s||1,1,m);if(m<=1)return null;const v=t===0?0:(g-1)*e+1,b=Math.min(g*e,t),_=R$(m,g,r,n),E=L=>i(G2(L,1,m));return O.jsxs("div",{className:Ht("flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6 dark:border-white/10 dark:bg-transparent",u),children:[O.jsxs("div",{className:"flex flex-1 justify-between sm:hidden",children:[O.jsx("button",{type:"button",onClick:()=>E(g-1),disabled:g<=1,className:"relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-white/10 dark:bg-white/5 dark:text-gray-200 dark:hover:bg-white/10",children:d}),O.jsx("button",{type:"button",onClick:()=>E(g+1),disabled:g>=m,className:"relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-white/10 dark:bg-white/5 dark:text-gray-200 dark:hover:bg-white/10",children:f})]}),O.jsxs("div",{className:"hidden sm:flex sm:flex-1 sm:items-center sm:justify-between",children:[O.jsx("div",{children:o?O.jsxs("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:["Showing ",O.jsx("span",{className:"font-medium",children:v})," to"," ",O.jsx("span",{className:"font-medium",children:b})," of"," ",O.jsx("span",{className:"font-medium",children:t})," results"]}):null}),O.jsx("div",{children:O.jsxs("nav",{"aria-label":c,className:"isolate inline-flex -space-x-px rounded-md shadow-xs dark:shadow-none",children:[O.jsxs("button",{type:"button",onClick:()=>E(g-1),disabled:g<=1,className:"relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 inset-ring inset-ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed dark:inset-ring-gray-700 dark:hover:bg-white/5",children:[O.jsx("span",{className:"sr-only",children:d}),O.jsx(UO,{"aria-hidden":"true",className:"size-5"})]}),_.map((L,I)=>L==="ellipsis"?O.jsx("span",{className:"relative inline-flex items-center px-4 py-2 text-sm font-semibold text-gray-700 inset-ring inset-ring-gray-300 dark:text-gray-400 dark:inset-ring-gray-700",children:"…"},`e-${I}`):O.jsx(O$,{active:L===g,onClick:()=>E(L),rounded:"none",children:L},L)),O.jsxs("button",{type:"button",onClick:()=>E(g+1),disabled:g>=m,className:"relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 inset-ring inset-ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed dark:inset-ring-gray-700 dark:hover:bg-white/5",children:[O.jsx("span",{className:"sr-only",children:f}),O.jsx(jO,{"aria-hidden":"true",className:"size-5"})]})]})})]})]})}async function hp(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}const V2=(s,e)=>O.jsx("span",{className:Ht("inline-flex items-center rounded-md px-2 py-0.5 text-xs","bg-indigo-50 text-indigo-700 dark:bg-indigo-500/10 dark:text-indigo-200"),children:e});function M$(s){let e=(s??"").trim();if(!e)return null;/^https?:\/\//i.test(e)||(e=`https://${e}`);try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function N$(s){if(!s)return[];const e=s.split(",").map(i=>i.trim()).filter(Boolean),t=Array.from(new Set(e));return t.sort((i,n)=>i.localeCompare(n,void 0,{sensitivity:"base"})),t}function q2({children:s,title:e}){return O.jsx("span",{title:e,className:"inline-flex max-w-[11rem] items-center truncate rounded-md bg-sky-50 px-2 py-0.5 text-xs text-sky-700 dark:bg-sky-500/10 dark:text-sky-200",children:s})}function z2({title:s,active:e,hiddenUntilHover:t,onClick:i,icon:n}){return O.jsx("span",{className:Ht(t&&!e?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:O.jsx(es,{variant:e?"soft":"secondary",size:"xs",className:Ht("px-2 py-1 leading-none",e?"":"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:s,onClick:i,children:O.jsx("span",{className:"text-base leading-none",children:n})})})}function B$(){const[s,e]=j.useState([]),[t,i]=j.useState(!1),[n,r]=j.useState(null),[o,u]=j.useState(""),[c,d]=j.useState(1),f=10,[m,g]=j.useState(""),[v,b]=j.useState(null),[_,E]=j.useState(null),[L,I]=j.useState(!1),[w,F]=j.useState(!1),[U,V]=j.useState(null),[B,q]=j.useState(null),[k,R]=j.useState("favorite"),[K,X]=j.useState(!1),[ee,le]=j.useState(null);async function ae(){if(U){X(!0),q(null),r(null);try{const Ee=new FormData;Ee.append("file",U),Ee.append("kind",k);const je=await fetch("/api/models/import",{method:"POST",body:Ee});if(!je.ok)throw new Error(await je.text());const Ve=await je.json();q(`✅ Import: ${Ve.inserted} neu, ${Ve.updated} aktualisiert, ${Ve.skipped} übersprungen`),F(!1),V(null),await Q()}catch(Ee){le(Ee?.message??String(Ee))}finally{X(!1)}}}const Y=()=>{le(null),q(null),V(null),R("favorite"),F(!0)},Q=j.useCallback(async()=>{i(!0),r(null);try{const Ee=await hp("/api/models/list");e(Array.isArray(Ee)?Ee:[])}catch(Ee){r(Ee?.message??String(Ee))}finally{i(!1)}},[]);j.useEffect(()=>{Q()},[Q]),j.useEffect(()=>{const Ee=()=>{Q()};return window.addEventListener("models-changed",Ee),()=>window.removeEventListener("models-changed",Ee)},[Q]),j.useEffect(()=>{const Ee=m.trim();if(!Ee){b(null),E(null);return}const je=M$(Ee);if(!je){b(null),E("Bitte nur gültige http(s) URLs einfügen (keine Modelnamen).");return}const Ve=window.setTimeout(async()=>{try{const tt=await hp("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:je})});if(!tt?.isUrl){b(null),E("Bitte nur URLs einfügen (keine Modelnamen).");return}b(tt),E(null)}catch(tt){b(null),E(tt?.message??String(tt))}},300);return()=>window.clearTimeout(Ve)},[m]);const te=j.useMemo(()=>s.map(Ee=>({m:Ee,hay:`${Ee.modelKey} ${Ee.host??""} ${Ee.input??""} ${Ee.tags??""}`.toLowerCase()})),[s]),oe=j.useDeferredValue(o),de=j.useMemo(()=>{const Ee=oe.trim().toLowerCase();return Ee?te.filter(je=>je.hay.includes(Ee)).map(je=>je.m):s},[s,te,oe]);j.useEffect(()=>{d(1)},[o]);const $=de.length,ie=j.useMemo(()=>Math.max(1,Math.ceil($/f)),[$,f]);j.useEffect(()=>{c>ie&&d(ie)},[c,ie]);const he=j.useMemo(()=>{const Ee=(c-1)*f;return de.slice(Ee,Ee+f)},[de,c,f]),Ce=async()=>{if(v){if(!v.isUrl){E("Bitte nur URLs einfügen (keine Modelnamen).");return}I(!0),r(null);try{const Ee=await hp("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});e(je=>{const Ve=je.filter(tt=>tt.id!==Ee.id);return[Ee,...Ve]}),g(""),b(null)}catch(Ee){r(Ee?.message??String(Ee))}finally{I(!1)}}},be=async(Ee,je)=>{r(null);try{const Ve=await hp("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:Ee,...je})});e(tt=>{const lt=tt.findIndex(Je=>Je.id===Ve.id);if(lt===-1)return tt;const Me=tt.slice();return Me[lt]=Ve,Me})}catch(Ve){r(Ve?.message??String(Ve))}},Ue=j.useMemo(()=>[{key:"statusAll",header:"Status",align:"center",cell:Ee=>{const je=Ee.liked===!0,Ve=Ee.favorite===!0,tt=Ee.watching===!0,lt=!tt&&!Ve&&!je;return O.jsxs("div",{className:"group flex items-center justify-center gap-1",children:[O.jsx("span",{className:Ht(lt&&!tt?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:O.jsx(es,{variant:tt?"soft":"secondary",size:"xs",className:Ht("px-2 py-1 leading-none",!tt&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:tt?"Nicht mehr beobachten":"Beobachten",onClick:Me=>{Me.stopPropagation(),be(Ee.id,{watching:!tt})},children:O.jsx("span",{className:Ht("text-base leading-none",tt?"text-indigo-600 dark:text-indigo-400":"text-gray-400 dark:text-gray-500"),children:"👁"})})}),O.jsx(z2,{title:Ve?"Favorit entfernen":"Als Favorit markieren",active:Ve,hiddenUntilHover:lt,onClick:Me=>{Me.stopPropagation(),Ve?be(Ee.id,{favorite:!1}):be(Ee.id,{favorite:!0,clearLiked:!0})},icon:O.jsx("span",{className:Ve?"text-amber-500":"text-gray-400 dark:text-gray-500",children:"★"})}),O.jsx(z2,{title:je?"Gefällt mir entfernen":"Gefällt mir",active:je,hiddenUntilHover:lt,onClick:Me=>{Me.stopPropagation(),je?be(Ee.id,{clearLiked:!0}):be(Ee.id,{liked:!0,favorite:!1})},icon:O.jsx("span",{className:je?"text-rose-500":"text-gray-400 dark:text-gray-500",children:"♥"})})]})}},{key:"model",header:"Model",cell:Ee=>O.jsxs("div",{className:"min-w-0",children:[O.jsx("div",{className:"font-medium truncate",children:Ee.modelKey}),O.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:Ee.host??"—"})]})},{key:"url",header:"URL",cell:Ee=>O.jsx("a",{href:Ee.input,target:"_blank",rel:"noreferrer",className:"text-indigo-600 dark:text-indigo-400 hover:underline truncate block max-w-[520px]",onClick:je=>je.stopPropagation(),title:Ee.input,children:Ee.input})},{key:"tags",header:"Tags",cell:Ee=>{const je=N$(Ee.tags),Ve=je.slice(0,6),tt=je.length-Ve.length,lt=je.join(", ");return O.jsxs("div",{className:"flex flex-wrap gap-2",title:lt||void 0,children:[Ee.hot?V2(!0,"🔥 HOT"):null,Ee.keep?V2(!0,"📌 Behalten"):null,Ve.map(Me=>O.jsx(q2,{title:Me,children:Me},Me)),tt>0?O.jsxs(q2,{title:lt,children:["+",tt]}):null,!Ee.hot&&!Ee.keep&&je.length===0?O.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"}):null]})}}],[]);return O.jsxs("div",{className:"space-y-4",children:[O.jsx(Pn,{header:O.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Model hinzufügen"}),grayBody:!0,children:O.jsxs("div",{className:"grid gap-2",children:[O.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[O.jsx("input",{value:m,onChange:Ee=>g(Ee.target.value),placeholder:"https://…",className:"flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),O.jsx(es,{className:"px-3 py-2 text-sm",onClick:Ce,disabled:!v||L,title:v?"In Models speichern":"Bitte gültige URL einfügen",children:"Hinzufügen"}),O.jsx(es,{className:"px-3 py-2 text-sm",onClick:Q,disabled:t,children:"Aktualisieren"})]}),_?O.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:_}):v?O.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Gefunden: ",O.jsx("span",{className:"font-medium",children:v.modelKey}),v.host?O.jsxs("span",{className:"opacity-70",children:[" • ",v.host]}):null]}):null,n?O.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:n}):null]})}),O.jsxs(Pn,{header:O.jsxs("div",{className:"flex items-center justify-between gap-2",children:[O.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Models (",de.length,")"]}),O.jsxs("div",{className:"flex items-center gap-2",children:[O.jsx(es,{variant:"secondary",size:"sm",onClick:Y,children:"Importieren"}),O.jsx("input",{value:o,onChange:Ee=>u(Ee.target.value),placeholder:"Suchen…",className:"w-[220px] rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"})]})]}),noBodyPadding:!0,children:[O.jsx(vm,{rows:he,columns:Ue,getRowKey:Ee=>Ee.id,striped:!0,compact:!0,fullWidth:!0,stickyHeader:!0,onRowClick:Ee=>Ee.input&&window.open(Ee.input,"_blank","noreferrer")}),O.jsx(P$,{page:c,pageSize:f,totalItems:$,onPageChange:d})]}),O.jsx(k$,{open:w,onClose:()=>!K&&F(!1),title:"Models importieren",footer:O.jsxs(O.Fragment,{children:[O.jsx(es,{variant:"secondary",onClick:()=>F(!1),disabled:K,children:"Abbrechen"}),O.jsx(es,{variant:"primary",onClick:ae,isLoading:K,disabled:!U||K,children:"Import starten"})]}),children:O.jsxs("div",{className:"space-y-3",children:[O.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Wähle eine CSV-Datei zum Import aus."}),O.jsxs("div",{className:"space-y-2",children:[O.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Import-Typ"}),O.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[O.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[O.jsx("input",{type:"radio",name:"import-kind",value:"favorite",checked:k==="favorite",onChange:()=>R("favorite"),disabled:K}),"Favoriten (★)"]}),O.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[O.jsx("input",{type:"radio",name:"import-kind",value:"liked",checked:k==="liked",onChange:()=>R("liked"),disabled:K}),"Gefällt mir (♥)"]})]})]}),O.jsx("input",{type:"file",accept:".csv,text/csv",onChange:Ee=>{const je=Ee.target.files?.[0]??null;le(null),V(je)},className:"block w-full text-sm text-gray-700 file:mr-4 file:rounded-md file:border-0 file:bg-gray-100 file:px-3 file:py-2 file:text-sm file:font-semibold file:text-gray-900 hover:file:bg-gray-200 dark:text-gray-200 dark:file:bg-white/10 dark:file:text-white dark:hover:file:bg-white/20"}),U?O.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Ausgewählt: ",O.jsx("span",{className:"font-medium",children:U.name})]}):null,ee?O.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:ee}):null,B?O.jsx("div",{className:"rounded-md bg-green-50 px-3 py-2 text-xs text-green-700 dark:bg-green-500/10 dark:text-green-200",children:B}):null]})})]})}const rv="record_cookies";function fp(s){return Object.fromEntries(Object.entries(s??{}).map(([t,i])=>[t.trim().toLowerCase(),String(i??"").trim()]).filter(([t,i])=>t.length>0&&i.length>0))}async function As(s,e){const t=await fetch(s,e);if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}const F$={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!1,autoStartAddedDownloads:!1,useChaturbateApi:!1,blurPreviews:!1};function K2(s){const e=(s??"").trim();if(!e)return null;for(const t of e.split(/\s+/g))if(/^https?:\/\//i.test(t))try{return new URL(t).toString()}catch{}return null}const Tn=s=>(s||"").replaceAll("\\","/").split("/").pop()||"";function av(s,e){const i=(s||"").replaceAll("\\","/").split("/");return i[i.length-1]=e,i.join("/")}function U$(s){return s.startsWith("HOT ")?s.slice(4):s}const $$=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function j$(s){const t=U$(Tn(s)).replace(/\.[^.]+$/,""),i=t.match($$);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function H$(){const[s,e]=j.useState(""),[,t]=j.useState(null),[,i]=j.useState(null),[n,r]=j.useState([]),[o,u]=j.useState([]),[c,d]=j.useState(0),[f,m]=j.useState(0),[g,v]=j.useState(null),b=j.useRef(null),[,_]=j.useState(null),[E,L]=j.useState(!1),[I,w]=j.useState(!1),[F,U]=j.useState({}),[V,B]=j.useState(!1),[q,k]=j.useState("running"),[R,K]=j.useState(null),[X,ee]=j.useState(!1),[le,ae]=j.useState(F$),Y=!!le.autoAddToDownloadList,Q=!!le.autoStartAddedDownloads,te=j.useRef(!1),oe=j.useRef({}),de=j.useRef([]);j.useEffect(()=>{te.current=E},[E]),j.useEffect(()=>{oe.current=F},[F]),j.useEffect(()=>{de.current=n},[n]);const $=j.useRef(null),ie=j.useRef("");j.useEffect(()=>{let _e=!1;const $e=async()=>{try{const We=await As("/api/settings",{cache:"no-store"});!_e&&We&&ae(pt=>({...pt,...We}))}catch{}},He=()=>{$e()},Xe=()=>{$e()};return window.addEventListener("recorder-settings-updated",He),window.addEventListener("focus",Xe),document.addEventListener("visibilitychange",Xe),$e(),()=>{_e=!0,window.removeEventListener("recorder-settings-updated",He),window.removeEventListener("focus",Xe),document.removeEventListener("visibilitychange",Xe)}},[]),j.useEffect(()=>{let _e=!1;const $e=async()=>{try{const Xe=await As("/api/models/meta",{cache:"no-store"}),We=Number(Xe?.count??0);!_e&&Number.isFinite(We)&&m(We)}catch{}};$e();const He=window.setInterval($e,document.hidden?6e4:3e4);return()=>{_e=!0,window.clearInterval(He)}},[]);const he=j.useMemo(()=>Object.entries(F).map(([_e,$e])=>({name:_e,value:$e})),[F]),Ce=_e=>{K(_e),ee(!1)},be=n.filter(_e=>_e.status==="running"),Ue=[{id:"running",label:"Laufende Downloads",count:be.length},{id:"finished",label:"Abgeschlossene Downloads",count:c},{id:"models",label:"Models",count:f},{id:"settings",label:"Einstellungen"}],Ee=j.useMemo(()=>s.trim().length>0&&!E,[s,E]);j.useEffect(()=>{let _e=!1;return(async()=>{try{const He=await As("/api/cookies",{cache:"no-store"}),Xe=fp(He?.cookies);if(_e||U(Xe),Object.keys(Xe).length===0){const We=localStorage.getItem(rv);if(We)try{const pt=JSON.parse(We),mt=fp(pt);Object.keys(mt).length>0&&(_e||U(mt),await As("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:mt})}))}catch{}}}catch{const He=localStorage.getItem(rv);if(He)try{const Xe=JSON.parse(He);_e||U(fp(Xe))}catch{}}finally{_e||B(!0)}})(),()=>{_e=!0}},[]),j.useEffect(()=>{V&&localStorage.setItem(rv,JSON.stringify(F))},[F,V]),j.useEffect(()=>{let _e=!1,$e;const He=async()=>{try{const We=await fetch("/api/record/done/meta",{cache:"no-store"});if(!We.ok)return;const pt=await We.json();_e||d(pt.count??0)}catch{}finally{if(!_e){const We=document.hidden?6e4:3e4;$e=window.setTimeout(He,We)}}},Xe=()=>{document.hidden||He()};return document.addEventListener("visibilitychange",Xe),He(),()=>{_e=!0,$e&&window.clearTimeout($e),document.removeEventListener("visibilitychange",Xe)}},[]),j.useEffect(()=>{if(s.trim()===""){t(null),i(null);return}const _e=setTimeout(async()=>{try{const $e=await As("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:s.trim()})});t($e),i(null)}catch($e){t(null),i($e?.message??String($e))}},300);return()=>clearTimeout(_e)},[s]),j.useEffect(()=>{let _e=!1;const $e=async()=>{try{const Xe=await As("/api/record/list");_e||r(Array.isArray(Xe)?Xe:[])}catch{}};$e();const He=setInterval($e,1e3);return()=>{_e=!0,clearInterval(He)}},[]),j.useEffect(()=>{if(q!=="finished")return;let _e=!1,$e=!1;const He=async()=>{if(!(_e||$e)){$e=!0;try{const jt=await As("/api/record/done",{cache:"no-store"});_e||u(Array.isArray(jt)?jt:[])}catch{_e||u([])}finally{$e=!1}}};He();const We=document.hidden?6e4:2e4,pt=window.setInterval(He,We),mt=()=>{document.hidden||He()};return document.addEventListener("visibilitychange",mt),()=>{_e=!0,window.clearInterval(pt),document.removeEventListener("visibilitychange",mt)}},[q]);function je(_e){try{return new URL(_e).hostname.includes("chaturbate.com")}catch{return!1}}function Ve(_e,$e){const He=Object.fromEntries(Object.entries(_e).map(([Xe,We])=>[Xe.trim().toLowerCase(),We]));for(const Xe of $e){const We=He[Xe.toLowerCase()];if(We)return We}}function tt(_e){const $e=Ve(_e,["cf_clearance"]),He=Ve(_e,["sessionid","session_id","sessionid","sessionId"]);return!!($e&&He)}const lt=j.useCallback(async(_e,$e)=>{const He=_e.trim();if(!He||te.current)return!1;const Xe=!!$e?.silent;Xe||_(null);const We=oe.current;if(je(He)&&!tt(We))return Xe||_('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;if(de.current.some(mt=>mt.status==="running"&&String(mt.sourceUrl||"")===He))return!0;L(!0),te.current=!0;try{const mt=Object.entries(We).map(([fi,Ai])=>`${fi}=${Ai}`).join("; "),jt=await As("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:He,cookie:mt})});return r(fi=>[jt,...fi]),de.current=[jt,...de.current],!0}catch(mt){return Xe||_(mt?.message??String(mt)),!1}finally{L(!1),te.current=!1}},[]);async function Me(_e){const $e=_e.sourceUrl??_e.SourceURL??"",He=K2($e);if(He){const Ai=await As("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:He})});return await As("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ai)})}const Xe=j$(_e.output||"");if(!Xe)return null;const We=Date.now(),pt=b.current;if(!pt||We-pt.ts>3e4){const Ai=await As("/api/models/list",{cache:"no-store"});b.current={ts:We,list:Array.isArray(Ai)?Ai:[]}}const mt=b.current?.list??[],jt=Xe.toLowerCase(),fi=mt.filter(Ai=>(Ai.modelKey||"").toLowerCase()===jt);return fi.length===0?null:fi.sort((Ai,Yi)=>+!!Yi.favorite-+!!Ai.favorite)[0]}j.useEffect(()=>{let _e=!1;if(!R){v(null);return}return(async()=>{try{const $e=await Me(R);_e||v($e)}catch{_e||v(null)}})(),()=>{_e=!0}},[R]);async function Je(){return lt(s)}const st=j.useCallback(async _e=>{const $e=Tn(_e.output||"");if($e){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:$e,phase:"start"}}));try{await As(`/api/record/delete?file=${encodeURIComponent($e)}`,{method:"POST"}),window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:$e,phase:"success"}})),window.setTimeout(()=>{u(He=>He.filter(Xe=>Tn(Xe.output||"")!==$e)),r(He=>He.filter(Xe=>Tn(Xe.output||"")!==$e)),K(He=>He&&Tn(He.output||"")===$e?null:He)},320)}catch(He){throw window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:$e,phase:"error"}})),He}}},[]),Ct=j.useCallback(async _e=>{const $e=Tn(_e.output||"");if(!$e)return;const He=await As(`/api/record/toggle-hot?file=${encodeURIComponent($e)}`,{method:"POST"}),Xe=av(_e.output||"",He.newFile);K(We=>We&&{...We,output:Xe}),u(We=>We.map(pt=>Tn(pt.output||"")===$e?{...pt,output:av(pt.output||"",He.newFile)}:pt)),r(We=>We.map(pt=>Tn(pt.output||"")===$e?{...pt,output:av(pt.output||"",He.newFile)}:pt))},[]);async function Fe(_e){return As("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_e)})}const ut=j.useCallback(async _e=>{const $e=Tn(_e.output||""),He=!!(R&&Tn(R.output||"")===$e);let Xe=He?g:null;if(Xe||(Xe=await Me(_e)),!Xe)return;const We=!Xe.favorite,pt=await Fe({id:Xe.id,favorite:We,...We?{clearLiked:!0}:{}});He&&v(pt),window.dispatchEvent(new Event("models-changed"))},[R,g]),xt=j.useCallback(async _e=>{const $e=Tn(_e.output||""),He=!!(R&&Tn(R.output||"")===$e);let Xe=He?g:null;if(Xe||(Xe=await Me(_e)),!Xe)return;const pt=Xe.liked===!0?await Fe({id:Xe.id,clearLiked:!0}):await Fe({id:Xe.id,liked:!0,favorite:!1});He&&v(pt),window.dispatchEvent(new Event("models-changed"))},[R,g]);j.useEffect(()=>{if(!Y&&!Q||!navigator.clipboard?.readText)return;let _e=!1,$e=!1,He=null;const Xe=async()=>{if(!(_e||$e)){$e=!0;try{const mt=await navigator.clipboard.readText(),jt=K2(mt);if(!jt||jt===ie.current)return;ie.current=jt,Y&&e(jt),Q&&(te.current?$.current=jt:($.current=null,await lt(jt)))}catch{}finally{$e=!1}}},We=mt=>{_e||(He=window.setTimeout(async()=>{await Xe(),We(document.hidden?5e3:1500)},mt))},pt=()=>{Xe()};return window.addEventListener("focus",pt),document.addEventListener("visibilitychange",pt),We(0),()=>{_e=!0,He&&window.clearTimeout(He),window.removeEventListener("focus",pt),document.removeEventListener("visibilitychange",pt)}},[Y,Q,lt]),j.useEffect(()=>{if(E||!Q)return;const _e=$.current;_e&&($.current=null,lt(_e))},[E,Q,lt]);async function Tt(_e){try{await As(`/api/record/stop?id=${encodeURIComponent(_e)}`,{method:"POST"})}catch{}}return O.jsxs("div",{className:"mx-auto py-4 max-w-7xl sm:px-6 lg:px-8 space-y-6",children:[O.jsxs(Pn,{header:O.jsxs("div",{className:"flex items-start justify-between gap-4",children:[O.jsx("h2",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Recorder"}),O.jsxs("div",{className:"flex gap-2",children:[O.jsx(es,{variant:"secondary",onClick:()=>w(!0),children:"Cookies"}),O.jsx(es,{variant:"primary",onClick:Je,disabled:!Ee,children:"Start"})]})]}),children:[O.jsx("label",{className:"block text-sm font-medium text-gray-900 dark:text-gray-200",children:"Source URL"}),O.jsx("input",{value:s,onChange:_e=>e(_e.target.value),placeholder:"https://…",className:"mt-1 block w-full rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),je(s)&&!tt(F)&&O.jsxs("div",{className:"mt-2 text-xs text-amber-600 dark:text-amber-400",children:["⚠️ Für Chaturbate werden die Cookies ",O.jsx("code",{children:"cf_clearance"})," und"," ",O.jsx("code",{children:"sessionId"})," benötigt."]})]}),O.jsx(PO,{tabs:Ue,value:q,onChange:k,ariaLabel:"Tabs",variant:"pillsBrand"}),q==="running"&&O.jsx(I$,{jobs:be,onOpenPlayer:Ce,onStopJob:Tt,blurPreviews:!!le.blurPreviews}),q==="finished"&&O.jsx(pP,{jobs:n,doneJobs:o,onOpenPlayer:Ce,onDeleteJob:st,onToggleHot:Ct,onToggleFavorite:ut,onToggleLike:xt,blurPreviews:!!le.blurPreviews}),q==="models"&&O.jsx(B$,{}),q==="settings"&&O.jsx(MO,{}),O.jsx(kO,{open:I,onClose:()=>w(!1),initialCookies:he,onApply:_e=>{const $e=fp(Object.fromEntries(_e.map(He=>[He.name,He.value])));U($e),As("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:$e})}).catch(()=>{})}}),R&&O.jsx(SB,{job:R,expanded:X,onToggleExpand:()=>ee(_e=>!_e),onClose:()=>K(null),isHot:Tn(R.output||"").startsWith("HOT "),isFavorite:!!g?.favorite,isLiked:g?.liked===!0,onDelete:st,onToggleHot:Ct,onToggleFavorite:ut,onToggleLike:xt})]})}vk.createRoot(document.getElementById("root")).render(O.jsx(j.StrictMode,{children:O.jsx(H$,{})})); diff --git a/backend/web/dist/index.html b/backend/web/dist/index.html index bc2368f..068cb68 100644 --- a/backend/web/dist/index.html +++ b/backend/web/dist/index.html @@ -5,8 +5,8 @@ frontend - - + +
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1d0f571..b170cb2 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,16 +1,22 @@ +// frontend\src\App.tsx + import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import './App.css' import Button from './components/ui/Button' import CookieModal from './components/ui/CookieModal' -import Card from './components/ui/Card' import Tabs, { type TabItem } from './components/ui/Tabs' import RecorderSettings from './components/ui/RecorderSettings' import FinishedDownloads from './components/ui/FinishedDownloads' import Player from './components/ui/Player' import type { RecordJob } from './types' -import RunningDownloads from './components/ui/RunningDownloads' +import Downloads from './components/ui/Downloads' import ModelsTab from './components/ui/ModelsTab' import ProgressBar from './components/ui/ProgressBar' +import ModelDetails from './components/ui/ModelDetails' +import { SignalIcon, HeartIcon, HandThumbUpIcon } from '@heroicons/react/24/solid' +import PerformanceMonitor from './components/ui/PerformanceMonitor' +import { useNotify } from './components/ui/notify' +import { startChaturbateOnlinePolling } from './lib/chaturbateOnlinePoller' const COOKIE_STORAGE_KEY = 'record_cookies' @@ -39,7 +45,12 @@ type RecorderSettings = { autoAddToDownloadList?: boolean autoStartAddedDownloads?: boolean useChaturbateApi?: boolean + useMyFreeCamsWatcher?: boolean + autoDeleteSmallDownloads?: boolean + autoDeleteSmallDownloadsBelowMB?: number blurPreviews?: boolean + teaserPlayback?: 'still' | 'hover' | 'all' + teaserAudio?: boolean } const DEFAULT_RECORDER_SETTINGS: RecorderSettings = { @@ -49,7 +60,12 @@ const DEFAULT_RECORDER_SETTINGS: RecorderSettings = { autoAddToDownloadList: false, autoStartAddedDownloads: false, useChaturbateApi: false, + useMyFreeCamsWatcher: false, + autoDeleteSmallDownloads: false, + autoDeleteSmallDownloadsBelowMB: 50, blurPreviews: false, + teaserPlayback: 'hover', + teaserAudio: false, } type StoredModel = { @@ -60,22 +76,81 @@ type StoredModel = { watching: boolean favorite?: boolean liked?: boolean | null + isUrl?: boolean + path?: string } -function extractFirstHttpUrl(text: string): string | null { +type PendingWatchedRoom = { + id: string + modelKey: string + url: string + currentShow: string // private/hidden/away/public/unknown + imageUrl?: string +} + +type ParsedModel = { + input: string + isUrl: boolean + host?: string + path?: string + modelKey: string +} + +type ChaturbateOnlineRoom = { + username?: string + current_show?: string + chat_room_url?: string + image_url?: string +} + +type ChaturbateOnlineResponse = { + enabled: boolean + rooms: ChaturbateOnlineRoom[] +} + +function normalizeHttpUrl(raw: string): string | null { + let v = (raw ?? '').trim() + if (!v) return null + + // häufige Copy/Paste-Randzeichen entfernen + v = v.replace(/^[("'[{<]+/, '').replace(/[)"'\]}>.,;:]+$/, '') + + // ohne Scheme -> https:// + if (!/^https?:\/\//i.test(v)) v = `https://${v}` + + try { + const u = new URL(v) + if (u.protocol !== 'http:' && u.protocol !== 'https:') return null + return u.toString() + } catch { + return null + } +} + +function extractFirstUrl(text: string): string | null { const t = (text ?? '').trim() if (!t) return null - // erstes Token, das wie eine URL aussieht for (const token of t.split(/\s+/g)) { - if (!/^https?:\/\//i.test(token)) continue - try { - return new URL(token).toString() - } catch {} + const url = normalizeHttpUrl(token) + if (url) return url } return null } +type Provider = 'chaturbate' | 'mfc' + +function getProviderFromNormalizedUrl(normUrl: string): Provider | null { + try { + const host = new URL(normUrl).hostname.replace(/^www\./i, '').toLowerCase() + if (host === 'chaturbate.com' || host.endsWith('.chaturbate.com')) return 'chaturbate' + if (host === 'myfreecams.com' || host.endsWith('.myfreecams.com')) return 'mfc' + return null + } catch { + return null + } +} + const baseName = (p: string) => (p || '').replaceAll('\\', '/').split('/').pop() || '' function replaceBasename(fullPath: string, newBase: string) { @@ -105,11 +180,41 @@ function modelKeyFromFilename(fileOrPath: string): string | null { return base ? base : null } - export default function App() { - + + const notify = useNotify() + const DONE_PAGE_SIZE = 8 + type DoneSortMode = + | 'completed_desc' + | 'completed_asc' + | 'model_asc' + | 'model_desc' + | 'file_asc' + | 'file_desc' + | 'duration_desc' + | 'duration_asc' + | 'size_desc' + | 'size_asc' + + const DONE_SORT_KEY = 'finishedDownloads_sort' + const [doneSort, setDoneSort] = useState(() => { + try { + const v = window.localStorage.getItem(DONE_SORT_KEY) as DoneSortMode | null + return v || 'completed_desc' + } catch { + return 'completed_desc' + } + }) + + useEffect(() => { + try { + window.localStorage.setItem(DONE_SORT_KEY, doneSort) + } catch {} + }, [doneSort]) + + const [playerModelKey, setPlayerModelKey] = useState(null) const [sourceUrl, setSourceUrl] = useState('') const [jobs, setJobs] = useState([]) const [doneJobs, setDoneJobs] = useState([]) @@ -117,8 +222,148 @@ export default function App() { const [doneCount, setDoneCount] = useState(0) const [modelsCount, setModelsCount] = useState(0) + const [lastHeaderUpdateAtMs, setLastHeaderUpdateAtMs] = useState(() => Date.now()) + const [nowMs, setNowMs] = useState(() => Date.now()) + useEffect(() => { + const t = window.setInterval(() => setNowMs(Date.now()), 1000) + return () => window.clearInterval(t) + }, []) + + const lower = (s: string) => (s || '').toLowerCase().trim() + + const formatAgoDE = (diffMs: number) => { + const s = Math.max(0, Math.floor(diffMs / 1000)) + if (s < 2) return 'gerade eben' + if (s < 60) return `vor ${s} Sekunden` + + const m = Math.floor(s / 60) + if (m === 1) return 'vor 1 Minute' + if (m < 60) return `vor ${m} Minuten` + + const h = Math.floor(m / 60) + if (h === 1) return 'vor 1 Stunde' + return `vor ${h} Stunden` + } + + const headerUpdatedText = useMemo(() => { + const diff = nowMs - lastHeaderUpdateAtMs + return `(zuletzt aktualisiert: ${formatAgoDE(diff)})` + }, [nowMs, lastHeaderUpdateAtMs]) + + const [modelsByKey, setModelsByKey] = useState>({}) + + const buildModelsByKey = useCallback((list: StoredModel[]) => { + const map: Record = {} + + for (const m of Array.isArray(list) ? list : []) { + const k = (m?.modelKey || '').trim().toLowerCase() + if (!k) continue + + const score = (x: StoredModel) => (x.favorite ? 4 : 0) + (x.liked === true ? 2 : 0) + (x.watching ? 1 : 0) + + const cur = map[k] + if (!cur || score(m) >= score(cur)) map[k] = m + } + + return map + }, []) + + const refreshModelsByKey = useCallback(async () => { + try { + const list = await apiJSON('/api/models/list', { cache: 'no-store' as any }) + setModelsByKey(buildModelsByKey(Array.isArray(list) ? list : [])) + setLastHeaderUpdateAtMs(Date.now()) + } catch { + // ignore + } + }, [buildModelsByKey]) + const [playerModel, setPlayerModel] = useState(null) const modelsCacheRef = useRef<{ ts: number; list: StoredModel[] } | null>(null) + + const [detailsModelKey, setDetailsModelKey] = useState(null) + + useEffect(() => { + const onOpen = (ev: Event) => { + const e = ev as CustomEvent<{ modelKey?: string }> + const raw = (e.detail?.modelKey ?? '').trim() + + let k = raw.replace(/^https?:\/\//i, '') + if (k.includes('/')) k = k.split('/').filter(Boolean).pop() || k + if (k.includes(':')) k = k.split(':').pop() || k + k = k.trim().toLowerCase() + + if (k) setDetailsModelKey(k) + } + + window.addEventListener('open-model-details', onOpen as any) + return () => window.removeEventListener('open-model-details', onOpen as any) + }, []) + + const upsertModelCache = useCallback((m: StoredModel) => { + const now = Date.now() + const cur = modelsCacheRef.current + if (!cur) { + modelsCacheRef.current = { ts: now, list: [m] } + return + } + cur.ts = now + const idx = cur.list.findIndex((x) => x.id === m.id) + if (idx >= 0) cur.list[idx] = m + else cur.list.unshift(m) + }, []) + + useEffect(() => { + // initial laden + void refreshModelsByKey() + + const onChanged = (ev: Event) => { + const e = ev as CustomEvent + const detail = e?.detail ?? {} + const updated = detail?.model + + // ✅ 1) Update-Event mit Model: direkt in State übernehmen (KEIN /api/models/list) + if (updated && typeof updated === 'object') { + const k = String(updated.modelKey ?? '').toLowerCase().trim() + if (k) setModelsByKey((prev) => ({ ...prev, [k]: updated })) + + try { + upsertModelCache(updated) + } catch {} + + setPlayerModel((prev) => (prev?.id === updated.id ? updated : prev)) + setLastHeaderUpdateAtMs(Date.now()) + return + } + + // ✅ 2) Delete-Event (optional): ebenfalls ohne Voll-Refresh + if (detail?.removed) { + const removedId = String(detail?.id ?? '').trim() + const removedKey = String(detail?.modelKey ?? '').toLowerCase().trim() + + if (removedKey) { + setModelsByKey((prev) => { + const { [removedKey]: _drop, ...rest } = prev + return rest + }) + } + + if (removedId) { + setPlayerModel((prev) => (prev?.id === removedId ? null : prev)) + } + + setLastHeaderUpdateAtMs(Date.now()) + return + } + + // ✅ 3) Nur wenn kein Model/keine Delete-Info mitkommt: kompletter Refresh + void refreshModelsByKey() + } + + window.addEventListener('models-changed', onChanged as any) + return () => window.removeEventListener('models-changed', onChanged as any) + }, [refreshModelsByKey, upsertModelCache]) + const [error, setError] = useState(null) const [busy, setBusy] = useState(false) const [cookieModalOpen, setCookieModalOpen] = useState(false) @@ -130,26 +375,183 @@ export default function App() { const [assetNonce, setAssetNonce] = useState(0) const bumpAssets = useCallback(() => setAssetNonce((n) => n + 1), []) + const assetsBumpTimerRef = useRef(null) + + const bumpAssetsTwice = useCallback(() => { + bumpAssets() + if (assetsBumpTimerRef.current) window.clearTimeout(assetsBumpTimerRef.current) + assetsBumpTimerRef.current = window.setTimeout(() => bumpAssets(), 3500) + }, [bumpAssets]) const [recSettings, setRecSettings] = useState(DEFAULT_RECORDER_SETTINGS) + const recSettingsRef = useRef(recSettings) + useEffect(() => { + recSettingsRef.current = recSettings + }, [recSettings]) const autoAddEnabled = Boolean(recSettings.autoAddToDownloadList) const autoStartEnabled = Boolean(recSettings.autoStartAddedDownloads) + const [pendingWatchedRooms, setPendingWatchedRooms] = useState([]) + const [pendingAutoStartByKey, setPendingAutoStartByKey] = useState>({}) + // "latest" Refs (damit Clipboard-Loop nicht wegen jobs-Polling neu startet) const busyRef = useRef(false) const cookiesRef = useRef>({}) const jobsRef = useRef([]) - - useEffect(() => { busyRef.current = busy }, [busy]) - useEffect(() => { cookiesRef.current = cookies }, [cookies]) - useEffect(() => { jobsRef.current = jobs }, [jobs]) + useEffect(() => { + busyRef.current = busy + }, [busy]) + useEffect(() => { + cookiesRef.current = cookies + }, [cookies]) + useEffect(() => { + jobsRef.current = jobs + }, [jobs]) // pending start falls gerade busy const pendingStartUrlRef = useRef(null) - // um identische Clipboard-Werte nicht dauernd zu triggern const lastClipboardUrlRef = useRef('') + // ✅ Online-Status für Models aus dem Model-Store + const [onlineStoreKeysLower, setOnlineStoreKeysLower] = useState>({}) + + // ✅ Zentraler Snapshot: username(lower) -> room + const [cbOnlineByKeyLower, setCbOnlineByKeyLower] = useState>({}) + const cbOnlineByKeyLowerRef = useRef>({}) + useEffect(() => { + cbOnlineByKeyLowerRef.current = cbOnlineByKeyLower + }, [cbOnlineByKeyLower]) + + const isChaturbateStoreModel = useCallback((m?: StoredModel | null) => { + const h = String(m?.host ?? '').toLowerCase() + const input = String(m?.input ?? '').toLowerCase() + return h.includes('chaturbate') || input.includes('chaturbate.com') + }, []) + + const chaturbateStoreKeysLower = useMemo(() => { + const set = new Set() + for (const m of Object.values(modelsByKey)) { + if (!isChaturbateStoreModel(m)) continue + const k = lower(String(m?.modelKey ?? '')) + if (k) set.add(k) + } + return Array.from(set) + }, [modelsByKey, isChaturbateStoreModel]) + + // ✅ latest Refs für Poller-Closures (damit Poller nicht "stale" wird) + const modelsByKeyRef = useRef(modelsByKey) + useEffect(() => { + modelsByKeyRef.current = modelsByKey + }, [modelsByKey]) + + const pendingAutoStartByKeyRef = useRef(pendingAutoStartByKey) + useEffect(() => { + pendingAutoStartByKeyRef.current = pendingAutoStartByKey + }, [pendingAutoStartByKey]) + + const chaturbateStoreKeysLowerRef = useRef(chaturbateStoreKeysLower) + useEffect(() => { + chaturbateStoreKeysLowerRef.current = chaturbateStoreKeysLower + }, [chaturbateStoreKeysLower]) + + const selectedTabRef = useRef(selectedTab) + useEffect(() => { + selectedTabRef.current = selectedTab + }, [selectedTab]) + + // ✅ StartURL (hier habe ich den alten Online-Fetch entfernt und nur Snapshot genutzt) + const startUrl = useCallback(async (rawUrl: string, opts?: { silent?: boolean }): Promise => { + const norm = normalizeHttpUrl(rawUrl) + if (!norm) return false + + const silent = Boolean(opts?.silent) + if (!silent) setError(null) + + const provider = getProviderFromNormalizedUrl(norm) + if (!provider) { + if (!silent) setError('Nur chaturbate.com oder myfreecams.com werden unterstützt.') + return false + } + + const currentCookies = cookiesRef.current + + if (provider === 'chaturbate' && !hasRequiredChaturbateCookies(currentCookies)) { + if (!silent) setError('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.') + return false + } + + // Duplicate-running guard (normalisiert vergleichen) + const alreadyRunning = jobsRef.current.some((j) => { + if (j.status !== 'running') return false + const jNorm = normalizeHttpUrl(String((j as any).sourceUrl || '')) + return jNorm === norm + }) + if (alreadyRunning) return true + + // ✅ Chaturbate: parse modelKey + queue-logic über Snapshot + if (provider === 'chaturbate' && recSettingsRef.current.useChaturbateApi) { + try { + const parsed = await apiJSON('/api/models/parse', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ input: norm }), + }) + + const mkLower = String(parsed?.modelKey ?? '').trim().toLowerCase() + if (mkLower) { + // 1) Wenn busy: IMMER queue (auch public, damit "public queued" sichtbar bleibt) + if (busyRef.current) { + setPendingAutoStartByKey((prev) => ({ ...(prev || {}), [mkLower]: norm })) + return true + } + + // 2) Wenn Snapshot sagt: online aber NICHT public -> queue + const room = cbOnlineByKeyLowerRef.current[mkLower] + const show = String(room?.current_show ?? '') + if (room && show && show !== 'public') { + setPendingAutoStartByKey((prev) => ({ ...(prev || {}), [mkLower]: norm })) + return true + } + } + } catch { + // parse fail -> normal starten + } + } else { + // Nicht-Chaturbate-API: wenn busy, wenigstens "pendingStart" setzen + if (busyRef.current) { + pendingStartUrlRef.current = norm + return true + } + } + + if (busyRef.current) return false + setBusy(true) + busyRef.current = true + + try { + const cookieString = Object.entries(currentCookies) + .map(([k, v]) => `${k}=${v}`) + .join('; ') + + const created = await apiJSON('/api/record', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ url: norm, cookie: cookieString }), + }) + + setJobs((prev) => [created, ...prev]) + jobsRef.current = [created, ...jobsRef.current] + return true + } catch (e: any) { + if (!silent) setError(e?.message ?? String(e)) + return false + } finally { + setBusy(false) + busyRef.current = false + } + }, []) + // ✅ settings: nur einmal laden + nach Save-Event + optional bei focus/visibility useEffect(() => { let cancelled = false @@ -157,7 +559,7 @@ export default function App() { const load = async () => { try { const s = await apiJSON('/api/settings', { cache: 'no-store' }) - if (!cancelled && s) setRecSettings((prev) => ({ ...prev, ...s })) + if (!cancelled && s) setRecSettings({ ...DEFAULT_RECORDER_SETTINGS, ...s }) } catch { // ignore } @@ -167,20 +569,20 @@ export default function App() { const onFocus = () => void load() window.addEventListener('recorder-settings-updated', onUpdated as EventListener) - window.addEventListener('focus', onFocus) + window.addEventListener('hover', onFocus) document.addEventListener('visibilitychange', onFocus) - load() // einmal initial + load() return () => { cancelled = true window.removeEventListener('recorder-settings-updated', onUpdated as EventListener) - window.removeEventListener('focus', onFocus) + window.removeEventListener('hover', onFocus) document.removeEventListener('visibilitychange', onFocus) } }, []) - // ✅ 1) Models-Count (leicht): nur Zahl fürs Tab, nicht die komplette Liste + // ✅ Models-Count (leicht) useEffect(() => { let cancelled = false @@ -188,7 +590,10 @@ export default function App() { try { const meta = await apiJSON<{ count?: number }>('/api/models/meta', { cache: 'no-store' }) const c = Number(meta?.count ?? 0) - if (!cancelled && Number.isFinite(c)) setModelsCount(c) + if (!cancelled && Number.isFinite(c)) { + setModelsCount(c) + setLastHeaderUpdateAtMs(Date.now()) + } } catch { // ignore } @@ -202,18 +607,43 @@ export default function App() { } }, []) - const initialCookies = useMemo( - () => Object.entries(cookies).map(([name, value]) => ({ name, value })), - [cookies] - ) + const initialCookies = useMemo(() => Object.entries(cookies).map(([name, value]) => ({ name, value })), [cookies]) - const openPlayer = (job: RecordJob) => { + const openPlayer = useCallback((job: RecordJob) => { + modelsCacheRef.current = null + setPlayerModel(null) setPlayerJob(job) - setPlayerExpanded(false) // startet als Mini - } + setPlayerExpanded(false) + }, []) const runningJobs = jobs.filter((j) => j.status === 'running') + const onlineModelsCount = useMemo(() => { + let c = 0 + for (const m of Object.values(modelsByKey)) { + const k = lower(String(m?.modelKey ?? '')) + if (!k) continue + if (onlineStoreKeysLower[k]) c++ + } + return c + }, [modelsByKey, onlineStoreKeysLower]) + + const { onlineFavCount, onlineLikedCount } = useMemo(() => { + let fav = 0 + let liked = 0 + + for (const m of Object.values(modelsByKey)) { + const k = lower(String(m?.modelKey ?? '')) + if (!k) continue + if (!onlineStoreKeysLower[k]) continue + + if (m?.favorite) fav++ + if (m?.liked === true) liked++ + } + + return { onlineFavCount: fav, onlineLikedCount: liked } + }, [modelsByKey, onlineStoreKeysLower]) + const tabs: TabItem[] = [ { id: 'running', label: 'Laufende Downloads', count: runningJobs.length }, { id: 'finished', label: 'Abgeschlossene Downloads', count: doneCount }, @@ -223,17 +653,16 @@ export default function App() { const canStart = useMemo(() => sourceUrl.trim().length > 0 && !busy, [sourceUrl, busy]) + // Cookies load/save useEffect(() => { let cancelled = false const load = async () => { - // 1) Try backend first (persisted + encrypted in recorder_settings.json) try { const res = await apiJSON<{ cookies?: Record }>('/api/cookies', { cache: 'no-store' }) const fromBackend = normalizeCookies(res?.cookies) if (!cancelled) setCookies(fromBackend) - // Optional migration: if backend is empty but localStorage has cookies, push them once if (Object.keys(fromBackend).length === 0) { const raw = localStorage.getItem(COOKIE_STORAGE_KEY) if (raw) { @@ -254,7 +683,6 @@ export default function App() { } } } catch { - // 2) Fallback: localStorage const raw = localStorage.getItem(COOKIE_STORAGE_KEY) if (raw) { try { @@ -278,6 +706,7 @@ export default function App() { localStorage.setItem(COOKIE_STORAGE_KEY, JSON.stringify(cookies)) }, [cookies, cookiesLoaded]) + // done meta polling (unverändert) useEffect(() => { let cancelled = false let t: number | undefined @@ -287,12 +716,14 @@ export default function App() { const res = await fetch('/api/record/done/meta', { cache: 'no-store' }) if (!res.ok) return const meta = (await res.json()) as { count?: number } - if (!cancelled) setDoneCount(meta.count ?? 0) + if (!cancelled) { + setDoneCount(meta.count ?? 0) + setLastHeaderUpdateAtMs(Date.now()) + } } catch { // ignore } finally { if (!cancelled) { - // wenn Tab nicht aktiv/Seite im Hintergrund: weniger oft const ms = document.hidden ? 60_000 : 30_000 t = window.setTimeout(loadDoneMeta, ms) } @@ -318,6 +749,7 @@ export default function App() { if (donePage > maxPage) setDonePage(maxPage) }, [doneCount, donePage]) + // jobs SSE / polling (unverändert) useEffect(() => { let cancelled = false let es: EventSource | null = null @@ -326,10 +758,28 @@ export default function App() { const applyList = (list: any) => { const arr = Array.isArray(list) ? (list as RecordJob[]) : [] - if (!cancelled) { - setJobs(arr) - jobsRef.current = arr - } + if (cancelled) return + + const prev = jobsRef.current + const prevById = new Map(prev.map((j) => [j.id, j.status])) + + const endedNow = arr.some((j) => { + const ps = prevById.get(j.id) + return ps && ps !== j.status && (j.status === 'finished' || j.status === 'stopped') + }) + + setJobs(arr) + jobsRef.current = arr + setLastHeaderUpdateAtMs(Date.now()) + + if (endedNow) bumpAssetsTwice() + + setPlayerJob((prevJob) => { + if (!prevJob) return prevJob + const updated = arr.find((j) => j.id === prevJob.id) + if (updated) return updated + return prevJob.status === 'running' ? null : prevJob + }) } const loadOnce = async () => { @@ -350,47 +800,37 @@ export default function App() { fallbackTimer = window.setInterval(loadOnce, document.hidden ? 15000 : 5000) } - // initial einmal laden void loadOnce() - // SSE verbinden es = new EventSource('/api/record/stream') const onJobs = (ev: MessageEvent) => { try { applyList(JSON.parse(ev.data)) - } catch { - // ignore - } + } catch {} } es.addEventListener('jobs', onJobs as any) - - es.onerror = () => { - // wenn SSE nicht geht (Proxy/Nginx/Browser): fallback polling - startFallbackPolling() - } + es.onerror = () => startFallbackPolling() const onVis = () => { - // wenn wieder sichtbar/fokus: einmal nachziehen if (!document.hidden) void loadOnce() } document.addEventListener('visibilitychange', onVis) - window.addEventListener('focus', onVis) + window.addEventListener('hover', onVis) return () => { cancelled = true if (fallbackTimer) window.clearInterval(fallbackTimer) document.removeEventListener('visibilitychange', onVis) - window.removeEventListener('focus', onVis) + window.removeEventListener('hover', onVis) es?.removeEventListener('jobs', onJobs as any) es?.close() es = null } - }, []) + }, [bumpAssetsTwice]) useEffect(() => { - // ✅ nur pollen, wenn Finished-Tab aktiv ist if (selectedTab !== 'finished') return let cancelled = false @@ -401,27 +841,23 @@ export default function App() { inFlight = true try { const list = await apiJSON( - `/api/record/done?page=${donePage}&pageSize=${DONE_PAGE_SIZE}`, + `/api/record/done?page=${donePage}&pageSize=${DONE_PAGE_SIZE}&sort=${encodeURIComponent(doneSort)}`, { cache: 'no-store' as any } ) if (!cancelled) setDoneJobs(Array.isArray(list) ? list : []) } catch { - // optional: bei Fehler nicht leeren, wenn du den letzten Stand behalten willst if (!cancelled) setDoneJobs([]) } finally { inFlight = false } } - // beim Betreten des Tabs einmal sofort laden loadDone() - // ✅ weniger aggressiv pollen - const baseMs = 20000 // 20s + const baseMs = 20000 const tickMs = document.hidden ? 60000 : baseMs const t = window.setInterval(loadDone, tickMs) - // ✅ wenn Tab wieder sichtbar wird: direkt refresh const onVis = () => { if (!document.hidden) void loadDone() } @@ -432,32 +868,23 @@ export default function App() { window.clearInterval(t) document.removeEventListener('visibilitychange', onVis) } - }, [selectedTab, donePage]) + }, [selectedTab, donePage, doneSort]) - // ✅ Sofort-Refresh für Finished-Liste + Count (z.B. nach Delete/Keep), - // damit die Seite direkt wieder mit PAGE_SIZE Items gefüllt wird und - // die Page-Nummern/Counts stimmen. const refreshDoneNow = useCallback( async (preferPage?: number) => { try { - // 1) Meta (Count) - const meta = await apiJSON<{ count?: number }>( - '/api/record/done/meta', - { cache: 'no-store' as any } - ) + const meta = await apiJSON<{ count?: number }>('/api/record/done/meta', { cache: 'no-store' as any }) const countRaw = typeof meta?.count === 'number' ? meta.count : 0 const count = Number.isFinite(countRaw) && countRaw >= 0 ? countRaw : 0 setDoneCount(count) - // 2) Page clampen const maxPage = Math.max(1, Math.ceil(count / DONE_PAGE_SIZE)) const wanted = typeof preferPage === 'number' ? preferPage : donePage const target = Math.min(Math.max(1, wanted), maxPage) if (target !== donePage) setDonePage(target) - // 3) Liste für (ggf. geclampte) Seite laden const list = await apiJSON( - `/api/record/done?page=${target}&pageSize=${DONE_PAGE_SIZE}`, + `/api/record/done?page=${target}&pageSize=${DONE_PAGE_SIZE}&sort=${encodeURIComponent(doneSort)}`, { cache: 'no-store' as any } ) setDoneJobs(Array.isArray(list) ? list : []) @@ -465,85 +892,616 @@ export default function App() { // ignore } }, - [donePage] + [donePage, doneSort] ) - - function isChaturbate(url: string): boolean { + function isChaturbate(raw: string): boolean { + const norm = normalizeHttpUrl(raw) + if (!norm) return false try { - return new URL(url).hostname.includes('chaturbate.com') + return new URL(norm).hostname.includes('chaturbate.com') } catch { return false } } - function getCookie( - cookies: Record, - names: string[] - ): string | undefined { - const lower = Object.fromEntries( - Object.entries(cookies).map(([k, v]) => [k.trim().toLowerCase(), v]) - ) + function getCookie(cookiesObj: Record, names: string[]): string | undefined { + const lowerMap = Object.fromEntries(Object.entries(cookiesObj).map(([k, v]) => [k.trim().toLowerCase(), v])) for (const n of names) { - const v = lower[n.toLowerCase()] + const v = lowerMap[n.toLowerCase()] if (v) return v } return undefined } - function hasRequiredChaturbateCookies(cookies: Record): boolean { - const cf = getCookie(cookies, ['cf_clearance']) - const sess = getCookie(cookies, ['sessionid', 'session_id', 'sessionid', 'sessionId']) + function hasRequiredChaturbateCookies(cookiesObj: Record): boolean { + const cf = getCookie(cookiesObj, ['cf_clearance']) + const sess = getCookie(cookiesObj, ['sessionid', 'session_id', 'sessionId']) return Boolean(cf && sess) } - const startUrl = useCallback(async (rawUrl: string, opts?: { silent?: boolean }): Promise => { - const url = rawUrl.trim() - if (!url) return false - if (busyRef.current) return false + async function stopJob(id: string) { + try { + await apiJSON(`/api/record/stop?id=${encodeURIComponent(id)}`, { method: 'POST' }) + } catch (e: any) { + notify.error('Stop fehlgeschlagen', e?.message ?? String(e)) + } + } - const silent = Boolean(opts?.silent) - if (!silent) setError(null) - - // ❌ Chaturbate ohne Cookies blockieren - const currentCookies = cookiesRef.current - if (isChaturbate(url) && !hasRequiredChaturbateCookies(currentCookies)) { - if (!silent) setError('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.') - return false + // ---- Player model sync (wie bei dir) ---- + useEffect(() => { + if (!playerJob) { + setPlayerModel(null) + setPlayerModelKey(null) + return } - // Duplicate-running guard - const alreadyRunning = jobsRef.current.some( - (j) => j.status === 'running' && String(j.sourceUrl || '') === url - ) - if (alreadyRunning) return true + const keyFromFile = (modelKeyFromFilename(playerJob.output || '') || '').trim().toLowerCase() + setPlayerModelKey(keyFromFile || null) - setBusy(true) - busyRef.current = true + const hit = keyFromFile ? modelsByKey[keyFromFile] : undefined + setPlayerModel(hit ?? null) + }, [playerJob, modelsByKey]) + + async function onStart() { + return startUrl(sourceUrl) + } + + const handleDeleteJob = useCallback(async (job: RecordJob) => { + const file = baseName(job.output || '') + if (!file) return + + window.dispatchEvent(new CustomEvent('finished-downloads:delete', { detail: { file, phase: 'start' as const } })) try { - const cookieString = Object.entries(currentCookies) - .map(([k, v]) => `${k}=${v}`) - .join('; ') + await apiJSON(`/api/record/delete?file=${encodeURIComponent(file)}`, { method: 'POST' }) + window.dispatchEvent(new CustomEvent('finished-downloads:delete', { detail: { file, phase: 'success' as const } })) - const created = await apiJSON('/api/record', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ url, cookie: cookieString }), - }) - - setJobs((prev) => [created, ...prev]) - // sofort in Ref, damit Duplicate-Guard greift, bevor Jobs-Polling nachzieht - jobsRef.current = [created, ...jobsRef.current] - return true + window.setTimeout(() => { + setDoneJobs((prev) => prev.filter((j) => baseName(j.output || '') !== file)) + setJobs((prev) => prev.filter((j) => baseName(j.output || '') !== file)) + setPlayerJob((prev) => (prev && baseName(prev.output || '') === file ? null : prev)) + }, 320) } catch (e: any) { - if (!silent) setError(e?.message ?? String(e)) - return false - } finally { - setBusy(false) - busyRef.current = false + window.dispatchEvent(new CustomEvent('finished-downloads:delete', { detail: { file, phase: 'error' as const } })) + notify.error('Löschen fehlgeschlagen', e?.message ?? String(e)) + return // ✅ wichtig: kein throw mehr -> keine Popup-Alerts mehr } - }, []) // arbeitet über refs, daher keine deps nötig + }, []) + + const handleKeepJob = useCallback( + async (job: RecordJob) => { + const file = baseName(job.output || '') + if (!file) return + + window.dispatchEvent(new CustomEvent('finished-downloads:delete', { detail: { file, phase: 'start' as const } })) + + try { + await apiJSON(`/api/record/keep?file=${encodeURIComponent(file)}`, { method: 'POST' }) + window.dispatchEvent(new CustomEvent('finished-downloads:delete', { detail: { file, phase: 'success' as const } })) + + window.setTimeout(() => { + setDoneJobs((prev) => prev.filter((j) => baseName(j.output || '') !== file)) + setJobs((prev) => prev.filter((j) => baseName(j.output || '') !== file)) + setPlayerJob((prev) => (prev && baseName(prev.output || '') === file ? null : prev)) + }, 320) + + if (selectedTab !== 'finished') void refreshDoneNow() + } catch (e: any) { + window.dispatchEvent(new CustomEvent('finished-downloads:delete', { detail: { file, phase: 'error' as const } })) + notify.error('Keep fehlgeschlagen', e?.message ?? String(e)) + return + } + }, + [selectedTab, refreshDoneNow] + ) + + const handleToggleHot = useCallback(async (job: RecordJob) => { + const file = baseName(job.output || '') + if (!file) return + + try { + const res = await apiJSON<{ ok: boolean; oldFile: string; newFile: string }>( + `/api/record/toggle-hot?file=${encodeURIComponent(file)}`, + { method: 'POST' } + ) + + const newOutput = replaceBasename(job.output || '', res.newFile) + + setPlayerJob((prev) => (prev ? { ...prev, output: newOutput } : prev)) + setDoneJobs((prev) => + prev.map((j) => (baseName(j.output || '') === file ? { ...j, output: replaceBasename(j.output || '', res.newFile) } : j)) + ) + setJobs((prev) => + prev.map((j) => (baseName(j.output || '') === file ? { ...j, output: replaceBasename(j.output || '', res.newFile) } : j)) + ) + } catch (e: any) { + notify.error('Umbenennen fehlgeschlagen', e?.message ?? String(e)) + return + } + }, [notify]) + + // --- flags patch (wie bei dir) --- + async function patchModelFlags(patch: any): Promise { + const res = await fetch('/api/models/flags', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(patch), + }) + + if (res.status === 204) return null + if (!res.ok) { + const text = await res.text().catch(() => '') + throw new Error(text || `HTTP ${res.status}`) + } + return res.json() + } + + const removeModelCache = useCallback((id: string) => { + const cur = modelsCacheRef.current + if (!cur || !id) return + cur.ts = Date.now() + cur.list = cur.list.filter((x) => x.id !== id) + }, []) + + // ✅ verhindert Doppel-Requests pro Model + const flagsInFlightRef = useRef>({}) + + // ✅ handleToggleFavorite (komplett) + const handleToggleFavorite = useCallback( + async (job: RecordJob) => { + const file = baseName(job.output || '') + const sameAsPlayer = Boolean(playerJob && baseName(playerJob.output || '') === file) + + // helper: host schnell aus job holen (für flags ohne id) + const hostFromJob = (j: RecordJob): string => { + try { + const urlFromJob = String((j as any).sourceUrl ?? (j as any).SourceURL ?? '') + const u = extractFirstUrl(urlFromJob) + if (!u) return '' + return new URL(u).hostname.replace(/^www\./i, '').toLowerCase() + } catch { + return '' + } + } + + // ✅ Fast-Path: modelKey aus Dateiname => instant optimistic + 1x flags call + const keyFromFile = (modelKeyFromFilename(job.output || '') || '').trim().toLowerCase() + if (keyFromFile) { + const guardKey = keyFromFile + if (flagsInFlightRef.current[guardKey]) return + flagsInFlightRef.current[guardKey] = true + + const prev = + modelsByKey[keyFromFile] ?? + ({ + id: '', // unknown (ok) + input: '', + host: hostFromJob(job) || undefined, + modelKey: keyFromFile, + watching: false, + favorite: false, + liked: null, + isUrl: false, + } as StoredModel) + + const nextFav = !Boolean(prev.favorite) + + const optimistic: StoredModel = { + ...prev, + modelKey: prev.modelKey || keyFromFile, + favorite: nextFav, + liked: nextFav ? false : prev.liked, + } + + setModelsByKey((p) => ({ ...p, [keyFromFile]: optimistic })) + upsertModelCache(optimistic) + if (sameAsPlayer) setPlayerModel(optimistic) + + try { + const updated = await patchModelFlags({ + ...(optimistic.id ? { id: optimistic.id } : {}), + host: optimistic.host || hostFromJob(job) || '', + modelKey: keyFromFile, + favorite: nextFav, + ...(nextFav ? { liked: false } : {}), + }) + + // ✅ Model wurde gelöscht (204) + if (!updated) { + setModelsByKey((p) => { + const { [keyFromFile]: _drop, ...rest } = p + return rest + }) + if (prev.id) removeModelCache(prev.id) + if (sameAsPlayer) setPlayerModel(null) + window.dispatchEvent( + new CustomEvent('models-changed', { detail: { removed: true, id: prev.id, modelKey: keyFromFile } }) + ) + return + } + + const k = lower(updated.modelKey || keyFromFile) + if (k) setModelsByKey((p) => ({ ...p, [k]: updated })) + upsertModelCache(updated) + if (sameAsPlayer) setPlayerModel(updated) + window.dispatchEvent(new CustomEvent('models-changed', { detail: { model: updated } })) + } catch (e: any) { + // rollback + setModelsByKey((p) => ({ ...p, [keyFromFile]: prev })) + upsertModelCache(prev) + if (sameAsPlayer) setPlayerModel(prev) + notify.error('Favorit umschalten fehlgeschlagen', e?.message ?? String(e)) + } finally { + delete flagsInFlightRef.current[guardKey] + } + + return + } + + // ✅ Fallback: keinen modelKey aus Filename -> wie bisher resolve+ensure + let m = sameAsPlayer ? playerModel : null + if (!m) m = await resolveModelForJob(job, { ensure: true }) + if (!m) return + + const guardKey = lower(m.modelKey || m.id || '') + if (!guardKey) return + + if (flagsInFlightRef.current[guardKey]) return + flagsInFlightRef.current[guardKey] = true + + const prev = m + const nextFav = !Boolean(prev.favorite) + + const optimistic: StoredModel = { + ...prev, + favorite: nextFav, + liked: nextFav ? false : prev.liked, + } + + const kPrev = lower(prev.modelKey || '') + if (kPrev) setModelsByKey((p) => ({ ...p, [kPrev]: optimistic })) + upsertModelCache(optimistic) + if (sameAsPlayer) setPlayerModel(optimistic) + + try { + const updated = await patchModelFlags({ + id: prev.id, + favorite: nextFav, + ...(nextFav ? { liked: false } : {}), + }) + + if (!updated) { + setModelsByKey((p) => { + const k = lower(prev.modelKey || '') + if (!k) return p + const { [k]: _drop, ...rest } = p + return rest + }) + removeModelCache(prev.id) + if (sameAsPlayer) setPlayerModel(null) + window.dispatchEvent( + new CustomEvent('models-changed', { detail: { removed: true, id: prev.id, modelKey: prev.modelKey } }) + ) + return + } + + const k = lower(updated.modelKey || '') + if (k) setModelsByKey((p) => ({ ...p, [k]: updated })) + upsertModelCache(updated) + if (sameAsPlayer) setPlayerModel(updated) + window.dispatchEvent(new CustomEvent('models-changed', { detail: { model: updated } })) + } catch (e: any) { + const k = lower(prev.modelKey || '') + if (k) setModelsByKey((p) => ({ ...p, [k]: prev })) + upsertModelCache(prev) + if (sameAsPlayer) setPlayerModel(prev) + notify.error('Favorit umschalten fehlgeschlagen', e?.message ?? String(e)) + } finally { + delete flagsInFlightRef.current[guardKey] + } + }, + [notify, playerJob, playerModel, resolveModelForJob, patchModelFlags, upsertModelCache, removeModelCache, modelsByKey] + ) + + + // ✅ handleToggleLike (komplett) + const handleToggleLike = useCallback( + async (job: RecordJob) => { + const file = baseName(job.output || '') + const sameAsPlayer = Boolean(playerJob && baseName(playerJob.output || '') === file) + + const hostFromJob = (j: RecordJob): string => { + try { + const urlFromJob = String((j as any).sourceUrl ?? (j as any).SourceURL ?? '') + const u = extractFirstUrl(urlFromJob) + if (!u) return '' + return new URL(u).hostname.replace(/^www\./i, '').toLowerCase() + } catch { + return '' + } + } + + const keyFromFile = (modelKeyFromFilename(job.output || '') || '').trim().toLowerCase() + if (keyFromFile) { + const guardKey = keyFromFile + if (flagsInFlightRef.current[guardKey]) return + flagsInFlightRef.current[guardKey] = true + + const prev = + modelsByKey[keyFromFile] ?? + ({ + id: '', + input: '', + host: hostFromJob(job) || undefined, + modelKey: keyFromFile, + watching: false, + favorite: false, + liked: null, + isUrl: false, + } as StoredModel) + + const nextLiked = !(prev.liked === true) + + const optimistic: StoredModel = { + ...prev, + modelKey: prev.modelKey || keyFromFile, + liked: nextLiked, + favorite: nextLiked ? false : prev.favorite, + } + + setModelsByKey((p) => ({ ...p, [keyFromFile]: optimistic })) + upsertModelCache(optimistic) + if (sameAsPlayer) setPlayerModel(optimistic) + + try { + const updated = await patchModelFlags({ + ...(optimistic.id ? { id: optimistic.id } : {}), + host: optimistic.host || hostFromJob(job) || '', + modelKey: keyFromFile, + liked: nextLiked, + ...(nextLiked ? { favorite: false } : {}), + }) + + if (!updated) { + setModelsByKey((p) => { + const { [keyFromFile]: _drop, ...rest } = p + return rest + }) + if (prev.id) removeModelCache(prev.id) + if (sameAsPlayer) setPlayerModel(null) + window.dispatchEvent( + new CustomEvent('models-changed', { detail: { removed: true, id: prev.id, modelKey: keyFromFile } }) + ) + return + } + + const k = lower(updated.modelKey || keyFromFile) + if (k) setModelsByKey((p) => ({ ...p, [k]: updated })) + upsertModelCache(updated) + if (sameAsPlayer) setPlayerModel(updated) + window.dispatchEvent(new CustomEvent('models-changed', { detail: { model: updated } })) + } catch (e: any) { + setModelsByKey((p) => ({ ...p, [keyFromFile]: prev })) + upsertModelCache(prev) + if (sameAsPlayer) setPlayerModel(prev) + notify.error('Like umschalten fehlgeschlagen', e?.message ?? String(e)) + } finally { + delete flagsInFlightRef.current[guardKey] + } + + return + } + + // fallback + let m = sameAsPlayer ? playerModel : null + if (!m) m = await resolveModelForJob(job, { ensure: true }) + if (!m) return + + const guardKey = lower(m.modelKey || m.id || '') + if (!guardKey) return + + if (flagsInFlightRef.current[guardKey]) return + flagsInFlightRef.current[guardKey] = true + + const prev = m + const nextLiked = !(prev.liked === true) + + const optimistic: StoredModel = { + ...prev, + liked: nextLiked, + favorite: nextLiked ? false : prev.favorite, + } + + const kPrev = lower(prev.modelKey || '') + if (kPrev) setModelsByKey((p) => ({ ...p, [kPrev]: optimistic })) + upsertModelCache(optimistic) + if (sameAsPlayer) setPlayerModel(optimistic) + + try { + const updated = nextLiked + ? await patchModelFlags({ id: prev.id, liked: true, favorite: false }) + : await patchModelFlags({ id: prev.id, liked: false }) + + if (!updated) { + setModelsByKey((p) => { + const k = lower(prev.modelKey || '') + if (!k) return p + const { [k]: _drop, ...rest } = p + return rest + }) + removeModelCache(prev.id) + if (sameAsPlayer) setPlayerModel(null) + window.dispatchEvent( + new CustomEvent('models-changed', { detail: { removed: true, id: prev.id, modelKey: prev.modelKey } }) + ) + return + } + + const k = lower(updated.modelKey || '') + if (k) setModelsByKey((p) => ({ ...p, [k]: updated })) + upsertModelCache(updated) + if (sameAsPlayer) setPlayerModel(updated) + window.dispatchEvent(new CustomEvent('models-changed', { detail: { model: updated } })) + } catch (e: any) { + const k = lower(prev.modelKey || '') + if (k) setModelsByKey((p) => ({ ...p, [k]: prev })) + upsertModelCache(prev) + if (sameAsPlayer) setPlayerModel(prev) + notify.error('Like umschalten fehlgeschlagen', e?.message ?? String(e)) + } finally { + delete flagsInFlightRef.current[guardKey] + } + }, + [notify, playerJob, playerModel, resolveModelForJob, patchModelFlags, upsertModelCache, removeModelCache, modelsByKey] + ) + + + // ✅ handleToggleWatch (komplett) + const handleToggleWatch = useCallback( + async (job: RecordJob) => { + const file = baseName(job.output || '') + const sameAsPlayer = Boolean(playerJob && baseName(playerJob.output || '') === file) + + const hostFromJob = (j: RecordJob): string => { + try { + const urlFromJob = String((j as any).sourceUrl ?? (j as any).SourceURL ?? '') + const u = extractFirstUrl(urlFromJob) + if (!u) return '' + return new URL(u).hostname.replace(/^www\./i, '').toLowerCase() + } catch { + return '' + } + } + + const keyFromFile = (modelKeyFromFilename(job.output || '') || '').trim().toLowerCase() + if (keyFromFile) { + const guardKey = keyFromFile + if (flagsInFlightRef.current[guardKey]) return + flagsInFlightRef.current[guardKey] = true + + const prev = + modelsByKey[keyFromFile] ?? + ({ + id: '', + input: '', + host: hostFromJob(job) || undefined, + modelKey: keyFromFile, + watching: false, + favorite: false, + liked: null, + isUrl: false, + } as StoredModel) + + const nextWatching = !Boolean(prev.watching) + + const optimistic: StoredModel = { + ...prev, + modelKey: prev.modelKey || keyFromFile, + watching: nextWatching, + } + + setModelsByKey((p) => ({ ...p, [keyFromFile]: optimistic })) + upsertModelCache(optimistic) + if (sameAsPlayer) setPlayerModel(optimistic) + + try { + const updated = await patchModelFlags({ + ...(optimistic.id ? { id: optimistic.id } : {}), + host: optimistic.host || hostFromJob(job) || '', + modelKey: keyFromFile, + watched: nextWatching, // ✅ API key watched => watching in DB + }) + + if (!updated) { + setModelsByKey((p) => { + const { [keyFromFile]: _drop, ...rest } = p + return rest + }) + if (prev.id) removeModelCache(prev.id) + if (sameAsPlayer) setPlayerModel(null) + window.dispatchEvent( + new CustomEvent('models-changed', { detail: { removed: true, id: prev.id, modelKey: keyFromFile } }) + ) + return + } + + const k = lower(updated.modelKey || keyFromFile) + if (k) setModelsByKey((p) => ({ ...p, [k]: updated })) + upsertModelCache(updated) + if (sameAsPlayer) setPlayerModel(updated) + window.dispatchEvent(new CustomEvent('models-changed', { detail: { model: updated } })) + } catch (e: any) { + setModelsByKey((p) => ({ ...p, [keyFromFile]: prev })) + upsertModelCache(prev) + if (sameAsPlayer) setPlayerModel(prev) + notify.error('Watched umschalten fehlgeschlagen', e?.message ?? String(e)) + } finally { + delete flagsInFlightRef.current[guardKey] + } + + return + } + + // fallback + let m = sameAsPlayer ? playerModel : null + if (!m) m = await resolveModelForJob(job, { ensure: true }) + if (!m) return + + const guardKey = lower(m.modelKey || m.id || '') + if (!guardKey) return + + if (flagsInFlightRef.current[guardKey]) return + flagsInFlightRef.current[guardKey] = true + + const prev = m + const nextWatching = !Boolean(prev.watching) + + const optimistic: StoredModel = { + ...prev, + watching: nextWatching, + } + + const kPrev = lower(prev.modelKey || '') + if (kPrev) setModelsByKey((p) => ({ ...p, [kPrev]: optimistic })) + upsertModelCache(optimistic) + if (sameAsPlayer) setPlayerModel(optimistic) + + try { + const updated = await patchModelFlags({ id: prev.id, watched: nextWatching }) + + if (!updated) { + setModelsByKey((p) => { + const k = lower(prev.modelKey || '') + if (!k) return p + const { [k]: _drop, ...rest } = p + return rest + }) + removeModelCache(prev.id) + if (sameAsPlayer) setPlayerModel(null) + window.dispatchEvent( + new CustomEvent('models-changed', { detail: { removed: true, id: prev.id, modelKey: prev.modelKey } }) + ) + return + } + + const k = lower(updated.modelKey || '') + if (k) setModelsByKey((p) => ({ ...p, [k]: updated })) + upsertModelCache(updated) + if (sameAsPlayer) setPlayerModel(updated) + window.dispatchEvent(new CustomEvent('models-changed', { detail: { model: updated } })) + } catch (e: any) { + const k = lower(prev.modelKey || '') + if (k) setModelsByKey((p) => ({ ...p, [k]: prev })) + upsertModelCache(prev) + if (sameAsPlayer) setPlayerModel(prev) + notify.error('Watched umschalten fehlgeschlagen', e?.message ?? String(e)) + } finally { + delete flagsInFlightRef.current[guardKey] + } + }, + [notify, playerJob, playerModel, resolveModelForJob, patchModelFlags, upsertModelCache, removeModelCache, modelsByKey] + ) async function resolveModelForJob( job: RecordJob, @@ -564,11 +1522,78 @@ export default function App() { else cur.list.unshift(m) } - const urlFromJob = ((job as any).sourceUrl ?? (job as any).SourceURL ?? '') as string - const url = extractFirstHttpUrl(urlFromJob) + const resolveByKey = async (key: string): Promise => { + if (!key) return null - // 1) Wenn URL da ist: parse + upsert - if (url) { + const needle = key.trim().toLowerCase() + if (!needle) return null + + // ✅ 0) Sofort aus App-State (schnellster Pfad) + const stateHit = modelsByKey[needle] + if (stateHit) { + upsertCache(stateHit) + return stateHit + } + + // ✅ 1) Wenn ensure gewünscht: DIREKT ensure (kein /api/models/list) + if (wantEnsure) { + let host: string | undefined + + // versuche Host aus sourceUrl zu nehmen (falls vorhanden) + try { + const urlFromJob = ((job as any).sourceUrl ?? (job as any).SourceURL ?? '') as string + const url = extractFirstUrl(urlFromJob) + if (url) host = new URL(url).hostname.replace(/^www\./i, '').toLowerCase() + } catch {} + + const ensured = await apiJSON('/api/models/ensure', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ modelKey: key, ...(host ? { host } : {}) }), + }) + upsertModelCache(ensured) + return ensured + } + + // ✅ 2) Cache refreshen / initial füllen (nur wenn KEIN ensure) + const now = Date.now() + const cached = modelsCacheRef.current + + if (!cached || now - cached.ts > 30_000) { + // erst aus State seeden (falls vorhanden) + const seeded = Object.values(modelsByKey) + if (seeded.length) { + modelsCacheRef.current = { ts: now, list: seeded } + } else { + const list = await apiJSON('/api/models/list', { cache: 'no-store' as any }) + modelsCacheRef.current = { ts: now, list: Array.isArray(list) ? list : [] } + } + } + + const list = modelsCacheRef.current?.list ?? [] + + // ✅ 3) im Cache suchen + const hit = list.find((m) => (m.modelKey || '').trim().toLowerCase() === needle) + if (hit) return hit + + return null + } + + const keyFromFile = modelKeyFromFilename(job.output || '') + + // ✅ Wichtig: IMMER zuerst Dateiname (auch bei running) + // -> spart /parse + /upsert und macht Toggle instant + if (keyFromFile) { + return resolveByKey(keyFromFile) + } + + const isRunning = job.status === 'running' + + // ✅ Nur wenn wir wirklich KEINEN Key aus dem Output haben: + const urlFromJob = ((job as any).sourceUrl ?? (job as any).SourceURL ?? '') as string + const url = extractFirstUrl(urlFromJob) + + if (isRunning && url) { const parsed = await apiJSON('/api/models/parse', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -581,210 +1606,15 @@ export default function App() { body: JSON.stringify(parsed), }) - upsertCache(saved) + upsertModelCache(saved) return saved } - // 2) Fallback: modelKey aus Dateiname - const key = modelKeyFromFilename(job.output || '') - if (!key) return null - - // Cache laden/auffrischen (nur fürs schnelle Match) - const now = Date.now() - const cached = modelsCacheRef.current - if (!cached || now - cached.ts > 30_000) { - const list = await apiJSON('/api/models/list', { cache: 'no-store' as any }) - modelsCacheRef.current = { ts: now, list: Array.isArray(list) ? list : [] } - } - - const list = modelsCacheRef.current?.list ?? [] - const needle = key.toLowerCase() - - const hits = list.filter((m) => (m.modelKey || '').toLowerCase() === needle) - if (hits.length > 0) { - return hits.sort((a, b) => Number(Boolean(b.favorite)) - Number(Boolean(a.favorite)))[0] - } - - // ✅ Wenn QuickAction: Model bei Bedarf anlegen - if (!wantEnsure) return null - - const ensured = await apiJSON('/api/models/ensure', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ modelKey: key }), - }) - - upsertCache(ensured) - return ensured + // Fallback: wenn gar nix geht + return null } - - useEffect(() => { - let cancelled = false - if (!playerJob) { - setPlayerModel(null) - return - } - - ;(async () => { - try { - const m = await resolveModelForJob(playerJob) - if (!cancelled) setPlayerModel(m) - } catch { - if (!cancelled) setPlayerModel(null) - } - })() - - return () => { cancelled = true } - }, [playerJob]) - - - async function onStart() { - return startUrl(sourceUrl) - } - - const handleDeleteJob = useCallback(async (job: RecordJob) => { - const file = baseName(job.output || '') - if (!file) return - - // 1) Animation START im FinishedDownloads triggern - window.dispatchEvent( - new CustomEvent('finished-downloads:delete', { - detail: { file, phase: 'start' as const }, - }) - ) - - try { - await apiJSON(`/api/record/delete?file=${encodeURIComponent(file)}`, { method: 'POST' }) - - // 2) Animation SUCCESS triggern (FinishedDownloads startet fade-out) - window.dispatchEvent( - new CustomEvent('finished-downloads:delete', { - detail: { file, phase: 'success' as const }, - }) - ) - - // 3) erst NACH der Animation wirklich aus den Arrays entfernen - window.setTimeout(() => { - setDoneJobs((prev) => prev.filter((j) => baseName(j.output || '') !== file)) - setJobs((prev) => prev.filter((j) => baseName(j.output || '') !== file)) - setPlayerJob((prev) => (prev && baseName(prev.output || '') === file ? null : prev)) - }, 320) - } catch (e) { - window.dispatchEvent( - new CustomEvent('finished-downloads:delete', { - detail: { file, phase: 'error' as const }, - }) - ) - throw e - } - }, []) - - const handleKeepJob = useCallback(async (job: RecordJob) => { - const file = baseName(job.output || '') - if (!file) return - - // 1) gleiche Animation wie Delete (fade-out + Nachrücken) - window.dispatchEvent( - new CustomEvent('finished-downloads:delete', { - detail: { file, phase: 'start' as const }, - }) - ) - - try { - await apiJSON(`/api/record/keep?file=${encodeURIComponent(file)}`, { method: 'POST' }) - - window.dispatchEvent( - new CustomEvent('finished-downloads:delete', { - detail: { file, phase: 'success' as const }, - }) - ) - - window.setTimeout(() => { - setDoneJobs((prev) => prev.filter((j) => baseName(j.output || '') !== file)) - setJobs((prev) => prev.filter((j) => baseName(j.output || '') !== file)) - setPlayerJob((prev) => (prev && baseName(prev.output || '') === file ? null : prev)) - }, 320) - - // Wenn Finished-Tab gerade NICHT offen ist, Counts/Liste trotzdem direkt updaten: - if (selectedTab !== 'finished') void refreshDoneNow() - } catch (e) { - window.dispatchEvent( - new CustomEvent('finished-downloads:delete', { - detail: { file, phase: 'error' as const }, - }) - ) - throw e - } - }, [selectedTab, refreshDoneNow]) - - const handleToggleHot = useCallback(async (job: RecordJob) => { - const file = baseName(job.output || '') - if (!file) return - - const res = await apiJSON<{ ok: boolean; oldFile: string; newFile: string }>( - `/api/record/toggle-hot?file=${encodeURIComponent(file)}`, - { method: 'POST' } - ) - - const newOutput = replaceBasename(job.output || '', res.newFile) - - setPlayerJob(prev => (prev ? { ...prev, output: newOutput } : prev)) - setDoneJobs(prev => prev.map(j => baseName(j.output || '') === file ? { ...j, output: replaceBasename(j.output || '', res.newFile) } : j)) - setJobs(prev => prev.map(j => baseName(j.output || '') === file ? { ...j, output: replaceBasename(j.output || '', res.newFile) } : j)) - }, []) - - async function patchModelFlags(patch: any) { - return apiJSON('/api/models/flags', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(patch), - }) - } - - const handleToggleFavorite = useCallback( - async (job: RecordJob) => { - const file = baseName(job.output || '') - const sameAsPlayer = Boolean(playerJob && baseName(playerJob.output || '') === file) - - let m = sameAsPlayer ? playerModel : null - if (!m) m = await resolveModelForJob(job, { ensure: true }) - if (!m) return - - const next = !Boolean(m.favorite) - - const updated = await patchModelFlags({ - id: m.id, - favorite: next, - ...(next ? { clearLiked: true } : {}), // ✅ wie ModelsTab - }) - - if (sameAsPlayer) setPlayerModel(updated) - window.dispatchEvent(new Event('models-changed')) - }, - [playerJob, playerModel] - ) - - const handleToggleLike = useCallback( - async (job: RecordJob) => { - const file = baseName(job.output || '') - const sameAsPlayer = Boolean(playerJob && baseName(playerJob.output || '') === file) - - let m = sameAsPlayer ? playerModel : null - if (!m) m = await resolveModelForJob(job, { ensure: true }) - if (!m) return - - const curLiked = m.liked === true - const updated = curLiked - ? await patchModelFlags({ id: m.id, clearLiked: true }) // ✅ aus - : await patchModelFlags({ id: m.id, liked: true, favorite: false }) // ✅ an + fav aus - - if (sameAsPlayer) setPlayerModel(updated) - window.dispatchEvent(new Event('models-changed')) - }, - [playerJob, playerModel] - ) - + // Clipboard auto add/start (wie bei dir) useEffect(() => { if (!autoAddEnabled && !autoStartEnabled) return if (!navigator.clipboard?.readText) return @@ -798,16 +1628,14 @@ export default function App() { inFlight = true try { const text = await navigator.clipboard.readText() - const url = extractFirstHttpUrl(text) + const url = extractFirstUrl(text) if (!url) return - + if (!getProviderFromNormalizedUrl(url)) return if (url === lastClipboardUrlRef.current) return lastClipboardUrlRef.current = url - // Auto-Add: Input befüllen if (autoAddEnabled) setSourceUrl(url) - // Auto-Start: sofort starten oder merken, wenn busy if (autoStartEnabled) { if (busyRef.current) { pendingStartUrlRef.current = url @@ -817,7 +1645,7 @@ export default function App() { } } } catch { - // In Browsern kann readText im Hintergrund/ohne Permission failen -> ignorieren + // ignore } finally { inFlight = false } @@ -827,13 +1655,12 @@ export default function App() { if (cancelled) return timer = window.setTimeout(async () => { await checkClipboard() - // Hintergrund weniger aggressiv pollen schedule(document.hidden ? 5000 : 1500) }, ms) } const kick = () => void checkClipboard() - window.addEventListener('focus', kick) + window.addEventListener('hover', kick) document.addEventListener('visibilitychange', kick) schedule(0) @@ -841,7 +1668,7 @@ export default function App() { return () => { cancelled = true if (timer) window.clearTimeout(timer) - window.removeEventListener('focus', kick) + window.removeEventListener('hover', kick) document.removeEventListener('visibilitychange', kick) } }, [autoAddEnabled, autoStartEnabled, startUrl]) @@ -855,153 +1682,381 @@ export default function App() { void startUrl(pending) }, [busy, autoStartEnabled, startUrl]) - async function stopJob(id: string) { - try { - await apiJSON(`/api/record/stop?id=${encodeURIComponent(id)}`, { method: 'POST' }) - } catch (e: any) { - setError(e?.message ?? String(e)) - } - } + useEffect(() => { + const stop = startChaturbateOnlinePolling({ + getModels: () => { + if (!recSettingsRef.current.useChaturbateApi) return [] + + const modelsMap = modelsByKeyRef.current + const pendingMap = pendingAutoStartByKeyRef.current + + const watchedKeysLower = Object.values(modelsMap) + .filter((m) => Boolean(m?.watching) && String(m?.host ?? '').toLowerCase().includes('chaturbate')) + .map((m) => String(m?.modelKey ?? '').trim().toLowerCase()) + .filter(Boolean) + + const queuedKeysLower = Object.keys(pendingMap || {}) + .map((k) => String(k || '').trim().toLowerCase()) + .filter(Boolean) + + // ✅ NUR watched + queued pollen (Store kann riesig sein -> lag) + // Wenn du Store-Online später willst: extra, seltener Poll (z.B. 60s) separat lösen. + return Array.from(new Set([...watchedKeysLower, ...queuedKeysLower])) + }, + + getShow: () => ['public', 'private', 'hidden', 'away'], + + intervalMs: 12000, + + onData: (data: ChaturbateOnlineResponse) => { + void (async () => { + if (!data?.enabled) { + setCbOnlineByKeyLower({}) + cbOnlineByKeyLowerRef.current = {} + setOnlineStoreKeysLower({}) + setPendingWatchedRooms([]) + setLastHeaderUpdateAtMs(Date.now()) + return + } + + const nextSnap: Record = {} + for (const r of Array.isArray(data.rooms) ? data.rooms : []) { + const u = String(r?.username ?? '').trim().toLowerCase() + if (u) nextSnap[u] = r + } + + setCbOnlineByKeyLower(nextSnap) + cbOnlineByKeyLowerRef.current = nextSnap + + // Online-Keys für Store + const storeKeys = chaturbateStoreKeysLowerRef.current + const nextOnlineStore: Record = {} + for (const k of storeKeys || []) { + const kl = String(k || '').trim().toLowerCase() + if (kl && nextSnap[kl]) nextOnlineStore[kl] = true + } + setOnlineStoreKeysLower(nextOnlineStore) + + // Pending Watched Rooms (nur im running Tab) + if (!recSettingsRef.current.useChaturbateApi) { + setPendingWatchedRooms([]) + } else if (selectedTabRef.current !== 'running') { + // optional: nicht leeren + } else { + const modelsMap = modelsByKeyRef.current + const pendingMap = pendingAutoStartByKeyRef.current + + const watchedKeysLower = Array.from( + new Set( + Object.values(modelsMap) + .filter((m) => Boolean(m?.watching) && String(m?.host ?? '').toLowerCase().includes('chaturbate')) + .map((m) => String(m?.modelKey ?? '').trim().toLowerCase()) + .filter(Boolean) + ) + ) + + const queuedKeysLower = Object.keys(pendingMap || {}) + .map((k) => String(k || '').trim().toLowerCase()) + .filter(Boolean) + + const queuedSetLower = new Set(queuedKeysLower) + const keysToCheckLower = Array.from(new Set([...watchedKeysLower, ...queuedKeysLower])) + + if (keysToCheckLower.length === 0) { + setPendingWatchedRooms([]) + } else { + const nextPending: PendingWatchedRoom[] = [] + + for (const keyLower of keysToCheckLower) { + const room = nextSnap[keyLower] + if (!room) continue + + const username = String(room?.username ?? '').trim() + const currentShow = String(room?.current_show ?? 'unknown') + + if (currentShow === 'public' && !queuedSetLower.has(keyLower)) continue + + const canonicalUrl = `https://chaturbate.com/${(username || keyLower).trim()}/` + + nextPending.push({ + id: keyLower, + modelKey: username || keyLower, + url: canonicalUrl, + currentShow, + imageUrl: String((room as any)?.image_url ?? ''), + }) + } + + nextPending.sort((a, b) => a.modelKey.localeCompare(b.modelKey, undefined, { sensitivity: 'base' })) + setPendingWatchedRooms(nextPending) + } + } + + // queued auto-start + if (!recSettingsRef.current.useChaturbateApi) return + if (busyRef.current) return + + const pendingMap = pendingAutoStartByKeyRef.current + const keys = Object.keys(pendingMap || {}) + .map((k) => String(k || '').toLowerCase()) + .filter(Boolean) + + for (const kLower of keys) { + const room = nextSnap[kLower] + if (!room) continue + if (String(room.current_show ?? '') !== 'public') continue + + const url = pendingMap[kLower] + if (!url) continue + + const ok = await startUrl(url, { silent: true }) + if (ok) { + // ✅ State + Ref gleichzeitig “synchron” löschen + setPendingAutoStartByKey((prev) => { + const copy = { ...(prev || {}) } + delete copy[kLower] + pendingAutoStartByKeyRef.current = copy + return copy + }) + } + } + + setLastHeaderUpdateAtMs(Date.now()) + })() + }, + }) + + return () => stop() + }, []) return ( -
- -

- Recorder -

-
- - +
+
+ + + +
+ + +
+ + +
+
+ + setSourceUrl(e.target.value)} + placeholder="https://…" + className="block w-full rounded-lg px-3 py-2.5 text-sm bg-white text-gray-900 shadow-sm ring-1 ring-gray-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:bg-white/10 dark:text-white dark:ring-white/10" + /> +
+ +
- - } - > - - setSourceUrl(e.target.value)} - placeholder="https://…" - className="mt-1 block w-full rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white" - /> - {error ? ( -
-
-
{error}
- + {error ? ( +
+
+
{error}
+ +
+
+ ) : null} + + {isChaturbate(sourceUrl) && !hasRequiredChaturbateCookies(cookies) ? ( +
+ ⚠️ Für Chaturbate werden die Cookies cf_clearance und sessionId benötigt. +
+ ) : null} + + {busy ? ( +
+ +
+ ) : null} + +
+
+ + +
+
+ +
+
+ +
+ {selectedTab === 'running' ? ( + + ) : null} + + {selectedTab === 'finished' ? ( + { + setDoneSort(m) + setDonePage(1) + }} + onRefreshDone={refreshDoneNow} + /> + ) : null} + + {selectedTab === 'models' ? : null} + {selectedTab === 'settings' ? : null} +
+ + setCookieModalOpen(false)} + initialCookies={initialCookies} + onApply={(list) => { + const normalized = normalizeCookies(Object.fromEntries(list.map((c) => [c.name, c.value] as const))) + setCookies(normalized) + + void apiJSON('/api/cookies', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ cookies: normalized }), + }).catch(() => {}) + }} + /> + + {playerJob ? ( + setPlayerExpanded((s) => !s)} + onClose={() => setPlayerJob(null)} + isHot={baseName(playerJob.output || '').startsWith('HOT ')} + isFavorite={Boolean(playerModel?.favorite)} + isLiked={playerModel?.liked === true} + isWatching={Boolean(playerModel?.watching)} + onKeep={handleKeepJob} + onDelete={handleDeleteJob} + onToggleHot={handleToggleHot} + onToggleFavorite={handleToggleFavorite} + onToggleLike={handleToggleLike} + onStopJob={stopJob} + onToggleWatch={handleToggleWatch} + /> ) : null} - {isChaturbate(sourceUrl) && !hasRequiredChaturbateCookies(cookies) && ( -
- ⚠️ Für Chaturbate werden die Cookies cf_clearance und{' '} - sessionId benötigt. -
- )} - - {busy ? ( -
- -
- ) : null} - - - - - - {selectedTab === 'running' && ( - setDetailsModelKey(null)} onOpenPlayer={openPlayer} - onStopJob={stopJob} - blurPreviews={Boolean(recSettings.blurPreviews)} + runningJobs={runningJobs} + cookies={cookies} + blurPreviews={recSettings.blurPreviews} /> - )} - - {selectedTab === 'finished' && ( - - )} - - {selectedTab === 'models' && } - - {selectedTab === 'settings' && } - - setCookieModalOpen(false)} - initialCookies={initialCookies} - onApply={(list) => { - const normalized = normalizeCookies( - Object.fromEntries(list.map((c) => [c.name, c.value] as const)) - ) - setCookies(normalized) - - // Persist encrypted in recorder_settings.json via backend - void apiJSON('/api/cookies', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ cookies: normalized }), - }).catch(() => { - // keep UI usable; backend persistence failed - }) - }} - /> - - {playerJob && ( - setPlayerExpanded((s) => !s)} - onClose={() => setPlayerJob(null)} - isHot={baseName(playerJob.output || '').startsWith('HOT ')} - isFavorite={Boolean(playerModel?.favorite)} - isLiked={playerModel?.liked === true} - onKeep={handleKeepJob} - onDelete={handleDeleteJob} - onToggleHot={handleToggleHot} - onToggleFavorite={handleToggleFavorite} - onToggleLike={handleToggleLike} - /> - )} +
) } diff --git a/frontend/src/components/ui/Button.tsx b/frontend/src/components/ui/Button.tsx index 8e08c64..57684dd 100644 --- a/frontend/src/components/ui/Button.tsx +++ b/frontend/src/components/ui/Button.tsx @@ -42,8 +42,8 @@ const sizeMap: Record = { const colorMap: Record> = { indigo: { primary: - 'bg-indigo-600 text-white shadow-xs hover:bg-indigo-500 focus-visible:outline-indigo-600 ' + - 'dark:bg-indigo-500 dark:shadow-none dark:hover:bg-indigo-400 dark:focus-visible:outline-indigo-500', + '!bg-indigo-600 !text-white shadow-sm hover:!bg-indigo-700 focus-visible:outline-indigo-600 ' + + 'dark:!bg-indigo-500 dark:hover:!bg-indigo-400 dark:focus-visible:outline-indigo-500', secondary: 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', @@ -51,10 +51,11 @@ const colorMap: Record> = { 'bg-indigo-50 text-indigo-600 shadow-xs hover:bg-indigo-100 ' + 'dark:bg-indigo-500/20 dark:text-indigo-400 dark:shadow-none dark:hover:bg-indigo-500/30', }, + blue: { primary: - 'bg-blue-600 text-white shadow-xs hover:bg-blue-500 focus-visible:outline-blue-600 ' + - 'dark:bg-blue-500 dark:shadow-none dark:hover:bg-blue-400 dark:focus-visible:outline-blue-500', + '!bg-blue-600 !text-white shadow-sm hover:!bg-blue-700 focus-visible:outline-blue-600 ' + + 'dark:!bg-blue-500 dark:hover:!bg-blue-400 dark:focus-visible:outline-blue-500', secondary: 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', @@ -62,10 +63,11 @@ const colorMap: Record> = { 'bg-blue-50 text-blue-600 shadow-xs hover:bg-blue-100 ' + 'dark:bg-blue-500/20 dark:text-blue-400 dark:shadow-none dark:hover:bg-blue-500/30', }, + emerald: { primary: - 'bg-emerald-600 text-white shadow-xs hover:bg-emerald-500 focus-visible:outline-emerald-600 ' + - 'dark:bg-emerald-500 dark:shadow-none dark:hover:bg-emerald-400 dark:focus-visible:outline-emerald-500', + '!bg-emerald-600 !text-white shadow-sm hover:!bg-emerald-700 focus-visible:outline-emerald-600 ' + + 'dark:!bg-emerald-500 dark:hover:!bg-emerald-400 dark:focus-visible:outline-emerald-500', secondary: 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', @@ -73,10 +75,11 @@ const colorMap: Record> = { 'bg-emerald-50 text-emerald-700 shadow-xs hover:bg-emerald-100 ' + 'dark:bg-emerald-500/20 dark:text-emerald-400 dark:shadow-none dark:hover:bg-emerald-500/30', }, + red: { primary: - 'bg-red-600 text-white shadow-xs hover:bg-red-500 focus-visible:outline-red-600 ' + - 'dark:bg-red-500 dark:shadow-none dark:hover:bg-red-400 dark:focus-visible:outline-red-500', + '!bg-red-600 !text-white shadow-sm hover:!bg-red-700 focus-visible:outline-red-600 ' + + 'dark:!bg-red-500 dark:hover:!bg-red-400 dark:focus-visible:outline-red-500', secondary: 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', @@ -84,10 +87,11 @@ const colorMap: Record> = { 'bg-red-50 text-red-700 shadow-xs hover:bg-red-100 ' + 'dark:bg-red-500/20 dark:text-red-400 dark:shadow-none dark:hover:bg-red-500/30', }, + amber: { primary: - 'bg-amber-500 text-white shadow-xs hover:bg-amber-400 focus-visible:outline-amber-500 ' + - 'dark:bg-amber-500 dark:shadow-none dark:hover:bg-amber-400 dark:focus-visible:outline-amber-500', + '!bg-amber-500 !text-white shadow-sm hover:!bg-amber-600 focus-visible:outline-amber-500 ' + + 'dark:!bg-amber-500 dark:hover:!bg-amber-400 dark:focus-visible:outline-amber-500', secondary: 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', @@ -100,8 +104,22 @@ const colorMap: Record> = { function Spinner() { return ( ) } diff --git a/frontend/src/components/ui/ButtonGroup.tsx b/frontend/src/components/ui/ButtonGroup.tsx index 24e61b5..ee1d959 100644 --- a/frontend/src/components/ui/ButtonGroup.tsx +++ b/frontend/src/components/ui/ButtonGroup.tsx @@ -57,30 +57,36 @@ export default function ButtonGroup({ onClick={() => onChange(it.id)} aria-pressed={active} className={cn( - 'relative inline-flex items-center font-semibold focus:z-10', + 'relative inline-flex items-center justify-center font-semibold focus:z-10 transition-colors', !isFirst && '-ml-px', isFirst && 'rounded-l-md', isLast && 'rounded-r-md', - // Base (wie im TailwindUI Beispiel) - 'bg-white text-gray-900 inset-ring-1 inset-ring-gray-300 hover:bg-gray-50', - 'dark:bg-white/10 dark:text-white dark:inset-ring-gray-700 dark:hover:bg-white/20', - - // Active-Style (dezente Hervorhebung) - active && 'bg-gray-50 dark:bg-white/20', + // Base vs Active: gegenseitig ausschließen (wichtig, sonst gewinnt oft bg-white) + active + ? 'bg-indigo-100 text-indigo-800 inset-ring-1 inset-ring-indigo-300 hover:bg-indigo-200 ' + + 'dark:bg-indigo-500/40 dark:text-indigo-100 dark:inset-ring-indigo-400/50 dark:hover:bg-indigo-500/50' + : 'bg-white text-gray-900 inset-ring-1 inset-ring-gray-300 hover:bg-gray-50 ' + + 'dark:bg-white/10 dark:text-white dark:inset-ring-gray-700 dark:hover:bg-white/20', // Disabled 'disabled:opacity-50 disabled:cursor-not-allowed', // Padding / Größe - iconOnly ? 'px-2 py-2 text-gray-400 dark:text-gray-300' : s.btn + iconOnly ? 'px-2 py-2' : s.btn )} title={typeof it.label === 'string' ? it.label : it.srLabel} > {iconOnly && it.srLabel ? {it.srLabel} : null} {it.icon ? ( - + {it.icon} ) : null} diff --git a/frontend/src/components/ui/CookieModal.tsx b/frontend/src/components/ui/CookieModal.tsx index 3ed71ad..6dcf3d2 100644 --- a/frontend/src/components/ui/CookieModal.tsx +++ b/frontend/src/components/ui/CookieModal.tsx @@ -71,13 +71,13 @@ export default function CookieModal({ value={name} onChange={(e) => setName(e.target.value)} placeholder="Name (z. B. cf_clearance)" - className="col-span-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white" + className="col-span-1 truncate rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white" /> setValue(e.target.value)} placeholder="Wert" - className="col-span-1 sm:col-span-2 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white" + className="col-span-1 truncate sm:col-span-2 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white" /> diff --git a/frontend/src/components/ui/Downloads.tsx b/frontend/src/components/ui/Downloads.tsx new file mode 100644 index 0000000..8388fa9 --- /dev/null +++ b/frontend/src/components/ui/Downloads.tsx @@ -0,0 +1,1109 @@ +// frontend\src\components\ui\Downloads.tsx +'use client' + +import { useMemo, useState, useCallback, useEffect } from 'react' +import Table, { type Column } from './Table' +import Card from './Card' +import Button from './Button' +import ModelPreview from './ModelPreview' +import type { RecordJob } from '../../types' +import ProgressBar from './ProgressBar' +import RecordJobActions from './RecordJobActions' +import { PauseIcon, PlayIcon } from '@heroicons/react/24/solid' +import { subscribeSSE } from '../../lib/sseSingleton' + +type PendingWatchedRoom = WaitingModelRow & { + currentShow: string // public / private / hidden / away / unknown +} + +type WaitingModelRow = { + id: string + modelKey: string + url: string + imageUrl?: string + currentShow?: string // public / private / hidden / away / unknown +} + +type AutostartState = { paused?: boolean } + +type Props = { + jobs: RecordJob[] + pending?: PendingWatchedRoom[] + modelsByKey?: Record + onOpenPlayer: (job: RecordJob) => void + onStopJob: (id: string) => void + blurPreviews?: boolean + onToggleFavorite?: (job: RecordJob) => void | Promise + onToggleLike?: (job: RecordJob) => void | Promise + onToggleWatch?: (job: RecordJob) => void | Promise +} + +type DownloadRow = + | { kind: 'job'; job: RecordJob } + | { kind: 'pending'; pending: PendingWatchedRoom } + +const pendingModelName = (p: PendingWatchedRoom) => { + const anyP = p as any + return ( + anyP.modelName ?? + anyP.model ?? + anyP.modelKey ?? + anyP.username ?? + anyP.name ?? + '—' + ) +} + +const pendingUrl = (p: PendingWatchedRoom) => { + const anyP = p as any + return anyP.sourceUrl ?? anyP.url ?? anyP.roomUrl ?? '' +} + +const pendingImageUrl = (p: PendingWatchedRoom) => { + const anyP = p as any + return String(anyP.imageUrl ?? anyP.image_url ?? '').trim() +} + +const pendingRowKey = (p: PendingWatchedRoom) => { + const anyP = p as any + return String(anyP.key ?? anyP.id ?? pendingModelName(p)) +} + +const toMs = (v: unknown): number => { + if (typeof v === 'number' && Number.isFinite(v)) { + // Heuristik: 10-stellige Unix-Sekunden -> ms + return v < 1_000_000_000_000 ? v * 1000 : v + } + if (typeof v === 'string') { + const ms = Date.parse(v) + return Number.isFinite(ms) ? ms : 0 + } + if (v instanceof Date) return v.getTime() + return 0 +} + +const addedAtMsOf = (r: DownloadRow): number => { + if (r.kind === 'job') { + const j = r.job as any + return ( + toMs(j.addedAt) || + toMs(j.createdAt) || + toMs(j.enqueuedAt) || + toMs(j.queuedAt) || + toMs(j.requestedAt) || + toMs(j.startedAt) || // Fallback + 0 + ) + } + + const p = r.pending as any + return ( + toMs(p.addedAt) || + toMs(p.createdAt) || + toMs(p.enqueuedAt) || + toMs(p.queuedAt) || + toMs(p.requestedAt) || + 0 + ) +} + +const phaseLabel = (p?: string) => { + switch (p) { + case 'stopping': + return 'Stop wird angefordert…' + case 'remuxing': + return 'Remux zu MP4…' + case 'moving': + return 'Verschiebe nach Done…' + case 'assets': + return 'Erstelle Vorschau…' + default: + return '' + } +} + +async function apiJSON(url: string, init?: RequestInit): Promise { + const res = await fetch(url, init) + if (!res.ok) { + const text = await res.text().catch(() => '') + throw new Error(text || `HTTP ${res.status}`) + } + return res.json() as Promise +} + +function StatusCell({ job }: { job: RecordJob }) { + const phaseRaw = String((job as any)?.phase ?? '').trim() + const progress = Number((job as any)?.progress ?? 0) + + const phaseText = phaseRaw ? (phaseLabel(phaseRaw) || phaseRaw) : '' + const text = phaseText || String((job as any)?.status ?? '').trim().toLowerCase() + + // ✅ ProgressBar unabhängig vom Text + // ✅ determinate nur wenn sinnvoll (0..100) + const showBar = Number.isFinite(progress) && progress > 0 && progress < 100 + + // ✅ wenn wir in einer Phase sind, aber noch kein Progress da ist -> indeterminate + const showIndeterminate = + !showBar && + Boolean(phaseRaw) && + (!Number.isFinite(progress) || progress <= 0 || progress >= 100) + + return ( +
+ {showBar ? ( + + ) : showIndeterminate ? ( + + ) : ( +
+ {text} +
+ )} +
+ ) +} + +function DownloadsCardRow({ + r, + nowMs, + blurPreviews, + modelsByKey, + stopRequestedIds, + markStopRequested, + onOpenPlayer, + onStopJob, + onToggleFavorite, + onToggleLike, + onToggleWatch, +}: { + r: DownloadRow + nowMs: number + blurPreviews?: boolean + modelsByKey: Record + stopRequestedIds: Record + markStopRequested: (ids: string | string[]) => void + onOpenPlayer: (job: RecordJob) => void + onStopJob: (id: string) => void + onToggleFavorite?: (job: RecordJob) => void | Promise + onToggleLike?: (job: RecordJob) => void | Promise + onToggleWatch?: (job: RecordJob) => void | Promise +}) { + // ---------- Pending ---------- + if (r.kind === 'pending') { + const p = r.pending + const name = pendingModelName(p) + const url = pendingUrl(p) + const show = (p.currentShow || 'unknown').toLowerCase() + + return ( +
+ {/* subtle gradient */} +
+ +
+
+
+
+ {name} +
+ +
+ + Wartend + + + {show} + +
+
+ + + ⏳ + +
+ +
+ {(() => { + const img = pendingImageUrl(p) + return ( +
+ {img ? ( + {name} { + ;(e.currentTarget as HTMLImageElement).style.display = "none" + }} + /> + ) : ( +
+
Waiting…
+
+ )} +
+ ) + })()} +
+ + {url ? ( + e.stopPropagation()} + title={url} + > + {url} + + ) : null} +
+
+ ) + } + + // ---------- Job ---------- + const j = r.job + const name = modelNameFromOutput(j.output) + const file = baseName(j.output || '') + + const phase = String((j as any).phase ?? '').trim() + const phaseText = phase ? (phaseLabel(phase) || phase) : '' + + const isStopRequested = Boolean(stopRequestedIds[j.id]) // nur UI-zwischenzustand + const rawStatus = String(j.status ?? '').toLowerCase() + + const isStopping = Boolean(phase) || rawStatus !== 'running' || isStopRequested + + // ✅ Badge hinter Modelname: IMMER Backend-Status + const statusText = rawStatus || 'unknown' + + // ✅ Progressbar Label: Phase (gemappt), fallback auf Status + const progressLabel = phaseText || statusText + + const progress = Number((j as any).progress ?? 0) + const showBar = Number.isFinite(progress) && progress > 0 && progress < 100 + const showIndeterminate = + !showBar && + Boolean(phase) && + (!Number.isFinite(progress) || progress <= 0 || progress >= 100) + + const key = name && name !== '—' ? name.toLowerCase() : '' + const flags = key ? modelsByKey[key] : undefined + const isFav = Boolean(flags?.favorite) + const isLiked = flags?.liked === true + const isWatching = Boolean(flags?.watching) + + return ( +
onOpenPlayer(j)} + role="button" + tabIndex={0} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onOpenPlayer(j) + }} + > + {/* subtle gradient */} +
+
+ +
+ {/* Header: kleines Preview links + Infos rechts */} +
+ {/* Thumbnail */} +
+ +
+ + {/* Infos */} +
+
+
+
+
+ {name} +
+ + + {statusText} + +
+
+ {file || '—'} +
+
+ +
+ + {runtimeOf(j, nowMs)} + + + {formatBytes(sizeBytesOf(j))} + +
+
+ + {j.sourceUrl ? ( + e.stopPropagation()} + title={j.sourceUrl} + > + {j.sourceUrl} + + ) : null} +
+
+ + {(showBar || showIndeterminate) ? ( +
+ {showBar ? ( + + ) : ( + + )} +
+ ) : null} + + {/* Footer */} +
+
e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + > + +
+ + +
+
+
+ ) +} + + + + +const baseName = (p: string) => + (p || '').replaceAll('\\', '/').trim().split('/').pop() || '' + +const modelNameFromOutput = (output?: string) => { + const file = baseName(output || '') + if (!file) return '—' + const stem = file.replace(/\.[^.]+$/, '') + + // _MM_DD_YYYY__HH-MM-SS + const m = stem.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/) + if (m?.[1]) return m[1] + + const i = stem.lastIndexOf('_') + return i > 0 ? stem.slice(0, i) : stem +} + +const formatDuration = (ms: number): string => { + if (!Number.isFinite(ms) || ms <= 0) return '—' + const total = Math.floor(ms / 1000) + const h = Math.floor(total / 3600) + const m = Math.floor((total % 3600) / 60) + const s = total % 60 + if (h > 0) return `${h}h ${m}m` + if (m > 0) return `${m}m ${s}s` + return `${s}s` +} + +const runtimeOf = (j: RecordJob, nowMs: number) => { + const start = Date.parse(String(j.startedAt || '')) + if (!Number.isFinite(start)) return '—' + const end = j.endedAt ? Date.parse(String(j.endedAt)) : nowMs + if (!Number.isFinite(end)) return '—' + return formatDuration(end - start) +} + +const sizeBytesOf = (job: RecordJob): number | null => { + const anyJob = job as any + const v = anyJob.sizeBytes ?? anyJob.fileSizeBytes ?? anyJob.bytes ?? anyJob.size ?? null + return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null +} + +const formatBytes = (bytes: number | null): string => { + if (!bytes || !Number.isFinite(bytes) || bytes <= 0) return '—' + const units = ['B', 'KB', 'MB', 'GB', 'TB'] + let v = bytes + let i = 0 + while (v >= 1024 && i < units.length - 1) { + v /= 1024 + i++ + } + const digits = i === 0 ? 0 : v >= 10 ? 1 : 2 + const s = v.toFixed(digits).replace(/\.0+$/, '') + return `${s} ${units[i]}` +} + + +export default function Downloads({ jobs, pending = [], onOpenPlayer, onStopJob, onToggleFavorite, onToggleLike, onToggleWatch, modelsByKey = {}, blurPreviews }: Props) { + + const [stopAllBusy, setStopAllBusy] = useState(false) + + const [watchedPaused, setWatchedPaused] = useState(false) + const [watchedBusy, setWatchedBusy] = useState(false) + + const refreshWatchedState = useCallback(async () => { + try { + const s = await apiJSON('/api/autostart/state', { cache: 'no-store' as any }) + setWatchedPaused(Boolean(s?.paused)) + } catch { + // wenn Endpoint (noch) nicht da ist: nichts kaputt machen + } + }, []) + + useEffect(() => { + // initial: einmal fetchen (schneller first paint) + void refreshWatchedState() + + // danach: Stream (Singleton) + const unsub = subscribeSSE( + '/api/autostart/state/stream', + 'autostart', + (data) => setWatchedPaused(Boolean((data as any)?.paused)) + ) + + return () => { + unsub() + } + }, [refreshWatchedState]) + + const pauseWatched = useCallback(async () => { + if (watchedBusy || watchedPaused) return + setWatchedBusy(true) + try { + await fetch('/api/autostart/pause', { method: 'POST' }) + setWatchedPaused(true) + } catch { + // ignore + } finally { + setWatchedBusy(false) + } + }, [watchedBusy, watchedPaused]) + + const resumeWatched = useCallback(async () => { + if (watchedBusy || !watchedPaused) return + setWatchedBusy(true) + try { + await fetch('/api/autostart/resume', { method: 'POST' }) + setWatchedPaused(false) + } catch { + // ignore + } finally { + setWatchedBusy(false) + } + }, [watchedBusy, watchedPaused]) + + // ✅ Merkt sich: für diese Jobs wurde "Stop" bereits angefordert (z.B. via "Alle stoppen") + const [stopRequestedIds, setStopRequestedIds] = useState>({}) + + // ✅ Merkt sich dauerhaft: Stop wurde vom User ausgelöst (damit wir später "Stopped" anzeigen können) + const [stopInitiatedIds, setStopInitiatedIds] = useState>({}) + + const markStopRequested = useCallback((ids: string | string[]) => { + const arr = Array.isArray(ids) ? ids : [ids] + + // UI-Zwischenzustand ("Stoppe…") + setStopRequestedIds((prev) => { + const next = { ...prev } + for (const id of arr) { + if (id) next[id] = true + } + return next + }) + + // dauerhaft merken: User hat Stop ausgelöst + setStopInitiatedIds((prev) => { + const next = { ...prev } + for (const id of arr) { + if (id) next[id] = true + } + return next + }) + }, []) + + // Cleanup: sobald Job nicht mehr "running ohne phase" ist, brauchen wir das Flag nicht mehr + useEffect(() => { + setStopRequestedIds((prev) => { + const keys = Object.keys(prev) + if (keys.length === 0) return prev + + const next: Record = {} + for (const id of keys) { + const j = jobs.find((x) => x.id === id) + if (!j) continue + const phase = String((j as any).phase ?? '').trim() + const isStopping = Boolean(phase) || j.status !== 'running' + if (!isStopping) next[id] = true + } + return next + }) + }, [jobs]) + + + const [nowMs, setNowMs] = useState(() => Date.now()) + + const hasActive = useMemo(() => { + // tickt solange mind. ein Job noch nicht beendet ist + return jobs.some((j) => !j.endedAt && j.status === 'running') + }, [jobs]) + + useEffect(() => { + if (!hasActive) return + const t = window.setInterval(() => setNowMs(Date.now()), 1000) + return () => window.clearInterval(t) + }, [hasActive]) + + const stoppableIds = useMemo(() => { + return jobs + .filter((j) => { + const phase = String((j as any).phase ?? '').trim() + const isStopRequested = Boolean(stopRequestedIds[j.id]) + const isStopping = Boolean(phase) || j.status !== 'running' || isStopRequested + return !isStopping + }) + .map((j) => j.id) + }, [jobs, stopRequestedIds]) + + const columns = useMemo[]>(() => { + return [ + { + key: 'preview', + header: 'Vorschau', + widthClassName: 'w-[96px]', + cell: (r) => { + if (r.kind === 'job') { + const j = r.job + return ( +
+ +
+ ) + } + + // pending: kein jobId → Platzhalter + const p = r.pending + const name = pendingModelName(p) + const img = pendingImageUrl(p) + + if (img) { + return ( +
+ {name} { + ;(e.currentTarget as HTMLImageElement).style.display = "none" + }} + /> +
+ ) + } + + return ( +
+ ⏳ +
+ ) + }, + }, + { + key: 'model', + header: 'Modelname', + widthClassName: 'w-[170px]', + cell: (r) => { + if (r.kind === 'job') { + const j = r.job + const f = baseName(j.output || '') + const name = modelNameFromOutput(j.output) + const phase = String((j as any).phase ?? '').trim() + + const isStopRequested = Boolean(stopRequestedIds[j.id]) + const stopInitiated = Boolean(stopInitiatedIds[j.id]) + const rawStatus = String(j.status ?? '').toLowerCase() + const isStoppedFinal = rawStatus === 'stopped' || (stopInitiated && Boolean(j.endedAt)) + + const isStopping = Boolean(phase) || rawStatus !== 'running' || isStopRequested + const statusText = rawStatus || 'unknown' + + return ( + <> +
+ + {name} + + + {statusText} + +
+ + {f} + + {j.sourceUrl ? ( + e.stopPropagation()} + > + {j.sourceUrl} + + ) : ( + + — + + )} + + ) + } + + const p = r.pending + const name = pendingModelName(p) + const url = pendingUrl(p) + + return ( + <> + + {name} + + {url ? ( + e.stopPropagation()} + > + {url} + + ) : ( + + — + + )} + + ) + }, + }, + { + key: 'status', + header: 'Status', + widthClassName: 'w-[260px] min-w-[240px]', + cell: (r) => { + if (r.kind === 'job') { + const j = r.job + return + } + + const p = r.pending + const show = (p.currentShow || 'unknown').toLowerCase() + + return ( +
+
+ + {show} + +
+
+ ) + }, + }, + { + key: 'runtime', + header: 'Dauer', + widthClassName: 'w-[90px]', + cell: (r) => { + if (r.kind === 'job') return runtimeOf(r.job, nowMs) + return '—' + }, + }, + { + key: 'size', + header: 'Größe', + align: 'right', + widthClassName: 'w-[110px]', + cell: (r) => { + if (r.kind === 'job') { + return ( + + {formatBytes(sizeBytesOf(r.job))} + + ) + } + return ( + + — + + ) + }, + }, + { + key: 'actions', + header: 'Aktion', + srOnlyHeader: true, + align: 'right', + widthClassName: 'w-[320px] min-w-[300px]', + cell: (r) => { + // actions nur für echte Jobs (Stop/Icons). Pending ist “read-only” in der Tabelle. + if (r.kind !== 'job') { + return
+ } + + const j = r.job + const phase = String((j as any).phase ?? '').trim() + const isStopRequested = Boolean(stopRequestedIds[j.id]) + const isStopping = Boolean(phase) || j.status !== 'running' || isStopRequested + + const key = modelNameFromOutput(j.output || '') + const flags = key && key !== '—' ? modelsByKey[key.toLowerCase()] : undefined + + const isFav = Boolean(flags?.favorite) + const isLiked = flags?.liked === true + const isWatching = Boolean(flags?.watching) + + return ( +
+ + + {(() => { + const phase = String((j as any).phase ?? '').trim() + const isStopRequested = Boolean(stopRequestedIds[j.id]) + const isStopping = Boolean(phase) || j.status !== 'running' || isStopRequested + + return ( + + ) + })()} +
+ ) + }, + }, + ] + }, [blurPreviews, markStopRequested, modelsByKey, nowMs, onStopJob, onToggleFavorite, onToggleLike, onToggleWatch, stopRequestedIds, stopInitiatedIds]) + + const hasAnyPending = pending.length > 0 + const hasJobs = jobs.length > 0 + + const rows = useMemo(() => { + const list: DownloadRow[] = [ + ...jobs.map((job) => ({ kind: 'job', job }) as const), + ...pending.map((p) => ({ kind: 'pending', pending: p }) as const), + ] + + // ✅ Neueste zuerst (Hinzugefügt am DESC) + list.sort((a, b) => addedAtMsOf(b) - addedAtMsOf(a)) + return list + }, [jobs, pending]) + + const stopAll = useCallback(async () => { + if (stopAllBusy) return + if (stoppableIds.length === 0) return + + setStopAllBusy(true) + try { + // UI sofort auf "Stoppe…" stellen + markStopRequested(stoppableIds) + + // Stop anfordern (parallel) + await Promise.allSettled(stoppableIds.map((id) => Promise.resolve(onStopJob(id)))) + } finally { + setStopAllBusy(false) + } + }, [stopAllBusy, stoppableIds, markStopRequested, onStopJob]) + + return ( +
+ {(hasAnyPending || hasJobs) ? ( + <> + {/* Toolbar (sticky) wie FinishedDownloads */} +
+
+
+ {/* Title + Count */} +
+
+ Downloads +
+ + {rows.length} + +
+ + {/* Actions + View */} +
+ + + +
+
+
+
+ + {/* Content */} + {/* Mobile: Cards */} +
+ {rows.map((r) => ( + + ))} +
+ + {/* Tablet/Desktop: Tabelle */} +
+ (r.kind === 'job' ? `job:${r.job.id}` : `pending:${pendingRowKey(r.pending)}`)} + striped + fullWidth + stickyHeader + compact={false} + card + onRowClick={(r) => { + if (r.kind === 'job') onOpenPlayer(r.job) + }} + /> + + + ) : null} + + {!hasAnyPending && !hasJobs ? ( + +
+
+ ⏸️ +
+
+
+ Keine laufenden Downloads +
+
+ Starte oben eine URL – hier siehst du Live-Status und kannst Jobs stoppen. +
+
+
+
+ ) : null} + + ) +} diff --git a/frontend/src/components/ui/FinishedDownloads.tsx b/frontend/src/components/ui/FinishedDownloads.tsx index 3b1aae2..4b87b0b 100644 --- a/frontend/src/components/ui/FinishedDownloads.tsx +++ b/frontend/src/components/ui/FinishedDownloads.tsx @@ -1,50 +1,64 @@ +// frontend\src\components\ui\FinishedDownloads.tsx + 'use client' import * as React from 'react' import { useMemo, useEffect, useCallback } from 'react' -import Table, { type Column, type SortState } from './Table' +import { type Column, type SortState } from './Table' import Card from './Card' import type { RecordJob } from '../../types' import FinishedVideoPreview from './FinishedVideoPreview' -import Button from './Button' import ButtonGroup from './ButtonGroup' -import { - TableCellsIcon, - RectangleStackIcon, - Squares2X2Icon, - TrashIcon, - FireIcon, - BookmarkSquareIcon, - StarIcon as StarOutlineIcon, - HeartIcon as HeartOutlineIcon, -} from '@heroicons/react/24/outline' -import { - StarIcon as StarSolidIcon, - HeartIcon as HeartSolidIcon, -} from '@heroicons/react/24/solid' -import SwipeCard, { type SwipeCardHandle } from './SwipeCard' +import { TableCellsIcon, RectangleStackIcon, Squares2X2Icon } from '@heroicons/react/24/outline' +import { type SwipeCardHandle } from './SwipeCard' import { flushSync } from 'react-dom' import FinishedDownloadsCardsView from './FinishedDownloadsCardsView' import FinishedDownloadsTableView from './FinishedDownloadsTableView' import FinishedDownloadsGalleryView from './FinishedDownloadsGalleryView' import Pagination from './Pagination' import { applyInlineVideoPolicy } from './videoPolicy' +import TagBadge from './TagBadge' +import RecordJobActions from './RecordJobActions' +import Button from './Button' +import { useNotify } from './notify' +import LazyMount from './LazyMount' + + +type SortMode = + | 'completed_desc' + | 'completed_asc' + | 'model_asc' + | 'model_desc' + | 'file_asc' + | 'file_desc' + | 'duration_desc' + | 'duration_asc' + | 'size_desc' + | 'size_asc' + +type TeaserPlaybackMode = 'still' | 'hover' | 'all' type Props = { jobs: RecordJob[] doneJobs: RecordJob[] + modelsByKey: Record blurPreviews?: boolean + teaserPlayback?: TeaserPlaybackMode + teaserAudio?: boolean onOpenPlayer: (job: RecordJob) => void onDeleteJob?: (job: RecordJob) => void | Promise onToggleHot?: (job: RecordJob) => void | Promise onToggleFavorite?: (job: RecordJob) => void | Promise onToggleLike?: (job: RecordJob) => void | Promise + onToggleWatch?: (job: RecordJob) => void | Promise doneTotal: number page: number pageSize: number onPageChange: (page: number) => void onRefreshDone?: (preferPage?: number) => void | Promise assetNonce?: number + sortMode: SortMode + onSortModeChange: (m: SortMode) => void } const norm = (p: string) => (p || '').replaceAll('\\', '/').trim() @@ -55,10 +69,6 @@ const baseName = (p: string) => { } const keyFor = (j: RecordJob) => baseName(j.output || '') || j.id -function cn(...parts: Array) { - return parts.filter(Boolean).join(' ') -} - function formatDuration(ms: number): string { if (!Number.isFinite(ms) || ms <= 0) return '—' const totalSec = Math.floor(ms / 1000) @@ -128,10 +138,36 @@ type StoredModelFlags = { modelKey: string favorite?: boolean liked?: boolean | null + watching?: boolean | null + tags?: string } const lower = (s: string) => (s || '').trim().toLowerCase() +// Tags kommen aus dem ModelStore als String (meist komma-/semicolon-getrennt) +const parseTags = (raw?: string): string[] => { + const s = String(raw ?? '').trim() + if (!s) return [] + const parts = s + .split(/[\n,;|]+/g) + .map((p) => p.trim()) + .filter(Boolean) + + // stable dedupe (case-insensitive), aber original casing behalten + const seen = new Set() + const out: string[] = [] + for (const p of parts) { + const k = p.toLowerCase() + if (seen.has(k)) continue + seen.add(k) + out.push(p) + } + + // wie in ModelsTab: alphabetisch (case-insensitive) + out.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })) + return out +} + // liest “irgendein” Size-Feld (falls du eins hast) aus dem Job const sizeBytesOf = (job: RecordJob): number | null => { const anyJob = job as any @@ -149,21 +185,38 @@ export default function FinishedDownloads({ jobs, doneJobs, blurPreviews, + teaserPlayback, + teaserAudio, onOpenPlayer, onDeleteJob, onToggleHot, onToggleFavorite, onToggleLike, + onToggleWatch, doneTotal, page, pageSize, onPageChange, onRefreshDone, assetNonce, + sortMode, + onSortModeChange, + modelsByKey, }: Props) { + const teaserPlaybackMode: TeaserPlaybackMode = teaserPlayback ?? 'hover' + + // Desktop vs Mobile: Desktop (hoverfähiger Pointer) -> Teaser nur bei Hover, Mobile -> im Viewport + const canHover = useMediaQuery('(hover: hover) and (pointer: fine)') + + const notify = useNotify() + const teaserHostsRef = React.useRef>(new Map()) const [teaserKey, setTeaserKey] = React.useState(null) + const [hoverTeaserKey, setHoverTeaserKey] = React.useState(null) + + const teaserIORef = React.useRef(null) + const elToKeyRef = React.useRef>(new WeakMap()) // 🗑️ lokale Optimistik: sofort ausblenden, ohne auf das nächste Polling zu warten const [deletedKeys, setDeletedKeys] = React.useState>(() => new Set()) @@ -189,64 +242,117 @@ export default function FinishedDownloads({ type ViewMode = 'table' | 'cards' | 'gallery' const VIEW_KEY = 'finishedDownloads_view' - type SortMode = - | 'completed_desc' - | 'completed_asc' - | 'model_asc' - | 'model_desc' - | 'file_asc' - | 'file_desc' - | 'duration_desc' - | 'duration_asc' - | 'size_desc' - | 'size_asc' - - const SORT_KEY = 'finishedDownloads_sort' - const [sortMode, setSortMode] = React.useState('completed_desc') - - useEffect(() => { - try { - const v = window.localStorage.getItem(SORT_KEY) as SortMode | null - if (v) setSortMode(v) - } catch {} - }, []) - - useEffect(() => { - try { - window.localStorage.setItem(SORT_KEY, sortMode) - } catch {} - }, [sortMode]) - const [view, setView] = React.useState('table') const swipeRefs = React.useRef>(new Map()) - // ⭐ Models-Flags (Fav/Like) aus Backend-Store - const [modelsByKey, setModelsByKey] = React.useState>({}) + // 🏷️ Tag-Filter (klickbare Tags wie in ModelsTab) + const [tagFilter, setTagFilter] = React.useState([]) + const activeTagSet = useMemo(() => new Set(tagFilter.map(lower)), [tagFilter]) + + const modelTags = useMemo(() => { + const tagsByModelKey: Record = {} + const tagSetByModelKey: Record> = {} + + for (const [k, flags] of Object.entries(modelsByKey ?? {})) { + const key = lower(k) + const arr = parseTags(flags?.tags) + tagsByModelKey[key] = arr + tagSetByModelKey[key] = new Set(arr.map(lower)) + } + + return { tagsByModelKey, tagSetByModelKey } + }, [modelsByKey]) + + // 🔎 Suche (client-side, innerhalb der aktuell geladenen Seite) + const [searchQuery, setSearchQuery] = React.useState('') + const deferredSearchQuery = React.useDeferredValue(searchQuery) + + const searchTokens = useMemo( + () => lower(deferredSearchQuery).split(/\s+/g).map((s) => s.trim()).filter(Boolean), + [deferredSearchQuery] + ) + + const clearSearch = useCallback(() => setSearchQuery(''), []) + + const toggleTagFilter = useCallback((tag: string) => { + const k = lower(tag) + setTagFilter((prev) => { + const has = prev.some((t) => lower(t) === k) + return has ? prev.filter((t) => lower(t) !== k) : [...prev, tag] + }) + }, []) + + const globalFilterActive = searchTokens.length > 0 || activeTagSet.size > 0 + + const fetchAllDoneJobs = useCallback( + async (signal?: AbortSignal) => { + const res = await fetch(`/api/record/done?all=1&sort=${encodeURIComponent(sortMode)}`, { + cache: 'no-store' as any, + signal, + }) + if (!res.ok) return + + const list = await res.json().catch(() => []) + const arr = Array.isArray(list) ? (list as RecordJob[]) : [] + setOverrideDoneJobs(arr) + setOverrideDoneTotal(arr.length) + }, + [sortMode] + ) + + const clearTagFilter = useCallback(() => setTagFilter([]), []) + + useEffect(() => { + if (!globalFilterActive) return + + const ac = new AbortController() + + // debounce: erst fetchen wenn User kurz aufgehört hat zu tippen + const t = window.setTimeout(() => { + fetchAllDoneJobs(ac.signal).catch(() => {}) + }, 250) + + return () => { + window.clearTimeout(t) + ac.abort() + } + }, [globalFilterActive, fetchAllDoneJobs]) // ✅ Seite auffüllen + doneTotal aktualisieren, damit Pagination stimmt useEffect(() => { if (refillTick === 0) return - let alive = true + + // ✅ Wenn Filter aktiv: nicht paginiert ziehen, sondern "all" + if (globalFilterActive) { + const ac = new AbortController() + ;(async () => { + try { + await fetchAllDoneJobs(ac.signal) + } catch {} + })() + return () => ac.abort() + } + + const ac = new AbortController() ;(async () => { try { - const [metaRes, listRes] = await Promise.all([ - fetch('/api/record/done/meta', { cache: 'no-store' as any }), - fetch(`/api/record/done?page=${page}&pageSize=${pageSize}`, { cache: 'no-store' as any }), - ]) - - if (!alive) return + // 1) META holen (count), damit Pagination stimmt + const metaRes = await fetch('/api/record/done/meta', { + cache: 'no-store' as any, + signal: ac.signal, + }) if (metaRes.ok) { - const meta = await metaRes.json() + const meta = await metaRes.json().catch(() => null) const count = Number(meta?.count ?? 0) + if (Number.isFinite(count) && count >= 0) { setOverrideDoneTotal(count) const totalPages = Math.max(1, Math.ceil(count / pageSize)) if (page > totalPages) { - // Seite ist nach Delete/Keep "weg" -> auf letzte gültige Seite springen onPageChange(totalPages) setOverrideDoneJobs(null) return @@ -254,62 +360,31 @@ export default function FinishedDownloads({ } } + // 2) LISTE für aktuelle Seite holen + const listRes = await fetch( + `/api/record/done?page=${page}&pageSize=${pageSize}&sort=${encodeURIComponent(sortMode)}`, + { cache: 'no-store' as any, signal: ac.signal } + ) + if (listRes.ok) { - const list = await listRes.json() + const list = await listRes.json().catch(() => []) setOverrideDoneJobs(Array.isArray(list) ? list : []) } } catch { - // optional: console.debug(...) + // Abort / Fehler ignorieren } })() - return () => { - alive = false - } - }, [refillTick, page, pageSize, onPageChange]) + return () => ac.abort() + }, [refillTick, page, pageSize, onPageChange, sortMode, globalFilterActive, fetchAllDoneJobs]) useEffect(() => { - // Wenn Parent neu geladen hat, brauchen wir Overrides nicht mehr + // Wenn Filter aktiv: Overrides behalten (wir arbeiten mit all=1) + if (globalFilterActive) return + setOverrideDoneJobs(null) setOverrideDoneTotal(null) - }, [doneJobs, doneTotal]) - - const refreshModelsByKey = useCallback(async () => { - try { - const res = await fetch('/api/models/list', { cache: 'no-store' as any }) - if (!res.ok) return - const list = (await res.json()) as StoredModelFlags[] - - const map: Record = {} - for (const m of Array.isArray(list) ? list : []) { - const k = lower(String(m?.modelKey ?? '')) - if (!k) continue - - // wenn mehrere Hosts etc.: bevorzuge Eintrag mit “mehr Signal” - const cur = map[k] - if (!cur) { - map[k] = m - continue - } - const score = (x: StoredModelFlags) => (x.favorite ? 2 : 0) + (x.liked === true ? 1 : 0) - if (score(m) > score(cur)) map[k] = m - } - - setModelsByKey(map) - } catch { - // optional: console.debug(...) - } - }, []) - - useEffect(() => { - void refreshModelsByKey() - }, [refreshModelsByKey]) - - useEffect(() => { - const onChanged = () => void refreshModelsByKey() - window.addEventListener('models-changed', onChanged as any) - return () => window.removeEventListener('models-changed', onChanged as any) - }, [refreshModelsByKey]) + }, [doneJobs, doneTotal, globalFilterActive]) useEffect(() => { try { @@ -336,18 +411,19 @@ export default function FinishedDownloads({ const [inlinePlay, setInlinePlay] = React.useState<{ key: string; nonce: number } | null>(null) + const previewMuted = !Boolean(teaserAudio) + const tryAutoplayInline = useCallback((domId: string) => { const host = document.getElementById(domId) const v = host?.querySelector('video') as HTMLVideoElement | null if (!v) return false - // ✅ zentral - applyInlineVideoPolicy(v, { muted: true }) + applyInlineVideoPolicy(v, { muted: previewMuted }) const p = v.play?.() if (p && typeof (p as any).catch === 'function') (p as Promise).catch(() => {}) return true - }, []) + }, [previewMuted]) const startInline = useCallback((key: string) => { setInlinePlay((prev) => (prev?.key === key ? { key, nonce: prev.nonce + 1 } : { key, nonce: 1 })) @@ -435,7 +511,7 @@ export default function FinishedDownloads({ const key = keyFor(job) if (!file) { - window.alert('Kein Dateiname gefunden – kann nicht löschen.') + notify.error('Löschen nicht möglich', 'Kein Dateiname gefunden – kann nicht löschen.') return false } if (deletingKeys.has(key)) return false @@ -464,13 +540,13 @@ export default function FinishedDownloads({ animateRemove(key) return true } catch (e: any) { - window.alert(`Löschen fehlgeschlagen: ${String(e?.message || e)}`) + notify.error('Löschen fehlgeschlagen', String(e?.message || e)) return false } finally { markDeleting(key, false) } }, - [deletingKeys, markDeleting, releasePlayingFile, onDeleteJob, animateRemove, queueRefill] + [deletingKeys, markDeleting, releasePlayingFile, onDeleteJob, animateRemove, queueRefill, notify] ) const keepVideo = useCallback( @@ -479,7 +555,7 @@ export default function FinishedDownloads({ const key = keyFor(job) if (!file) { - window.alert('Kein Dateiname gefunden – kann nicht behalten.') + notify.error('Keep nicht möglich', 'Kein Dateiname gefunden – kann nicht behalten.') return false } if (keepingKeys.has(key) || deletingKeys.has(key)) return false @@ -497,20 +573,20 @@ export default function FinishedDownloads({ animateRemove(key) return true } catch (e: any) { - window.alert(`Behalten fehlgeschlagen: ${String(e?.message || e)}`) + notify.error('Keep fehlgeschlagen', String(e?.message || e)) return false } finally { markKeeping(key, false) } }, - [keepingKeys, deletingKeys, markKeeping, releasePlayingFile, animateRemove] + [keepingKeys, deletingKeys, markKeeping, releasePlayingFile, animateRemove, notify] ) const toggleHotVideo = useCallback( async (job: RecordJob) => { const file = baseName(job.output || '') if (!file) { - window.alert('Kein Dateiname gefunden – kann nicht HOT togglen.') + notify.error('HOT nicht möglich', 'Kein Dateiname gefunden – kann nicht HOT togglen.') return } @@ -548,18 +624,30 @@ export default function FinishedDownloads({ }) } } catch (e: any) { - window.alert(`HOT umbenennen fehlgeschlagen: ${String(e?.message || e)}`) + notify.error('HOT umbenennen fehlgeschlagen', String(e?.message || e)) } }, - [baseName, releasePlayingFile, onToggleHot] + [baseName, releasePlayingFile, onToggleHot, notify] ) const runtimeSecondsForSort = useCallback((job: RecordJob) => { - const start = Date.parse(String(job.startedAt || '')) - const end = Date.parse(String(job.endedAt || '')) - if (Number.isFinite(start) && Number.isFinite(end) && end > start) return (end - start) / 1000 + // 1) Prefer real video duration (ffprobe / backend) const sec = (job as any)?.durationSeconds - return (typeof sec === 'number' && sec > 0) ? sec : Number.POSITIVE_INFINITY + if (typeof sec === 'number' && Number.isFinite(sec) && sec > 0) return sec + + // 2) Fallback: endedAt-startedAt (only if plausible) + const start = Date.parse(String((job as any)?.startedAt || '')) + const end = Date.parse(String((job as any)?.endedAt || '')) + if (Number.isFinite(start) && Number.isFinite(end) && end > start) { + const diffSec = (end - start) / 1000 + + // guard: ignore absurd values (move/copy can skew modtime) + // accept e.g. 1s..24h + if (diffSec >= 1 && diffSec <= 24 * 60 * 60) return diffSec + } + + // 3) Unknown durations last + return Number.POSITIVE_INFINITY }, []) const applyRenamedOutput = useCallback( @@ -600,81 +688,10 @@ export default function FinishedDownloads({ return j.status === 'finished' || j.status === 'failed' || j.status === 'stopped' }) - list.sort((a, b) => norm(b.endedAt || '').localeCompare(norm(a.endedAt || ''))) return list }, [jobs, doneJobsPage, deletedKeys, applyRenamedOutput]) - const endedAtMs = (j: RecordJob) => (j.endedAt ? new Date(j.endedAt).getTime() : 0) - - const modelForSort = (j: RecordJob) => modelNameFromOutput(j.output || '').toLowerCase() - - const fileForSort = (j: RecordJob) => { - const raw = baseName(j.output || '').toLowerCase() - return stripHotPrefix(raw) - } - - const durationSecondsForSort = (j: RecordJob) => { - const k = keyFor(j) - const s = - (typeof (j as any).durationSeconds === 'number' && (j as any).durationSeconds > 0) - ? (j as any).durationSeconds - : durations[k] - return typeof s === 'number' && Number.isFinite(s) && s > 0 ? s : NaN - } - - const sizeBytesForSort = (j: RecordJob) => { - const s = sizeBytesOf(j) - return typeof s === 'number' ? s : NaN - } - - const cmpStr = (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) - const cmpNum = (a: number, b: number) => a - b - const cmpMaybeNum = (a: number, b: number, dir: 1 | -1) => { - const aOk = Number.isFinite(a) - const bOk = Number.isFinite(b) - if (!aOk && !bOk) return 0 - if (!aOk) return 1 - if (!bOk) return -1 - return dir * cmpNum(a, b) - } - - const sortedNonTableRows = React.useMemo(() => { - const arr = [...rows] - - arr.sort((a, b) => { - switch (sortMode) { - case 'completed_asc': - return cmpNum(endedAtMs(a), endedAtMs(b)) || cmpStr(keyFor(a), keyFor(b)) - case 'completed_desc': - return cmpNum(endedAtMs(b), endedAtMs(a)) || cmpStr(keyFor(a), keyFor(b)) - - case 'model_asc': - return cmpStr(modelForSort(a), modelForSort(b)) || cmpNum(endedAtMs(b), endedAtMs(a)) - case 'model_desc': - return cmpStr(modelForSort(b), modelForSort(a)) || cmpNum(endedAtMs(b), endedAtMs(a)) - - case 'file_asc': - return cmpStr(fileForSort(a), fileForSort(b)) || cmpNum(endedAtMs(b), endedAtMs(a)) - case 'file_desc': - return cmpStr(fileForSort(b), fileForSort(a)) || cmpNum(endedAtMs(b), endedAtMs(a)) - - case 'duration_asc': - return cmpMaybeNum(durationSecondsForSort(a), durationSecondsForSort(b), 1) || cmpNum(endedAtMs(b), endedAtMs(a)) - case 'duration_desc': - return cmpMaybeNum(durationSecondsForSort(a), durationSecondsForSort(b), -1) || cmpNum(endedAtMs(b), endedAtMs(a)) - - case 'size_asc': - return cmpMaybeNum(sizeBytesForSort(a), sizeBytesForSort(b), 1) || cmpNum(endedAtMs(b), endedAtMs(a)) - case 'size_desc': - return cmpMaybeNum(sizeBytesForSort(a), sizeBytesForSort(b), -1) || cmpNum(endedAtMs(b), endedAtMs(a)) - - default: - return cmpNum(endedAtMs(b), endedAtMs(a)) - } - }) - - return arr - }, [rows, sortMode, durations]) + const viewRows = rows useEffect(() => { const onExternalDelete = (ev: Event) => { @@ -712,73 +729,152 @@ export default function FinishedDownloads({ window.addEventListener('finished-downloads:delete', onExternalDelete as EventListener) return () => window.removeEventListener('finished-downloads:delete', onExternalDelete as EventListener) }, [animateRemove, markDeleting, markDeleted, view, onRefreshDone, page, queueRefill]) - - const viewRows = view === 'table' ? rows : sortedNonTableRows - const visibleRows = viewRows.filter((j) => !deletedKeys.has(keyFor(j))) + const visibleRows = useMemo(() => { + const base = viewRows.filter((j) => !deletedKeys.has(keyFor(j))) + + // 🔎 Suche (AND über Tokens) + const searched = searchTokens.length + ? base.filter((j) => { + const file = baseName(j.output || '') + const model = modelNameFromOutput(j.output) + const modelKey = lower(model) + const tags = modelTags.tagsByModelKey[modelKey] ?? [] + + const hay = lower([file, stripHotPrefix(file), model, j.id, j.status, tags.join(' ')].join(' ')) + + for (const t of searchTokens) { + if (!hay.includes(t)) return false + } + return true + }) + : base + + if (activeTagSet.size === 0) return searched + + // AND-Filter: alle ausgewählten Tags müssen vorhanden sein + return searched.filter((j) => { + const modelKey = lower(modelNameFromOutput(j.output)) + + const have = modelTags.tagSetByModelKey[modelKey] + if (!have || have.size === 0) return false + + for (const t of activeTagSet) { + if (!have.has(t)) return false + } + return true + }) + }, [viewRows, deletedKeys, activeTagSet, modelTags, searchTokens]) + + const totalItemsForPagination = globalFilterActive ? visibleRows.length : doneTotalPage + + const pageRows = useMemo(() => { + if (!globalFilterActive) return visibleRows + const start = (page - 1) * pageSize + const end = start + pageSize + return visibleRows.slice(Math.max(0, start), Math.max(0, end)) + }, [globalFilterActive, visibleRows, page, pageSize]) useEffect(() => { - const active = view === 'cards' - if (!active) { setTeaserKey(null); return } + if (!globalFilterActive) return + const totalPages = Math.max(1, Math.ceil(visibleRows.length / pageSize)) + if (page > totalPages) onPageChange(totalPages) + }, [globalFilterActive, visibleRows.length, page, pageSize, onPageChange]) - // in Cards: wenn Inline-Player aktiv ist, diesen festhalten - if (view === 'cards' && inlinePlay?.key) { setTeaserKey(inlinePlay.key); return } + // 🖱️ Desktop: Teaser nur bei Hover (Settings: 'hover' = Standard). Mobile: weiterhin Viewport-Fokus (Effect darunter) + useEffect(() => { + const active = + teaserPlaybackMode === 'hover' && + !canHover && + (view === 'cards' || view === 'gallery' || view === 'table') - let raf = 0 - const schedule = () => { - if (raf) return - raf = requestAnimationFrame(() => { - raf = 0 - const cx = window.innerWidth / 2 - const cy = window.innerHeight / 2 + if (!active) { + setTeaserKey(null) + teaserIORef.current?.disconnect() + teaserIORef.current = null + return + } + // Cards: Inline-Player soll “sticky” bleiben + if (view === 'cards' && inlinePlay?.key) { + setTeaserKey(inlinePlay.key) + return + } + + teaserIORef.current?.disconnect() + + const io = new IntersectionObserver( + (entries) => { let bestKey: string | null = null - let best = Number.POSITIVE_INFINITY + let bestRatio = 0 - for (const [key, el] of teaserHostsRef.current) { - const r = el.getBoundingClientRect() - if (r.bottom <= 0 || r.top >= window.innerHeight) continue - const ex = r.left + r.width / 2 - const ey = r.top + r.height / 2 - const d = Math.hypot(ex - cx, ey - cy) - if (d < best) { best = d; bestKey = key } + for (const ent of entries) { + if (!ent.isIntersecting) continue + const k = elToKeyRef.current.get(ent.target) + if (!k) continue + + if (ent.intersectionRatio > bestRatio) { + bestRatio = ent.intersectionRatio + bestKey = k + } } - setTeaserKey(prev => (prev === bestKey ? prev : bestKey)) + if (bestKey) { + setTeaserKey((prev) => (prev === bestKey ? prev : bestKey)) + } + }, + { + // eher “welche Card ist wirklich sichtbar” + threshold: [0, 0.15, 0.3, 0.5, 0.7, 0.9], + rootMargin: '0px', + } + ) - }) + teaserIORef.current = io + + for (const [k, el] of teaserHostsRef.current) { + elToKeyRef.current.set(el, k) + io.observe(el) } - schedule() - window.addEventListener('scroll', schedule, { passive: true }) - window.addEventListener('resize', schedule) return () => { - if (raf) cancelAnimationFrame(raf) - window.removeEventListener('scroll', schedule) - window.removeEventListener('resize', schedule) + io.disconnect() + if (teaserIORef.current === io) teaserIORef.current = null } - }, [view, visibleRows.length, inlinePlay?.key]) - + }, [view, teaserPlaybackMode, canHover, inlinePlay?.key]) // 🧠 Laufzeit-Anzeige: bevorzugt Videodauer, sonst Fallback auf startedAt/endedAt const runtimeOf = (job: RecordJob): string => { + const k = keyFor(job) + + // ✅ 1) echte Videodauer (Preview-Metadaten oder Backend durationSeconds) + const sec = durations[k] ?? (job as any)?.durationSeconds + if (typeof sec === 'number' && Number.isFinite(sec) && sec > 0) { + return formatDuration(sec * 1000) + } + + // 2) Fallback const start = Date.parse(String(job.startedAt || '')) const end = Date.parse(String(job.endedAt || '')) if (Number.isFinite(start) && Number.isFinite(end) && end > start) { return formatDuration(end - start) } - // Fallback (falls mal nur durationSeconds kommt) - const sec = (job as any)?.durationSeconds - if (typeof sec === 'number' && Number.isFinite(sec) && sec > 0) return formatDuration(sec * 1000) - return '—' } const registerTeaserHost = useCallback( (key: string) => (el: HTMLDivElement | null) => { - if (el) teaserHostsRef.current.set(key, el) - else teaserHostsRef.current.delete(key) + const prev = teaserHostsRef.current.get(key) + if (prev && teaserIORef.current) teaserIORef.current.unobserve(prev) + + if (el) { + teaserHostsRef.current.set(key, el) + elToKeyRef.current.set(el, key) + teaserIORef.current?.observe(el) + } else { + teaserHostsRef.current.delete(key) + } }, [] ) @@ -803,32 +899,53 @@ export default function FinishedDownloads({ widthClassName: 'w-[140px]', cell: (j) => { const k = keyFor(j) + const allowSound = Boolean(teaserAudio) && hoverTeaserKey === k + const previewMuted = !allowSound + return (
e.stopPropagation()} onMouseDown={(e) => e.stopPropagation()} + onMouseEnter={() => { + if (canHover) setHoverTeaserKey(k) + }} + onMouseLeave={() => { + if (canHover) setHoverTeaserKey(null) + }} > - + + } + > + +
) }, }, { - key: 'video', - header: 'Video', + key: 'Model', + header: 'Model', sortable: true, sortValue: (j) => { const fileRaw = baseName(j.output || '') @@ -842,18 +959,46 @@ export default function FinishedDownloads({ const isHot = fileRaw.startsWith('HOT ') const model = modelNameFromOutput(j.output) const file = stripHotPrefix(fileRaw) + const modelKey = lower(modelNameFromOutput(j.output)) + const tags = parseTags(modelsByKey[modelKey]?.tags) + const show = tags.slice(0, 6) + const rest = tags.length - show.length + const full = tags.join(', ') return (
-
- - {file || '—'} - +
{model}
- {isHot ? ( - - HOT +
+ {/* Zeile 1: Filename + HOT */} +
+ + {file || '—'} + + {isHot ? ( + + HOT + + ) : null} +
+ + {/* Zeile 2: Tags unter dem Filename */} + {show.length > 0 ? ( +
+ {show.map((t) => ( + + ))} + + {rest > 0 ? ( + + +{rest} + + ) : null} +
) : null}
@@ -906,6 +1051,36 @@ export default function FinishedDownloads({ ) }, }, + { + key: 'completedAt', + header: 'Fertiggestellt am', + sortable: true, + widthClassName: 'w-[150px]', + sortValue: (j) => { + const t = Date.parse(String(j.endedAt || '')) + return Number.isFinite(t) ? t : Number.NEGATIVE_INFINITY + }, + cell: (j) => { + const t = Date.parse(String(j.endedAt || '')) + if (!Number.isFinite(t)) return + + const d = new Date(t) + const date = d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' }) + const time = d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }) + + return ( + + ) + }, + }, { key: 'runtime', header: 'Dauer', @@ -937,125 +1112,59 @@ export default function FinishedDownloads({ cell: (j) => { const k = keyFor(j) const busy = deletingKeys.has(k) || keepingKeys.has(k) || removingKeys.has(k) - const iconBtn = - 'inline-flex items-center justify-center rounded-md p-1.5 ' + - 'hover:bg-gray-100/70 dark:hover:bg-white/5 ' + - 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500 ' + - 'disabled:opacity-50 disabled:cursor-not-allowed' const fileRaw = baseName(j.output || '') const isHot = fileRaw.startsWith('HOT ') const modelKey = lower(modelNameFromOutput(j.output)) const flags = modelsByKey[modelKey] const isFav = Boolean(flags?.favorite) const isLiked = flags?.liked === true - + const isWatching = Boolean(flags?.watching) return ( -
- {/* Favorite */} - - - {/* Like */} - - - {/* HOT */} - - - {/* Keep */} - - - {/* Delete */} - -
+ ) }, }] + const sortStateToMode = (s: SortState): SortMode => { + if (!s) return 'completed_desc' + + const anyS = s as any + const key = String(anyS.key ?? anyS.columnKey ?? anyS.id ?? '') + const dirRaw = String(anyS.dir ?? anyS.direction ?? anyS.order ?? '').toLowerCase() + const asc = dirRaw === 'asc' || dirRaw === '1' || dirRaw === 'true' + + if (key === 'completedAt') return asc ? 'completed_asc' : 'completed_desc' + if (key === 'runtime') return asc ? 'duration_asc' : 'duration_desc' + if (key === 'size') return asc ? 'size_asc' : 'size_desc' + if (key === 'video') return asc ? 'file_asc' : 'file_desc' + + // fallback + return asc ? 'completed_asc' : 'completed_desc' + } + + const handleTableSortChange = (s: SortState) => { + setSort(s) // lässt Table weiterhin Pfeil anzeigen + const mode = sortStateToMode(s) + onSortModeChange(mode) + if (page !== 1) onPageChange(1) + } // ✅ Hooks immer zuerst – unabhängig von rows const isSmall = useMediaQuery('(max-width: 639px)') @@ -1067,204 +1176,390 @@ export default function FinishedDownloads({ } }, [isSmall]) - if (rows.length === 0 && doneTotalPage === 0) { - return ( - -
- Keine abgeschlossenen Downloads im Zielordner vorhanden. -
-
- ) - } + const emptyFolder = rows.length === 0 && doneTotalPage === 0 + const emptyByFilter = !emptyFolder && visibleRows.length === 0 return ( <> - {/* Toolbar */} -
- {/* Mobile title */} -
-
- Abgeschlossene Downloads ({rows.length}) -
-
+ {/* Toolbar (sticky) */} +
+
+ {/* Header row */} +
+ {/* Mobile title + count badge */} +
+
+ Abgeschlossene Downloads +
+ + {totalItemsForPagination} + +
- {/* Views */} -
- setView(id as ViewMode)} - size="sm" - ariaLabel="Ansicht" - items={[ - { - id: 'table', - icon: , - label: Tabelle, - srLabel: 'Tabelle', - }, - { - id: 'cards', - icon: , - label: Cards, - srLabel: 'Cards', - }, - { - id: 'gallery', - icon: , - label: Galerie, - srLabel: 'Galerie', - }, - ]} - /> + {/* Desktop title */} +
+
+ Abgeschlossene Downloads +
+ + {totalItemsForPagination} + +
+ +
+ {/* Desktop: Sort rechts neben View-Buttons */} + {view !== 'table' && ( +
+ + +
+ )} + + {/* Desktop: Suche neben Sort */} +
+ setSearchQuery(e.target.value)} + placeholder="Suchen…" + className=" + h-9 w-56 md:w-72 rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm + focus:outline-none focus:ring-2 focus:ring-indigo-500 + dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark] + " + /> + {(searchQuery || '').trim() !== '' ? ( + + ) : null} +
+ + {/* Views */} + setView(id as ViewMode)} + size="md" + ariaLabel="Ansicht" + items={[ + { + id: 'table', + icon: , + label: isSmall ? undefined : 'Tabelle', + srLabel: 'Tabelle', + }, + { + id: 'cards', + icon: , + label: isSmall ? undefined : 'Cards', + srLabel: 'Cards', + }, + { + id: 'gallery', + icon: , + label: isSmall ? undefined : 'Galerie', + srLabel: 'Galerie', + }, + ]} + /> +
+
+ + {/* Mobile Suche */} +
+
+ setSearchQuery(e.target.value)} + placeholder="Suchen…" + className=" + w-full h-9 rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 shadow-sm + focus:outline-none focus:ring-2 focus:ring-indigo-500 + dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:[color-scheme:dark] + " + /> + {(searchQuery || '').trim() !== '' ? ( + + ) : null} +
+
+ + {/* Mobile Sort (eigene Sektion, schöner Abstand automatisch durch Trenner/Padding) */} + {view !== 'table' && ( +
+ + +
+ )} + + {/* Tag-Filter (als Sektion IN der Card, nicht nochmal eine eigene Box-in-Box) */} + {tagFilter.length > 0 ? ( +
+
+ Tag-Filter + +
+ {tagFilter.map((t) => ( + + ))} + + +
+
+
+ ) : null}
- {view !== 'table' && ( -
- - -
+ {emptyFolder ? ( + +
+
+ 📁 +
+
+
+ Keine abgeschlossenen Downloads +
+
+ Im Zielordner ist aktuell nichts vorhanden. +
+
+
+
+ ) : emptyByFilter ? ( + +
+ Keine Treffer für die aktuellen Filter. +
+ + {tagFilter.length > 0 || (searchQuery || '').trim() !== '' ? ( +
+ {tagFilter.length > 0 ? ( + + ) : null} + + {(searchQuery || '').trim() !== '' ? ( + + ) : null} +
+ ) : null} +
+ ) : ( + <> + {view === 'cards' && ( + + )} + + {view === 'table' && ( + keyFor(j)} + sort={sort} + onSortChange={handleTableSortChange} + onRowClick={onOpenPlayer} + rowClassName={(j) => { + const k = keyFor(j) + return [ + 'transition-all duration-300', + (deletingKeys.has(k) || removingKeys.has(k)) && + 'bg-red-50/60 dark:bg-red-500/10 pointer-events-none', + deletingKeys.has(k) && 'animate-pulse', + (keepingKeys.has(k) || removingKeys.has(k)) && 'pointer-events-none', + keepingKeys.has(k) && 'bg-emerald-50/60 dark:bg-emerald-500/10 animate-pulse', + removingKeys.has(k) && 'opacity-0', + ] + .filter(Boolean) + .join(' ') + }} + /> + )} + + {view === 'gallery' && ( + + )} + + { + flushSync(() => { + setInlinePlay(null) + setTeaserKey(null) + setHoverTeaserKey(null) + }) + + for (const j of pageRows) { + const f = baseName(j.output || '') + if (!f) continue + window.dispatchEvent(new CustomEvent('player:release', { detail: { file: f } })) + window.dispatchEvent(new CustomEvent('player:close', { detail: { file: f } })) + } + + window.scrollTo({ top: 0, behavior: 'auto' }) + onPageChange(p) + }} + showSummary={false} + prevLabel="Zurück" + nextLabel="Weiter" + className="mt-4" + /> + )} - - {view === 'cards' && ( - - )} - - {view === 'table' && ( - keyFor(j)} - sort={sort} - onSortChange={setSort} - onRowClick={onOpenPlayer} - rowClassName={(j) => { - const k = keyFor(j) - return [ - 'transition-all duration-300', - (deletingKeys.has(k) || removingKeys.has(k)) && 'bg-red-50/60 dark:bg-red-500/10 pointer-events-none', - deletingKeys.has(k) && 'animate-pulse', - (keepingKeys.has(k) || removingKeys.has(k)) && 'pointer-events-none', - keepingKeys.has(k) && 'bg-emerald-50/60 dark:bg-emerald-500/10 animate-pulse', - removingKeys.has(k) && 'opacity-0', - ].filter(Boolean).join(' ') - }} - /> - )} - - {view === 'gallery' && ( - - )} - - { - // 1) Inline-Playback + aktiven Teaser sofort stoppen - flushSync(() => { - setInlinePlay(null) - setTeaserKey(null) - }) - - // 2) alle aktuell sichtbaren Previews "freigeben" (damit keine Datei mehr offen ist) - for (const j of visibleRows) { - const f = baseName(j.output || '') - if (!f) continue - window.dispatchEvent(new CustomEvent('player:release', { detail: { file: f } })) - window.dispatchEvent(new CustomEvent('player:close', { detail: { file: f } })) - } - - // optional: zurück nach oben, damit neue Seite "sauber" startet - window.scrollTo({ top: 0, behavior: 'auto' }) - - // 3) Seite wechseln (App lädt dann neue doneJobs) - onPageChange(p) - }} - showSummary={false} - prevLabel="Zurück" - nextLabel="Weiter" - className="mt-4" - /> ) diff --git a/frontend/src/components/ui/FinishedDownloadsCardsView.tsx b/frontend/src/components/ui/FinishedDownloadsCardsView.tsx index 2d9aaae..7e0a74d 100644 --- a/frontend/src/components/ui/FinishedDownloadsCardsView.tsx +++ b/frontend/src/components/ui/FinishedDownloadsCardsView.tsx @@ -1,3 +1,5 @@ +// frontend\src\components\ui\FinishedDownloadsCardsView.tsx + 'use client' import * as React from 'react' @@ -5,15 +7,15 @@ import Card from './Card' import type { RecordJob } from '../../types' import FinishedVideoPreview from './FinishedVideoPreview' import SwipeCard, { type SwipeCardHandle } from './SwipeCard' -import { flushSync } from 'react-dom' import { - TrashIcon, - FireIcon, - BookmarkSquareIcon, - StarIcon as StarOutlineIcon, - HeartIcon as HeartOutlineIcon, -} from '@heroicons/react/24/outline' -import { StarIcon as StarSolidIcon, HeartIcon as HeartSolidIcon } from '@heroicons/react/24/solid' + StarIcon as StarSolidIcon, + HeartIcon as HeartSolidIcon, + EyeIcon as EyeSolidIcon, +} from '@heroicons/react/24/solid' +import TagBadge from './TagBadge' +import RecordJobActions from './RecordJobActions' +import LazyMount from './LazyMount' + function cn(...parts: Array) { return parts.filter(Boolean).join(' ') @@ -24,6 +26,9 @@ type InlinePlayState = { key: string; nonce: number } | null type Props = { rows: RecordJob[] isSmall: boolean + teaserPlayback: 'still' | 'hover' | 'all' + teaserAudio?: boolean + hoverTeaserKey?: string | null blurPreviews?: boolean durations: Record @@ -48,6 +53,7 @@ type Props = { lower: (s: string) => string // callbacks/actions + onHoverPreviewKeyChange?: (key: string | null) => void onOpenPlayer: (job: RecordJob) => void openPlayer: (job: RecordJob) => void startInline: (key: string) => void @@ -61,17 +67,42 @@ type Props = { releasePlayingFile: (file: string, opts?: { close?: boolean }) => Promise - modelsByKey: Record + modelsByKey: Record + activeTagSet: Set + onToggleTagFilter: (tag: string) => void onToggleHot?: (job: RecordJob) => void | Promise onToggleFavorite?: (job: RecordJob) => void | Promise onToggleLike?: (job: RecordJob) => void | Promise + onToggleWatch?: (job: RecordJob) => void | Promise } +const parseTags = (raw?: string): string[] => { + const s = String(raw ?? '').trim() + if (!s) return [] + const parts = s + .split(/[\n,;|]+/g) + .map((p) => p.trim()) + .filter(Boolean) + + const seen = new Set() + const out: string[] = [] + for (const p of parts) { + const k = p.toLowerCase() + if (seen.has(k)) continue + seen.add(k) + out.push(p) + } + return out +} + + export default function FinishedDownloadsCardsView({ rows, isSmall, - + teaserPlayback, + teaserAudio, + hoverTeaserKey, blurPreviews, durations, teaserKey, @@ -93,6 +124,7 @@ export default function FinishedDownloadsCardsView({ formatBytes, lower, + onHoverPreviewKeyChange, onOpenPlayer, openPlayer, startInline, @@ -107,16 +139,57 @@ export default function FinishedDownloadsCardsView({ releasePlayingFile, modelsByKey, + activeTagSet, + onToggleTagFilter, onToggleHot, onToggleFavorite, onToggleLike, + onToggleWatch }: Props) { + + const [openTagsKey, setOpenTagsKey] = React.useState(null) + const tagsPopoverRef = React.useRef(null) + + React.useEffect(() => { + if (!openTagsKey) return + + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Escape') setOpenTagsKey(null) + } + + const onPointerDown = (e: PointerEvent) => { + const el = tagsPopoverRef.current + if (!el) return + if (el.contains(e.target as Node)) return + setOpenTagsKey(null) + } + + document.addEventListener('keydown', onKeyDown) + document.addEventListener('pointerdown', onPointerDown) + return () => { + document.removeEventListener('keydown', onKeyDown) + document.removeEventListener('pointerdown', onPointerDown) + } + }, [openTagsKey]) + + React.useEffect(() => { + if (!openTagsKey) return + // Falls Job aus der Liste verschwindet → Popover schließen + const exists = rows.some((j) => keyFor(j) === openTagsKey) + if (!exists) setOpenTagsKey(null) + }, [rows, keyFor, openTagsKey]) + + const mobileRootMargin = isSmall ? '180px' : '500px' + return ( -
+
{rows.map((j) => { const k = keyFor(j) const inlineActive = inlinePlay?.key === k + // Sound nur, wenn Setting aktiv UND (Inline aktiv ODER Hover auf diesem Teaser) + const allowSound = Boolean(teaserAudio) && (inlineActive || hoverTeaserKey === k) + const previewMuted = !allowSound const inlineNonce = inlineActive ? inlinePlay?.nonce ?? 0 : 0 const busy = deletingKeys.has(k) || keepingKeys.has(k) || removingKeys.has(k) @@ -127,6 +200,11 @@ export default function FinishedDownloadsCardsView({ const flags = modelsByKey[lower(model)] const isFav = Boolean(flags?.favorite) const isLiked = flags?.liked === true + const isWatching = Boolean(flags?.watching) + const tags = parseTags(flags?.tags) + const showTags = tags.slice(0, 6) + const restTags = tags.length - showTags.length + const fullTags = tags.join(', ') const statusCls = j.status === 'failed' @@ -141,13 +219,17 @@ export default function FinishedDownloadsCardsView({ const size = formatBytes(sizeBytesOf(j)) const inlineDomId = `inline-prev-${encodeURIComponent(k)}` + const motionCls = isSmall ? '' : 'transition-all duration-300 ease-in-out hover:-translate-y-0.5 hover:shadow-md dark:hover:shadow-none' const cardInner = (
onHoverPreviewKeyChange?.(k)} + onMouseLeave={isSmall ? undefined : () => onHoverPreviewKeyChange?.(null)} onClick={(e) => { e.preventDefault() e.stopPropagation() @@ -175,22 +259,29 @@ export default function FinishedDownloadsCardsView({ startInline(k) }} > - stripHotPrefix(baseName(p))} - durationSeconds={durations[k]} - onDuration={handleDuration} - className="w-full h-full" - showPopover={false} - blur={blurPreviews} - animated={teaserKey === k} - animatedMode="teaser" - animatedTrigger="always" - inlineVideo={inlineActive ? 'always' : false} - inlineNonce={inlineNonce} - inlineControls={inlineActive} - inlineLoop={false} - /> + } + className="absolute inset-0" + > + stripHotPrefix(baseName(p))} + className="w-full h-full" + showPopover={false} + blur={isSmall ? false : (inlineActive ? false : blurPreviews)} + animated={teaserPlayback === 'all' ? true : teaserPlayback === 'hover' ? teaserKey === k : false} + animatedMode="teaser" + animatedTrigger="always" + inlineVideo={inlineActive ? 'always' : false} + inlineNonce={inlineNonce} + inlineControls={inlineActive} + inlineLoop={false} + muted={previewMuted} + popoverMuted={previewMuted} + /> + {/* Gradient overlay bottom */}
- {(() => { - const iconBtn = - 'inline-flex items-center justify-center rounded-md bg-black/40 p-2 text-white ' + - 'backdrop-blur hover:bg-black/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500' - - return ( - <> - - {/* Favorite */} - - - {/* Like */} - - - - {/* HOT */} - - - {!isSmall && ( - <> - {/* Keep */} - - - {/* Delete */} - - - )} - - ) - })()} +
e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + > + { + const file = baseName(job.output || '') + if (file) { + // wichtig gegen File-Lock beim Rename: + await releasePlayingFile(file, { close: true }) + await new Promise((r) => setTimeout(r, 150)) + } + await onToggleHot(job) + } + : undefined + } + showKeep={!isSmall} + showDelete={!isSmall} + onKeep={keepVideo} + onDelete={deleteVideo} + order={['watch', 'favorite', 'like', 'hot', 'details', 'keep', 'delete']} + className="flex items-center gap-2" + />
{/* Footer / Meta */} -
{/* Model + Datei im Footer */} +
{model}
+ {isWatching ? : null} {isLiked ? : null} {isFav ? : null}
@@ -372,6 +395,90 @@ export default function FinishedDownloadsCardsView({ ) : null}
+ + {/* Tags: 1 Zeile, +N öffnet Popover */} +
e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + > + {/* links: Tags (nowrap, werden ggf. geclippt) */} +
+
+ {showTags.length > 0 ? ( + showTags.map((t) => ( + + )) + ) : ( + + )} +
+
+ + {/* rechts: Rest-Count immer sichtbar + klickbar */} + {restTags > 0 ? ( + + ) : null} + + {/* Popover */} + {openTagsKey === k ? ( +
e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + > +
+
Tags
+ +
+ +
+
+ {tags.map((t) => ( + + ))} +
+
+
+ ) : null} +
@@ -390,10 +497,14 @@ export default function FinishedDownloadsCardsView({ ignoreFromBottomPx={110} onTap={() => { const domId = `inline-prev-${encodeURIComponent(k)}` - flushSync(() => startInline(k)) - if (!tryAutoplayInline(domId)) { - requestAnimationFrame(() => tryAutoplayInline(domId)) - } + startInline(k) + + // ✅ nach dem State-Update dem DOM 1–2 Frames geben + requestAnimationFrame(() => { + if (!tryAutoplayInline(domId)) { + requestAnimationFrame(() => tryAutoplayInline(domId)) + } + }) }} onSwipeLeft={() => deleteVideo(j)} onSwipeRight={() => keepVideo(j)} diff --git a/frontend/src/components/ui/FinishedDownloadsGalleryView.tsx b/frontend/src/components/ui/FinishedDownloadsGalleryView.tsx index 74524d1..38cbdcd 100644 --- a/frontend/src/components/ui/FinishedDownloadsGalleryView.tsx +++ b/frontend/src/components/ui/FinishedDownloadsGalleryView.tsx @@ -3,22 +3,25 @@ import * as React from 'react' import type { RecordJob } from '../../types' import FinishedVideoPreview from './FinishedVideoPreview' -import { - TrashIcon, - BookmarkSquareIcon, - FireIcon, - StarIcon as StarOutlineIcon, - HeartIcon as HeartOutlineIcon, -} from '@heroicons/react/24/outline' import { StarIcon as StarSolidIcon, HeartIcon as HeartSolidIcon, + EyeIcon as EyeSolidIcon, } from '@heroicons/react/24/solid' +import TagBadge from './TagBadge' +import RecordJobActions from './RecordJobActions' +import LazyMount from './LazyMount' type Props = { rows: RecordJob[] blurPreviews?: boolean durations: Record + teaserPlayback: 'still' | 'hover' | 'all' + teaserAudio?: boolean + hoverTeaserKey?: string | null + teaserKey: string | null + + handleDuration: (job: RecordJob, seconds: number) => void keyFor: (j: RecordJob) => string @@ -39,20 +42,27 @@ type Props = { onOpenPlayer: (job: RecordJob) => void deleteVideo: (job: RecordJob) => Promise keepVideo: (job: RecordJob) => Promise - onToggleHot: (job: RecordJob) => void | Promise lower: (s: string) => string - modelsByKey: Record + + modelsByKey: Record + activeTagSet: Set + onHoverPreviewKeyChange?: (key: string | null) => void + onToggleTagFilter: (tag: string) => void onToggleFavorite?: (job: RecordJob) => void | Promise onToggleLike?: (job: RecordJob) => void | Promise - - + onToggleWatch?: (job: RecordJob) => void | Promise + onToggleHot: (job: RecordJob) => void | Promise } export default function FinishedDownloadsGalleryView({ rows, blurPreviews, durations, + teaserPlayback, + teaserAudio, + hoverTeaserKey, + teaserKey, handleDuration, keyFor, @@ -70,253 +80,334 @@ export default function FinishedDownloadsGalleryView({ registerTeaserHost, + onHoverPreviewKeyChange, onOpenPlayer, deleteVideo, keepVideo, onToggleHot, lower, modelsByKey, + activeTagSet, + onToggleTagFilter, onToggleFavorite, onToggleLike, + onToggleWatch, }: Props) { + + const [openTagsKey, setOpenTagsKey] = React.useState(null) + const tagsPopoverRef = React.useRef(null) + + React.useEffect(() => { + if (!openTagsKey) return + + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Escape') setOpenTagsKey(null) + } + + const onPointerDown = (e: PointerEvent) => { + const el = tagsPopoverRef.current + if (!el) return + if (el.contains(e.target as Node)) return + setOpenTagsKey(null) + } + + document.addEventListener('keydown', onKeyDown) + document.addEventListener('pointerdown', onPointerDown) + return () => { + document.removeEventListener('keydown', onKeyDown) + document.removeEventListener('pointerdown', onPointerDown) + } + }, [openTagsKey]) + + React.useEffect(() => { + if (!openTagsKey) return + // Falls Job aus der Liste verschwindet → Popover schließen + const exists = rows.some((j) => keyFor(j) === openTagsKey) + if (!exists) setOpenTagsKey(null) + }, [rows, keyFor, openTagsKey]) + + const parseTags = (raw?: string): string[] => { + const s = String(raw ?? '').trim() + if (!s) return [] + const parts = s + .split(/[\n,;|]+/g) + .map((p) => p.trim()) + .filter(Boolean) + + const seen = new Set() + const out: string[] = [] + for (const p of parts) { + const k = p.toLowerCase() + if (seen.has(k)) continue + seen.add(k) + out.push(p) + } + return out + } + return ( -
- {rows.map((j) => { - const k = keyFor(j) - const model = modelNameFromOutput(j.output) - const modelKey = lower(model) - const flags = modelsByKey[modelKey] - const isFav = Boolean(flags?.favorite) - const isLiked = flags?.liked === true - const file = baseName(j.output || '') - const isHot = file.startsWith('HOT ') - const dur = runtimeOf(j) - const size = formatBytes(sizeBytesOf(j)) - const statusCls = - j.status === 'failed' - ? 'bg-red-500/35' - : j.status === 'finished' - ? 'bg-emerald-500/35' - : j.status === 'stopped' - ? 'bg-amber-500/35' - : 'bg-black/40' + <> +
+ {rows.map((j) => { + const k = keyFor(j) + // Sound nur bei Hover auf genau diesem Teaser + const allowSound = Boolean(teaserAudio) && hoverTeaserKey === k + const previewMuted = !allowSound - const busy = deletingKeys.has(k) || keepingKeys.has(k) || removingKeys.has(k) - const deleted = deletedKeys.has(k) + const model = modelNameFromOutput(j.output) + const modelKey = lower(model) + const flags = modelsByKey[modelKey] + const isFav = Boolean(flags?.favorite) + const isLiked = flags?.liked === true + const isWatching = Boolean(flags?.watching) + const tags = parseTags(flags?.tags) + const showTags = tags.slice(0, 6) + const restTags = tags.length - showTags.length + const fullTags = tags.join(', ') - return ( -
onOpenPlayer(j)} - onKeyDown={(e) => { - if (e.key === 'Enter' || e.key === ' ') onOpenPlayer(j) - }} - > - {/* Thumb */} + const file = baseName(j.output || '') + const isHot = file.startsWith('HOT ') + const dur = runtimeOf(j) + const size = formatBytes(sizeBytesOf(j)) + + const busy = deletingKeys.has(k) || keepingKeys.has(k) || removingKeys.has(k) + const deleted = deletedKeys.has(k) + + return (
onOpenPlayer(j)} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onOpenPlayer(j) + }} > - stripHotPrefix(baseName(p))} - durationSeconds={durations[k]} - onDuration={handleDuration} - variant="fill" - showPopover={false} - blur={blurPreviews} - animated={true} - animatedMode="teaser" - animatedTrigger="always" - clipSeconds={1} - thumbSamples={18} - /> - - {/* Gradient overlay bottom */} + {/* Thumb */}
- - {/* Bottom overlay meta (Status links, Dauer+Größe rechts) */} -
onHoverPreviewKeyChange?.(k)} + onMouseLeave={() => onHoverPreviewKeyChange?.(null)} > -
- - {j.status} - + {/* ✅ Clip nur Media + Bottom-Overlays (nicht das Menü) */} +
+ } + className="absolute inset-0" + > + stripHotPrefix(baseName(p))} + durationSeconds={durations[k] ?? (j as any)?.durationSeconds} + onDuration={handleDuration} + variant="fill" + showPopover={false} + blur={blurPreviews} + animated={teaserPlayback === 'all' ? true : teaserPlayback === 'hover' ? teaserKey === k : false} + animatedMode="teaser" + animatedTrigger="always" + clipSeconds={1} + thumbSamples={18} + muted={previewMuted} + popoverMuted={previewMuted} + /> + -
- {dur} - {size} + {/* Gradient overlay bottom */} +
+ + {/* Bottom overlay meta */} +
+
+ {/* Left: File + Status unten links */} +
+
+ + {j.status} + +
+
+ + {/* Right bottom: Duration + Size */} +
+ {dur} + {size} +
+
-
- {/* Quick actions (top-right, wie Cards) */} -
- {(() => { - const iconBtn = - 'pointer-events-auto inline-flex items-center justify-center rounded-md bg-black/40 p-2 text-white ' + - 'backdrop-blur hover:bg-black/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500 ' + - 'disabled:opacity-50 disabled:cursor-not-allowed' - - return ( - <> - {/* Favorite */} - {onToggleFavorite ? ( - - ) : null} - - {/* Like */} - {onToggleLike ? ( - - ) : null} - - - - - - - - ) - })()} -
-
- - {/* Footer / Meta (wie CardView) */} -
- {/* Model + Datei im Footer */} -
-
- {model} -
-
- {isLiked ? : null} - {isFav ? : null} + {/* Actions (top-right) */} +
e.stopPropagation()} + > +
-
- {stripHotPrefix(file) || '—'} + {/* Footer / Meta */} +
+
+
{model}
+
+ {isWatching ? : null} + {isLiked ? : null} + {isFav ? : null} +
+
- {isHot ? ( - - HOT - - ) : null} +
+ {stripHotPrefix(file) || '—'} + + {isHot ? ( + + HOT + + ) : null} +
+ + {/* Tags: 1 Zeile, +N öffnet Popover */} +
e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + > + {/* links: Tags (nowrap, werden ggf. geclippt) */} +
+
+ {showTags.length > 0 ? ( + showTags.map((t) => ( + + )) + ) : ( + + )} +
+
+ + {/* rechts: Rest-Count immer sichtbar + klickbar */} + {restTags > 0 ? ( + + ) : null} + + {/* Popover */} + {openTagsKey === k ? ( +
e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + > +
+
Tags
+ +
+ +
+
+ {tags.map((t) => ( + + ))} +
+
+
+ ) : null} +
-
- ) - })} -
+ ) + })} +
+ ) } diff --git a/frontend/src/components/ui/FinishedDownloadsTableView.tsx b/frontend/src/components/ui/FinishedDownloadsTableView.tsx index 4a6999c..f8a1216 100644 --- a/frontend/src/components/ui/FinishedDownloadsTableView.tsx +++ b/frontend/src/components/ui/FinishedDownloadsTableView.tsx @@ -1,6 +1,7 @@ +// frontend\src\components\ui\FinishedDownloadsTableView.tsx + 'use client' -import * as React from 'react' import Table, { type Column, type SortState } from './Table' import type { RecordJob } from '../../types' @@ -31,7 +32,8 @@ export default function FinishedDownloadsTableView({ striped fullWidth stickyHeader - compact + compact={false} + card sort={sort} onSortChange={onSortChange} onRowClick={onRowClick} diff --git a/frontend/src/components/ui/FinishedVideoPreview.tsx b/frontend/src/components/ui/FinishedVideoPreview.tsx index 6f3282a..beed3a4 100644 --- a/frontend/src/components/ui/FinishedVideoPreview.tsx +++ b/frontend/src/components/ui/FinishedVideoPreview.tsx @@ -20,7 +20,6 @@ export type FinishedVideoPreviewProps = { animated?: boolean animatedMode?: AnimatedMode animatedTrigger?: AnimatedTrigger - active?: boolean /** nur für frames */ autoTickMs?: number @@ -70,8 +69,6 @@ export default function FinishedVideoPreview({ animated = false, animatedMode = 'frames', animatedTrigger = 'always', - active, - autoTickMs = 15000, thumbStepSec, thumbSpread, @@ -107,10 +104,15 @@ export default function FinishedVideoPreview({ const [videoOk, setVideoOk] = useState(true) const [metaLoaded, setMetaLoaded] = useState(false) + const [teaserReady, setTeaserReady] = useState(false) + // inView (Viewport) const rootRef = useRef(null) const [inView, setInView] = useState(false) + // ✅ NEU: sobald einmal im Viewport gewesen -> true (damit wir danach nicht wieder entladen) + const [everInView, setEverInView] = useState(false) + // Tick nur für frames-Mode const [localTick, setLocalTick] = useState(0) @@ -139,9 +141,6 @@ export default function FinishedVideoPreview({ [file] ) - // ✅ Teaser-Video (vorgerendert) - const isActive = active !== undefined ? Boolean(active) : true - const hasDuration = typeof durationSeconds === 'number' && Number.isFinite(durationSeconds) && durationSeconds > 0 @@ -162,6 +161,10 @@ export default function FinishedVideoPreview({ } catch {} } + useEffect(() => { + setTeaserReady(false) + }, [previewId, assetNonce]) + useEffect(() => { const onRelease = (ev: any) => { const f = String(ev?.detail?.file ?? '') @@ -184,9 +187,17 @@ export default function FinishedVideoPreview({ if (!el) return const obs = new IntersectionObserver( - (entries) => setInView(Boolean(entries[0]?.isIntersecting)), - { threshold: 0.1 } + (entries) => { + const hit = Boolean(entries[0]?.isIntersecting) + setInView(hit) + if (hit) setEverInView(true) // ✅ NEU + }, + { + threshold: 0.01, + rootMargin: '350px 0px', // ✅ lädt erst "bei Bedarf", aber schon etwas vor dem Viewport + } ) + obs.observe(el) return () => obs.disconnect() }, []) @@ -281,6 +292,9 @@ export default function FinishedVideoPreview({ inlineMode === 'hover' || (animated && (animatedMode === 'clips' || animatedMode === 'teaser') && animatedTrigger === 'hover') + // ✅ Nur dann echte Asset-Requests auslösen, wenn wir sie brauchen + const shouldLoadAssets = everInView || (wantsHover && hovered) + // --- Legacy "clips" Logik (wenn du es noch nutzt) const clipTimes = useMemo(() => { if (!animated) return [] @@ -308,6 +322,28 @@ export default function FinishedVideoPreview({ const clipIdxRef = useRef(0) const clipStartRef = useRef(0) + useEffect(() => { + const v = teaserMp4Ref.current + if (!v) return + + const active = teaserActive && animatedMode === 'teaser' + if (!active) { + try { v.pause() } catch {} + return + } + + // iOS/Safari: Eigenschaften wirklich als Properties setzen + v.muted = Boolean(muted) + // @ts-ignore + v.defaultMuted = Boolean(muted) + v.playsInline = true + v.setAttribute('playsinline', '') + v.setAttribute('webkit-playsinline', '') + + const p = v.play?.() + if (p && typeof (p as any).catch === 'function') (p as Promise).catch(() => {}) + }, [teaserActive, animatedMode, teaserSrc, muted]) + // Legacy: "clips" spielt 1s Segmente aus dem Vollvideo per seek useEffect(() => { const v = teaserRef.current @@ -371,71 +407,90 @@ export default function FinishedVideoPreview({ onBlur={wantsHover ? () => setHovered(false) : undefined} > {/* 1) Inline Full Video (mit Controls) */} + {/* ✅ Thumb IMMER als Fallback/Background */} + {shouldLoadAssets && thumbSrc && thumbOk ? ( + {file} setThumbOk(false)} + /> + ) : ( +
+ )} + + {/* ✅ Inline Full Video (nur wenn sichtbar/aktiv) */} {showingInlineVideo ? (
r.id} - striped - fullWidth - onRowClick={onOpenPlayer} - /> - - - )} - - ) -} diff --git a/frontend/src/components/ui/SwipeCard.tsx b/frontend/src/components/ui/SwipeCard.tsx index 5d96374..08911ba 100644 --- a/frontend/src/components/ui/SwipeCard.tsx +++ b/frontend/src/components/ui/SwipeCard.tsx @@ -1,3 +1,5 @@ +// frontend\src\components\ui\SwipeCard.tsx + 'use client' import * as React from 'react' @@ -58,6 +60,13 @@ export type SwipeCardProps = { */ ignoreSelector?: string + /** + * Optional: CSS-Selector, bei dem ein "Tap" NICHT onTap() auslösen soll. + * (z.B. Buttons/Inputs innerhalb der Karte) + */ + tapIgnoreSelector?: string + + } export type SwipeCardHandle = { @@ -93,31 +102,49 @@ const SwipeCard = React.forwardRef(function Swi ), className: 'bg-red-500/20 text-red-800 dark:bg-red-500/15 dark:text-red-300', }, - thresholdPx = 120, - thresholdRatio = 0.35, + //thresholdPx = 120, + thresholdPx = 180, + //thresholdRatio = 0.35, + thresholdRatio = 0.1, ignoreFromBottomPx = 72, ignoreSelector = '[data-swipe-ignore]', snapMs = 180, commitMs = 180, + tapIgnoreSelector = 'button,a,input,textarea,select,video[controls],video[controls] *,[data-tap-ignore]', }, ref ) { const cardRef = React.useRef(null) + // ✅ Perf: dx pro Frame updaten (statt pro Pointer-Move) + const dxRef = React.useRef(0) + const rafRef = React.useRef(null) + + // ✅ Perf: Threshold einmal pro PointerDown berechnen (kein offsetWidth pro Move) + const thresholdRef = React.useRef(0) + const pointer = React.useRef<{ id: number | null x: number y: number dragging: boolean captured: boolean - }>({ id: null, x: 0, y: 0, dragging: false, captured: false }) + tapIgnored: boolean + }>({ id: null, x: 0, y: 0, dragging: false, captured: false, tapIgnored: false }) const [dx, setDx] = React.useState(0) const [armedDir, setArmedDir] = React.useState(null) const [animMs, setAnimMs] = React.useState(0) const reset = React.useCallback(() => { + // ✅ rAF cleanup + if (rafRef.current != null) { + cancelAnimationFrame(rafRef.current) + rafRef.current = null + } + dxRef.current = 0 + setAnimMs(snapMs) setDx(0) setArmedDir(null) @@ -126,13 +153,21 @@ const SwipeCard = React.forwardRef(function Swi const commit = React.useCallback( async (dir: 'left' | 'right', runAction: boolean) => { + + if (rafRef.current != null) { + cancelAnimationFrame(rafRef.current) + rafRef.current = null + } + const el = cardRef.current const w = el?.offsetWidth || 360 // rausfliegen lassen setAnimMs(commitMs) setArmedDir(dir === 'right' ? 'right' : 'left') - setDx(dir === 'right' ? w + 40 : -(w + 40)) + const outDx = dir === 'right' ? w + 40 : -(w + 40) + dxRef.current = outDx + setDx(outDx) let ok: boolean | void = true if (runAction) { @@ -200,18 +235,51 @@ const SwipeCard = React.forwardRef(function Swi ref={cardRef} className="relative" style={{ - transform: `translateX(${dx}px)`, + // ✅ iOS Fix: kein transform im Idle-Zustand, sonst sind Video-Controls oft nicht tappbar + transform: dx !== 0 ? `translate3d(${dx}px,0,0)` : undefined, transition: animMs ? `transform ${animMs}ms ease` : undefined, - touchAction: 'pan-y', // wichtig: vertikales Scrollen zulassen + touchAction: 'pan-y', + willChange: dx !== 0 ? 'transform' : undefined, }} onPointerDown={(e) => { if (!enabled || disabled) return // ✅ 1) Ignoriere Start auf "No-swipe"-Elementen const target = e.target as HTMLElement | null + const tapIgnored = Boolean(tapIgnoreSelector && target?.closest?.(tapIgnoreSelector)) + if (ignoreSelector && target?.closest?.(ignoreSelector)) return - // ✅ 2) Ignoriere Start im unteren Bereich (z.B. Video-Controls/Progressbar) + const root = e.currentTarget as HTMLElement + const videos = Array.from(root.querySelectorAll('video')) as HTMLVideoElement[] + const ctlVideo = videos.find((v) => v.controls) + + if (ctlVideo) { + const vr = ctlVideo.getBoundingClientRect() + + const inVideo = + e.clientX >= vr.left && + e.clientX <= vr.right && + e.clientY >= vr.top && + e.clientY <= vr.bottom + + if (inVideo) { + // unten frei für Timeline/Scrub (iPhone braucht meist etwas mehr) + const fromBottomVideo = vr.bottom - e.clientY + const scrubZonePx = 72 + if (fromBottomVideo <= scrubZonePx) return + + // Swipe nur aus den Seitenrändern + const edgeZonePx = 64 + const xFromLeft = e.clientX - vr.left + const xFromRight = vr.right - e.clientX + const inEdge = xFromLeft <= edgeZonePx || xFromRight <= edgeZonePx + + if (!inEdge) return + } + } + + // ✅ 3) Optional: generelle Card-Bottom-Sperre (bei dir in CardsView auf 0 lassen) const rect = (e.currentTarget as HTMLElement).getBoundingClientRect() const fromBottom = rect.bottom - e.clientY if (ignoreFromBottomPx && fromBottom <= ignoreFromBottomPx) return @@ -222,7 +290,17 @@ const SwipeCard = React.forwardRef(function Swi y: e.clientY, dragging: false, captured: false, + tapIgnored, // ✅ WICHTIG: nicht "false" } + + // ✅ Perf: pro Gesture einmal Threshold berechnen + const el = cardRef.current + const w = el?.offsetWidth || 360 + thresholdRef.current = Math.min(thresholdPx, w * thresholdRatio) + + // ✅ dxRef reset (neue Gesture) + dxRef.current = 0 + }} onPointerMove={(e) => { @@ -246,6 +324,9 @@ const SwipeCard = React.forwardRef(function Swi // ✅ jetzt erst beginnen wir zu swipen pointer.current.dragging = true + // ✅ Anim nur 1x beim Drag-Start deaktivieren + setAnimMs(0) + // ✅ Pointer-Capture erst JETZT (nicht bei pointerdown) try { ;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId) @@ -255,25 +336,31 @@ const SwipeCard = React.forwardRef(function Swi } } - setAnimMs(0) - setDx(ddx) + // ✅ dx nur pro Frame in React-State schreiben + dxRef.current = ddx - const el = cardRef.current - const w = el?.offsetWidth || 360 - const threshold = Math.min(thresholdPx, w * thresholdRatio) - setArmedDir(ddx > threshold ? 'right' : ddx < -threshold ? 'left' : null) + if (rafRef.current == null) { + rafRef.current = requestAnimationFrame(() => { + rafRef.current = null + setDx(dxRef.current) + }) + } + + // ✅ armedDir nur updaten wenn geändert + const threshold = thresholdRef.current + const nextDir = ddx > threshold ? 'right' : ddx < -threshold ? 'left' : null + setArmedDir((prev) => (prev === nextDir ? prev : nextDir)) }} onPointerUp={(e) => { if (!enabled || disabled) return if (pointer.current.id !== e.pointerId) return - const el = cardRef.current - const w = el?.offsetWidth || 360 - const threshold = Math.min(thresholdPx, w * thresholdRatio) + const threshold = thresholdRef.current || Math.min(thresholdPx, (cardRef.current?.offsetWidth || 360) * thresholdRatio) const wasDragging = pointer.current.dragging const wasCaptured = pointer.current.captured + const wasTapIgnored = pointer.current.tapIgnored pointer.current.id = null pointer.current.dragging = false @@ -287,18 +374,38 @@ const SwipeCard = React.forwardRef(function Swi } if (!wasDragging) { + // ✅ Wichtig: Wenn Tap auf Video/Controls (tapIgnored), NICHT resetten + // sonst “stiehlt” SwipeCard den Tap (iOS besonders empfindlich). + if (wasTapIgnored) { + setAnimMs(0) + setDx(0) + setArmedDir(null) + return + } + reset() onTap?.() return } - if (dx > threshold) { + const finalDx = dxRef.current + + // rAF cleanup + if (rafRef.current != null) { + cancelAnimationFrame(rafRef.current) + rafRef.current = null + } + + if (finalDx > threshold) { void commit('right', true) - } else if (dx < -threshold) { + } else if (finalDx < -threshold) { void commit('left', true) } else { reset() } + + dxRef.current = 0 + }} onPointerCancel={(e) => { if (!enabled || disabled) return @@ -307,7 +414,13 @@ const SwipeCard = React.forwardRef(function Swi ;(e.currentTarget as HTMLElement).releasePointerCapture(pointer.current.id) } catch {} } - pointer.current = { id: null, x: 0, y: 0, dragging: false, captured: false } + pointer.current = { id: null, x: 0, y: 0, dragging: false, captured: false, tapIgnored: false } + if (rafRef.current != null) { + cancelAnimationFrame(rafRef.current) + rafRef.current = null + } + dxRef.current = 0 + reset() }} > diff --git a/frontend/src/components/ui/TagBadge.tsx b/frontend/src/components/ui/TagBadge.tsx new file mode 100644 index 0000000..5513de0 --- /dev/null +++ b/frontend/src/components/ui/TagBadge.tsx @@ -0,0 +1,99 @@ +'use client' + +import * as React from 'react' +import clsx from 'clsx' + +type Props = { + /** Entweder tag ODER children nutzen (tag ist praktisch, wenn du onClick nutzt). */ + tag?: string + children?: React.ReactNode + + title?: string + + /** Wenn aktiv (z.B. in Filter), etwas "stärker" highlighten */ + active?: boolean + + /** Wenn gesetzt, wird ein + ) +} diff --git a/frontend/src/components/ui/ToastProvider.tsx b/frontend/src/components/ui/ToastProvider.tsx new file mode 100644 index 0000000..b26c1c7 --- /dev/null +++ b/frontend/src/components/ui/ToastProvider.tsx @@ -0,0 +1,211 @@ +'use client' + +import * as React from 'react' +import { Transition } from '@headlessui/react' +import { + CheckCircleIcon, + XCircleIcon, + InformationCircleIcon, + ExclamationTriangleIcon, +} from '@heroicons/react/24/outline' +import { XMarkIcon } from '@heroicons/react/20/solid' + +type ToastType = 'success' | 'error' | 'info' | 'warning' + +export type Toast = { + id: string + type: ToastType + title?: string + message?: string + durationMs?: number // auto close +} + +type ToastContextValue = { + push: (t: Omit) => string + remove: (id: string) => void + clear: () => void +} + +const ToastContext = React.createContext(null) + +function iconFor(type: ToastType) { + switch (type) { + case 'success': + return { Icon: CheckCircleIcon, cls: 'text-emerald-500' } + case 'error': + return { Icon: XCircleIcon, cls: 'text-rose-500' } + case 'warning': + return { Icon: ExclamationTriangleIcon, cls: 'text-amber-500' } + default: + return { Icon: InformationCircleIcon, cls: 'text-sky-500' } + } +} + +function borderFor(type: ToastType) { + switch (type) { + case 'success': + return 'border-emerald-200/70 dark:border-emerald-400/20' + case 'error': + return 'border-rose-200/70 dark:border-rose-400/20' + case 'warning': + return 'border-amber-200/70 dark:border-amber-400/20' + default: + return 'border-sky-200/70 dark:border-sky-400/20' + } +} + +function titleDefault(type: ToastType) { + switch (type) { + case 'success': + return 'Erfolg' + case 'error': + return 'Fehler' + case 'warning': + return 'Hinweis' + default: + return 'Info' + } +} + +function uid() { + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}` +} + +export function ToastProvider({ + children, + maxToasts = 3, + defaultDurationMs = 3500, + position = 'bottom-right', +}: { + children: React.ReactNode + maxToasts?: number + defaultDurationMs?: number + position?: 'bottom-right' | 'top-right' | 'bottom-left' | 'top-left' +}) { + const [toasts, setToasts] = React.useState([]) + + const remove = React.useCallback((id: string) => { + setToasts((prev) => prev.filter((t) => t.id !== id)) + }, []) + + const clear = React.useCallback(() => setToasts([]), []) + + const push = React.useCallback( + (t: Omit) => { + const id = uid() + const durationMs = t.durationMs ?? defaultDurationMs + + setToasts((prev) => { + const next = [{ ...t, id, durationMs }, ...prev] + return next.slice(0, Math.max(1, maxToasts)) + }) + + if (durationMs && durationMs > 0) { + window.setTimeout(() => remove(id), durationMs) + } + + return id + }, + [defaultDurationMs, maxToasts, remove] + ) + + const ctx = React.useMemo(() => ({ push, remove, clear }), [push, remove, clear]) + + const posCls = + position === 'top-right' + ? 'items-start sm:items-start sm:justify-start' + : position === 'top-left' + ? 'items-start sm:items-start sm:justify-start' + : position === 'bottom-left' + ? 'items-end sm:items-end sm:justify-end' + : 'items-end sm:items-end sm:justify-end' + + const alignCls = + position.endsWith('left') + ? 'sm:items-start' + : 'sm:items-end' + + const insetCls = + position.startsWith('top') + ? 'top-0 bottom-auto' + : 'bottom-0 top-auto' + + return ( + + {children} + + {/* Live region */} +
+
+
+ {toasts.map((t) => { + const { Icon, cls } = iconFor(t.type) + const title = (t.title || '').trim() || titleDefault(t.type) + const msg = (t.message || '').trim() + + return ( + +
+
+
+
+
+ +
+

+ {title} +

+ {msg ? ( +

+ {msg} +

+ ) : null} +
+ + +
+
+
+
+ ) + })} +
+
+
+
+ ) +} + +export function useToast() { + const ctx = React.useContext(ToastContext) + if (!ctx) throw new Error('useToast must be used within ') + return ctx +} diff --git a/frontend/src/components/ui/WaitingModelsTable.tsx b/frontend/src/components/ui/WaitingModelsTable.tsx deleted file mode 100644 index 18f2566..0000000 --- a/frontend/src/components/ui/WaitingModelsTable.tsx +++ /dev/null @@ -1,91 +0,0 @@ -// WaitingModelsTable.tsx -'use client' - -import { useMemo } from 'react' -import Table, { type Column } from './Table' - -export type WaitingModelRow = { - id: string - modelKey: string - url: string - currentShow?: string // public / private / hidden / away / unknown -} - -type Props = { - models: WaitingModelRow[] -} - -export default function WaitingModelsTable({ models }: Props) { - const columns = useMemo[]>(() => { - return [ - { - key: 'model', - header: 'Model', - cell: (m) => ( - - {m.modelKey} - - ), - }, - { - key: 'status', - header: 'Status', - cell: (m) => {m.currentShow || 'unknown'}, - }, - { - key: 'open', - header: 'Öffnen', - srOnlyHeader: true, - align: 'right', - cell: (m) => ( - e.stopPropagation()} - > - Öffnen - - ), - }, - ] - }, []) - - if (models.length === 0) return null - - return ( - <> - {/* ✅ Mobile: kompakte Liste */} -
- {models.map((m) => ( -
-
-
{m.modelKey}
-
- Status: {m.currentShow || 'unknown'} -
-
- - - Öffnen - -
- ))} -
- - {/* ✅ Desktop/Tablet: Tabelle */} -
-
r.id} striped fullWidth /> - - - ) -} diff --git a/frontend/src/components/ui/notify.ts b/frontend/src/components/ui/notify.ts new file mode 100644 index 0000000..e96abc6 --- /dev/null +++ b/frontend/src/components/ui/notify.ts @@ -0,0 +1,22 @@ +'use client' + +import type { Toast } from './ToastProvider' +import { useToast } from './ToastProvider' + +// Hook-Wrapper (komfortabel) +export function useNotify() { + const { push, remove, clear } = useToast() + + const base = (type: Toast['type']) => (title: string, message?: string, opts?: Partial>) => + push({ type, title, message, ...opts }) + + return { + push, + remove, + clear, + success: base('success'), + error: base('error'), + info: base('info'), + warning: base('warning'), + } +} diff --git a/frontend/src/lib/chaturbateOnlinePoller.ts b/frontend/src/lib/chaturbateOnlinePoller.ts new file mode 100644 index 0000000..e0c8595 --- /dev/null +++ b/frontend/src/lib/chaturbateOnlinePoller.ts @@ -0,0 +1,174 @@ +// frontend/src/lib/chaturbateOnlinePoller.ts + +export type ChaturbateOnlineRoom = { + username?: string + current_show?: string + chat_room_url?: string + image_url?: string +} + +export type ChaturbateOnlineResponse = { + enabled: boolean + rooms: ChaturbateOnlineRoom[] +} + +type OnlineState = ChaturbateOnlineResponse + +function chunk(arr: T[], size: number): T[][] { + const out: T[][] = [] + for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size)) + return out +} + +function dedupeRooms(rooms: ChaturbateOnlineRoom[]): ChaturbateOnlineRoom[] { + const seen = new Set() + const out: ChaturbateOnlineRoom[] = [] + for (const r of rooms) { + const u = String(r?.username ?? '').trim().toLowerCase() + if (!u || seen.has(u)) continue + seen.add(u) + out.push(r) + } + return out +} + +export function startChaturbateOnlinePolling(opts: { + getModels: () => string[] + getShow: () => string[] + onData: (data: OnlineState) => void + intervalMs?: number + /** Optional: wird bei Fehlern aufgerufen (für Debug) */ + onError?: (err: unknown) => void +}) { + const baseIntervalMs = opts.intervalMs ?? 5000 + + let timer: number | null = null + let inFlight: AbortController | null = null + let lastKey = '' + let lastResult: OnlineState | null = null + let stopped = false + + const clearTimer = () => { + if (timer != null) { + window.clearTimeout(timer) + timer = null + } + } + + const closeInFlight = () => { + if (inFlight) { + try { + inFlight.abort() + } catch {} + inFlight = null + } + } + + const schedule = (ms: number) => { + if (stopped) return + clearTimer() + timer = window.setTimeout(() => void tick(), ms) + } + + const tick = async () => { + if (stopped) return + + try { + const models = (opts.getModels?.() ?? []) + .map((x) => String(x || '').trim()) + .filter(Boolean) + + const showRaw = (opts.getShow?.() ?? []) + .map((x) => String(x || '').trim()) + .filter(Boolean) + + // stabilisieren + const show = showRaw.slice().sort() + const modelsSorted = models.slice().sort() + + // keine Models -> rooms leeren (enabled nicht neu erfinden) + if (modelsSorted.length === 0) { + closeInFlight() + + const empty: OnlineState = { enabled: lastResult?.enabled ?? false, rooms: [] } + lastResult = empty + opts.onData(empty) + + // hidden tab -> seltener pollen + const nextMs = document.hidden ? Math.max(15000, baseIntervalMs) : baseIntervalMs + schedule(nextMs) + return + } + + const key = `${show.join(',')}|${modelsSorted.join(',')}` + const requestKey = key + lastKey = key + + // dedupe / cancel previous + closeInFlight() + const controller = new AbortController() + inFlight = controller + + // ✅ Wichtig: "keepalive" NICHT setzen (kann Ressourcen kosten) + const CHUNK_SIZE = 350 // wenn du extrem viele Keys hast: 200–300 nehmen + const parts = chunk(modelsSorted, CHUNK_SIZE) + + let mergedRooms: ChaturbateOnlineRoom[] = [] + let mergedEnabled = false + let hadAnyOk = false + + for (const part of parts) { + if (controller.signal.aborted) return + if (requestKey !== lastKey) return + if (stopped) return + + const res = await fetch('/api/chaturbate/online', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ q: part, show, refresh: false }), + signal: controller.signal, + cache: 'no-store', + }) + + if (!res.ok) continue + + hadAnyOk = true + const data = (await res.json()) as OnlineState + mergedEnabled = mergedEnabled || Boolean(data?.enabled) + mergedRooms.push(...(Array.isArray(data?.rooms) ? data.rooms : [])) + } + + if (!hadAnyOk) { + const nextMs = document.hidden ? Math.max(15000, baseIntervalMs) : baseIntervalMs + schedule(nextMs) + return + } + + const merged: OnlineState = { enabled: mergedEnabled, rooms: dedupeRooms(mergedRooms) } + + if (controller.signal.aborted) return + if (requestKey !== lastKey) return + if (stopped) return + + lastResult = merged + opts.onData(merged) + } catch (e: any) { + if (e?.name === 'AbortError') return + opts.onError?.(e) + } finally { + // ✅ adaptive backoff: hidden tab = viel seltener pollen + const nextMs = document.hidden ? Math.max(15000, baseIntervalMs) : baseIntervalMs + schedule(nextMs) + } + } + + // sofort einmal + void tick() + + // stop function + return () => { + stopped = true + clearTimer() + closeInFlight() + } +} diff --git a/frontend/src/lib/sseSingleton.ts b/frontend/src/lib/sseSingleton.ts new file mode 100644 index 0000000..2b4849c --- /dev/null +++ b/frontend/src/lib/sseSingleton.ts @@ -0,0 +1,144 @@ +// frontend/src/lib/sseSingleton.ts +type Handler = (data: T) => void + +type Stream = { + url: string + es: EventSource | null + refs: number + listeners: Map> + dispatchers: Map void> +} + +const streams = new Map() +let visHookInstalled = false + +function ensureVisHook() { + if (visHookInstalled) return + visHookInstalled = true + + document.addEventListener('visibilitychange', () => { + if (document.hidden) { + // Tab hidden -> alle Streams schließen + for (const s of streams.values()) { + if (s.es) { + s.es.close() + s.es = null + s.dispatchers.clear() + } + } + } else { + // Tab visible -> Streams mit refs>0 wieder öffnen + for (const s of streams.values()) { + if (s.refs > 0 && !s.es) openStream(s) + } + } + }) +} + +function openStream(s: Stream) { + if (s.es) return + if (document.hidden) return + + s.es = new EventSource(s.url) + + // pro eventName genau EIN dispatcher registrieren + for (const [eventName, set] of s.listeners.entries()) { + const dispatcher = (ev: MessageEvent) => { + let data: any = null + try { + data = JSON.parse(String(ev.data ?? 'null')) + } catch { + // ignore + return + } + for (const fn of set) fn(data) + } + s.dispatchers.set(eventName, dispatcher) + s.es.addEventListener(eventName, dispatcher as any) + } + + s.es.onerror = () => { + // EventSource reconnectet selbst. + // Bei Server-Restart kann es sinnvoll sein, kurz zu schließen -> Browser baut neu auf. + // (optional) + } +} + +function closeStream(s: Stream) { + if (!s.es) return + s.es.close() + s.es = null + s.dispatchers.clear() +} + +function getStream(url: string): Stream { + let s = streams.get(url) + if (!s) { + s = { + url, + es: null, + refs: 0, + listeners: new Map(), + dispatchers: new Map(), + } + streams.set(url, s) + } + return s +} + +/** + * Subscribe auf SSE JSON Events. + * - öffnet pro URL genau eine EventSource (pro Tab) + * - schließt automatisch, wenn kein Subscriber mehr da ist + * - pausiert in hidden Tabs + */ +export function subscribeSSE(url: string, eventName: string, handler: Handler) { + ensureVisHook() + const s = getStream(url) + + let set = s.listeners.get(eventName) + if (!set) { + set = new Set() + s.listeners.set(eventName, set) + } + set.add(handler as Handler) + + s.refs += 1 + + // wenn Stream schon offen: ggf. Listener an EventSource nachrüsten + if (s.es) { + if (!s.dispatchers.has(eventName)) { + const dispatcher = (ev: MessageEvent) => { + let data: any = null + try { + data = JSON.parse(String(ev.data ?? 'null')) + } catch { + return + } + for (const fn of s.listeners.get(eventName) ?? []) fn(data) + } + s.dispatchers.set(eventName, dispatcher) + s.es.addEventListener(eventName, dispatcher as any) + } + } else { + openStream(s) + } + + return () => { + const s2 = streams.get(url) + if (!s2) return + + const set2 = s2.listeners.get(eventName) + if (set2) { + set2.delete(handler as Handler) + if (set2.size === 0) s2.listeners.delete(eventName) + } + + s2.refs = Math.max(0, s2.refs - 1) + + if (s2.refs === 0) { + closeStream(s2) + streams.delete(url) + } + } +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index bef5202..631fc78 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -2,9 +2,12 @@ import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' import App from './App.tsx' +import { ToastProvider } from './components/ui/ToastProvider.tsx' createRoot(document.getElementById('root')!).render( - + + + , ) diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 899b31c..c250cbc 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -2,16 +2,26 @@ export type RecordJob = { id: string - sourceUrl: string + sourceUrl?: string output: string status: 'running' | 'finished' | 'failed' | 'stopped' startedAt: string endedAt?: string + + // ✅ kommt aus dem Backend bei done-list (und ggf. später auch live) + durationSeconds?: number + sizeBytes?: number + + // ✅ wird fürs UI genutzt (Stop/Finalize Fortschritt) + phase?: string + progress?: number + exitCode?: number error?: string logTail?: string } + export type ParsedModel = { input: string isUrl: boolean @@ -19,3 +29,24 @@ export type ParsedModel = { path?: string modelKey: string } + +export type Model = { + id: string + input: string + isUrl: boolean + host?: string + path?: string + key: string + + tags?: string + + watching?: boolean + favorite?: boolean + hot?: boolean + keep?: boolean + liked?: boolean | null + + createdAt?: string + updatedAt?: string + lastStream?: string +} diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index aa1f025..294a1e1 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -16,6 +16,10 @@ export default defineConfig({ target: 'http://10.0.1.25:9999', changeOrigin: true, }, + '/generated': { + target: 'http://localhost:9999', + changeOrigin: true, + }, }, }, })